Sunday, April 1, 2018

2d - Rotate object to face player


This is probably a simple vector question, but I'm not sure how to do it.


I have an object at vector position (ox,oy). Potentially every update, the user walks around the screen, and will be at position (px,py) at any given moment. How do I make it so that the object is always facing the player? I need to get the angle in degrees.



This is what I've been messing around with, but the direction doesn't immediately point to where the user is located. Instead, it slowly increments in the direction the user is walking in.


 objVec.Normalize(); 
playerVec.Normalize();

obj.Rotation = MathHelper.ToDegrees((float)Math.Acos(Vector2.Dot(objVec, playerVec)));

I might be going about it completely wrong, so any help is appreciated!



Answer



Think about the problem differently. You want to object always to "face" the player, which means you want its "forward" vector rotated around to be parallel to the vector from itself to the player. Assuming its "forward" vector is normally at obj.Rotation = 0, the proper rotation is basically the arctangent of Vector2.Subtract(playerPos, objectPos). Most math libraries will have something like atan2 that takes two arguments or a Vector2 that will automatically figure out the right quadrant for you.


EDIT: I realized that you're in C# and these are actually built-in classes. So you don't have to go hunting for math library documentation, I can do so for you. The right code should be:



Vector2 facingVec = playerVec - objVec;
obj.Rotation = MathHelper.ToDegrees((float)Math.Atan2(facingVec.Y, facingVec.X));

Note the X/Y reversal; for hysterical raisins, Atan2 always has the arguments reversed.


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...