Gatekeeper
Gatekeeper

Reputation: 7128

Move Object along a straight line

I am trying to move a Sprite along a straight line path. I want to move it 5 pixels on the slope, or the hypotenuse each time I go through the method until I reach the end point.

I have the slope and y-intercept of the line, I also have the current X and Y values of the sprite through getX() and getY(). The final X and Y points to stop at are variables finalX and finalY.

I have tried so many equations but I can't seem to get any of them to work. What am I missing!!?

Hopefully this image makes sense for what I am trying to do!

My latest equation was trying to use y=mx+b.

float X = (getY() + 5 - interceptY)/slope;
float Y = slope*(getX() + 5) + interceptY;
setPosition(X, Y);

Upvotes: 1

Views: 4604

Answers (1)

Egor
Egor

Reputation: 40193

Can help you with a few equations from my recent game, the code moves an object given its rotation:

float xDirection = FloatMath.sin((float) Math.toRadians(getRotation()))
            * currentSpeed;
float yDirection = FloatMath.cos((float) Math.toRadians(getRotation()))
            * -currentSpeed;

float newX = getX() + xDirection;
float newY = getY() + yDirection;

You just need to derive the angle in which you need your sprite to move and this will do for you. Hope this helps.

Upvotes: 4

Related Questions