Public Group

# Making a NPC move/rotate towards the player

This topic is 4213 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello! I want my NPC face the player character. I suppose the new directions are somehow based on the player char's X- and Z-Positions. What rotation values do I have to pass to D3DXMatrixRotationYawPitchRoll()? The same question goes for movement towards the player and the D3DXMatrixTranslation()-function. Any suggestions? I would be very grateful. Regards!

##### Share on other sites
OK, at least I solved the second problem (the coordinates to move to). The NPC now walks in the direction he is facing by this call:

NBPC.MoveRel(-sin(NPC.GetYRotation()) * ElapsedTime, 0.0f, -cos(NPC.GetYRotation()) * ElapsedTime);

But the question how to rotate the NPC in the first place, so that he faces the player char, still remains...

##### Share on other sites
To face the character towards the NPC you just use basic trigonometry. I'm not sure how to apply this to DirectX as I don't use it but to find the angle between the NPC and the player is just:

atan2((NPC.Z - Player.Z), (NPC.X - Player.X))

NOTE: atan2 is inverse tan and returns a value between –π and π.

##### Share on other sites
Thank you for your help. But in order to work correctly, I had to switch the parameters for atan2 (first the x-distance, then the z-distance).

My thanks again.

• 39
• 15
• 9
• 23
• 10