I am dealing with a similar problem like yours. (I have an arraylist holding a history of the positions that my player left, and I want to use this to rewind the game.) Instead of simply increasing the x and y position with 1, you can:
- Calculate the angle between the starting position and the destination of the position.
- Calculate a new direction using a variable that represents speed
- Update your position using calculated direction
I made a class of this. Hope this is helpful.
import java.awt.geom.Point2D; public class MyVelocityCalculator { public static void main(String[] args) { Point2D.Double currentPosition = new Point2D.Double(); Point2D.Double destinationPosition = new Point2D.Double(); currentPosition.setLocation(100, 100); destinationPosition.setLocation(50, 50); Double speed = 0.5; Point2D.Double nextPosition = MyVelocityCalculator.getVelocity(currentPosition, destinationPosition, speed); System.out.println("player was initially at: "+currentPosition); System.out.println("player destination is at: "+destinationPosition); System.out.println("half seconds later player should be at: "+nextPosition); } public static final Point2D.Double getVelocity(Point2D.Double currentPosition, Point2D.Double destinationPosition, double speed){ Point2D.Double nextPosition = new Point2D.Double(); double angle = calcAngleBetweenPoints(currentPosition, destinationPosition); double distance = speed; Point2D.Double velocityPoint = getVelocity(angle, distance); nextPosition.x = currentPosition.x + velocityPoint.x; nextPosition.y = currentPosition.y + velocityPoint.y; return nextPosition; } public static final double calcAngleBetweenPoints(Point2D.Double p1, Point2D.Double p2) { return Math.toDegrees( Math.atan2( p2.getY()-p1.getY(), p2.getX()-p1.getX() ) ); } public static final Point2D.Double getVelocity(double angle, double speed){ double x = Math.cos(Math.toRadians(angle))*speed; double y = Math.sin(Math.toRadians(angle))*speed; return (new Point2D.Double(x, y)); } }
source share