How to code the projectile of a ball of different force and angle in Java Swing?

后端 未结 3 554
眼角桃花
眼角桃花 2020-12-01 20:36

I have written the following function for projectile motion of different force and angle, but it doesn\'t work properly. Where have I gone wrong? I want something like the A

3条回答
  •  無奈伤痛
    2020-12-01 21:24

    Quite important to notice: in Java (like in many other languages) position (0, 0) in your image is the top left corner. So to simulate your object "fall down" you actually need to increase its Y coordinate (and check if it already "hit the ground" -> if (position.Y == GROUND) stop();). Also the starting position is not (0, 0) but (0, startingY).

    Apart from this, my recommendation is:

    1. store current position of a ball in a seperate structure (could be simply 2 variables, x and y.)
    2. let your velocity consist of two elements: velocity in direction of X and velocity in direction of Y.
    3. create a move method, which would change current position according to velocity.

    Note that your x coordinate changes in a constant maner, so your velocity.X would be constant and could be calculated at the start. Then, your velocity.Y should change with time: you calculate it's initial value and then substract a gravity-related amount (also constant) from it in every iteration. The move method could look like this:

    public void move(Position position, Velocity velocity) {
        position.X += velocity.X;
        position.Y += velocity.Y;
        velocity.Y -= ACCELERATION*TIME;    //TIME is time between calls of move(), approximate.
    }
    

    Of course this is a very simple example, but I guess it gives the idea. Note that both TIME and ACCELERATION are constant inside the simulation, as TIME is not time elapsed from the start, but time elapsed from the previous move call. Remember the notice from the top of this answer. Also: initialize your velocity and position correctly, like this:

    position.X = startingX;    //the leftmost pixel of the screen is 0, of course.
    position.Y = startingY;    //the "ground level" of your simulation is probably NOT 0.
    velocity.X = speed*Math.cos(throwAngle);
    velocity.Y = speed*Math.sin(throwAngle);
    

    Where speed is just an int (the length of your velocity vector at the start.)

提交回复
热议问题