How to work out what direction an object is moving

715 Views Asked by At

SO I currently have an object which moves in the Y axis (up and down). How would I be able to program it so the program knows whether the object is moving up or down?

I understand I'd need an if statement like the following:

if (object is moving up)
{
//set direction to 1
}

else
{
//object must be going down, set direction to 2
}

I just don't understand what syntax I'd need to use. This would be easy if I was holding down the key and it was moving up or down however that's not the case. The object is a bouncing ball and therefore when you set a power the ball jumps, and bounces so it is constantly changing.

Thanks for your help, let me know if this wasn't described well and you need more info.

2

There are 2 best solutions below

0
On

When you update the position of the ball you have one position and you calculate the position for the next frame -> You can calculate the distance vector.

With the sign of the y-value of this distance vector you can decide if it's moving upwards, downwards or isn't moving (=0).

0
On

You need to save the current coordinates so that you can check them after the update method is called. Then you can check the differences between the previous and current location:

Declare it in Game1() constructor:

Point previous = new Point();
previous.X = myObject.InitialX;
previous.Y = myObject.InitialY;

In Update:

int deltaX = object.X - previous.X;
int deltaY = object.Y - previous.Y;

if (deltaX < 0)
{
    object is moving upwards
} 
else
{
    object is moving downwards
}

if (deltaY < 0)
{
    object is moving to the left
} 
else
{
    object is moving to the right
}

//update the previous state
previous.X = myObject.X;
previous.Y = myObject.Y;