Moving an object at a consistent speed from point A to B

我与影子孤独终老i 提交于 2019-12-04 08:28:06

In general the best way to handle directional movement is using trigonometry. Your projectile needs two things for this: direction (in radians) and speed.

The three trig functions you need are sin, cos, and arctan

For updating your X: setX(getX() + (speed * Math.cos(direction)));

For updating your Y: setY(getY() + (speed * Math.sin(direction)));

For calculating the direction: Math.atan(slope)

You should add the fields direction and speed to your class and declare them as doubles.

public void setHasTarget(boolean hasTargetIn)
{
    if (hasTargetIn)
    {
        deltaX = getTargetX() - getX();
        deltaY = getTargetY() - getY();
        direction = Math.atan(deltaY / deltaX); // Math.atan2(deltaY, deltaX) does the same thing but checks for deltaX being zero to prevent divide-by-zero exceptions
        speed = 5.0;
    }
    hasTarget = hasTargetIn;
}

public void setNext()
{
    setX(getX() + (speed * Math.cos(direction)));
    setY(getY() + (speed * Math.sin(direction)));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!