ClownInTheMoon - 1 month ago 24

Java Question

I'm working on a game that leverages sprites in two dimensional space and I'm trying to figure out a better way to stop at an exact point.

I've gotten the following to work:

`public void target(boolean hasTargetIn, Point target) {`

if (hasTarget) {

deltaX = target.getX() - this.mPos.getX();

deltaY = target.getY() - this.mPos.getY();

mDirection = Math.atan2(deltaY,deltaX);

mVelocityX = Math.cos(mDirection) * mSpeed;

mVelocityY = Math.sin(mDirection) * mSpeed;

}

hasTarget = hasTargetIn;

}

public void move(Point target) {

if (mPos.getX() != target.getX() + 3 && mPos.getY() != target.getY() + 3) {

this.mPos.x += mVelocityX;

this.mPos.y += mVelocityY;

}

}

Here are the arguments I'm giving to the method:

`sprite.target(true, new Point(700,305));`

sprite.move(new Point(700,305));

But this requires me to offset the target.getX() by 3 in the move() method as the X values vacillate between 703 and 697 when the sprite reaches the position (thus it simply stays there jittering without the logic I've included in the move() method). Is there a better way to move and stop at an exact point?

Answer

Just use the distance to the target. If the distance is greater than the speed just move as normal, if the distance is less than the speed then just move the distance.

You don't need to use `atan2`

, `sin`

and `cos`

to get the normalized deltaX,Y you can just divide the deltas by the distance. Does the same as get direction and using sin and cos.

```
deltaX = target.getX() - this.mPos.getX();
deltaY = target.getY() - this.mPos.getY();
// get the distance
mDist = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
if(mDist > 0){
if(mDist < mSpeed){
mVelocityX = deltaX;
mVelocityY = deltaY;
}else{
mVelocityX = (deltaX / mDist) * mSpeed;
mVelocityY = (deltaY / mDist) * mSpeed;
}
}else{
mVelocityX = 0;
mVelocityY = 0;
}
```