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
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:
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.)