Sunday, January 5, 2020

java - How do I make an entity move in a direction?


I have an Entity instance which is updated every game tick. Let's just assume that entity moves forward constantly. I'd like to be able to give the entity's angle to a function that makes it move in that direction:


moveForward(90); should make them move to the right. If I declared my rotation as a global int, then doing


moveForward(rotation);
rotation++;

would make it trace a small circle with its movement.


How can I do this? I assume this involves vector math; I don't know any, so a brief explanation would be nice.




Answer



Well in the simplest sense you have something like this.


   y  |\
| \
m | \ s
o | \ p
v |(a) \ e
(y)e |angle\ e
m | \ d
e | \

n | \
t | \
|__________\
x movement
(x)

The speed is however fast the enemy is, and you can determine how much they should move in the x direction and how much they move in the y direction by taking the sin or cos of the angle and multiplying by speed. Because...


 sin(a) = x / speed

So:



 x = speed * sin(a)

And:


cos(a) = y / speed

So:


y = speed * cos(a)

In your example moveForward(90) would yield speed * sin(90) or speed * 1 in the x direction and speed * cos(90) or 0 in the y direction (It should move to the right as you specified). That should get you started in the basic sense.


Making it general:



moveForward(float angle)
{
x += speed * sin(angle);
y += speed * cos(angle);
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...