简体   繁体   中英

How to make find the angle one object must rotate at to face another, JS HTML5 CANVAS

Okay, so I have two objects, a player and a cursor. I have both object's positions, I just need to find the number in degrees or radians the player must rotate to face the cursor.

I'm making this game in Javascript, and the game is running within a canvas. So I'd prefer to have a code to place in the Update() or Draw() function to update a variable which I can use to rotate my player each time the Draw() function is called.

I figured there would be some sot of formula to use for this, but I haven't been able to find it myself, and frankly I might not know what to do with this if I have. So it would be amazing if one of you could help me out with this!

OK, let's assume the following:
1) As well as a player (whose location you know) and a cursor (whose location you know), you also know the current rotation of the player (I'm thinking you've got a top-down view onto a guy and you can see which way he's facing). I'm assuming this because you ask how far the player must rotate to face the cursor, which implies that the player has rotation. If the player is always facing in one direction and everything else is rotated about them, the same method will work, you just won't need to subtract the player's rotation at the end.
2) The players rotation is relative to "right" (being the positive x-axis).
3) The players rotation is measured in radians.

If this is true, then you'd do the follow:
1) Work out the rotation to get from "right" to the cursor (if you shift everything so that the player is at the origin). To do this you'd do Math.atan2(cursor.y - player.y,cursor.x - player.x); - this would give you the angle in radians.
2) Subtract the player's rotation from this angle.

Ta da?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM