1

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);
Gatekeeper
  • 6,708
  • 6
  • 27
  • 37

1 Answers1

4

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.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • Thank you so much for this! =) worked purrrfectly once I figured out the rotation properly! Used this to set the rotation of my sprite, which plugged right into your code! `setRotation((float) Math.toDegrees(Math.atan2(finalY - getY(), finalX - getX())) + 90);` By chance do you use AndEngine? =) – Gatekeeper Jul 20 '12 at 07:36
  • @Gatekeeper, You're welcome, glad I could help! Yes, I'm using AndEngine. – Egor Jul 20 '12 at 08:10