1

I'm working on a javascript game where you drive a car based on where your mouse is, (so it moves towards your mouse).

But right now its just a rectangle that follows your mouse. I want it to rotate towarts the mouse, (for example if you have a rectangle that is 100px wide and 50px high and the left side is white and the right side is black, the black side should always face the cursor).

i tried making if statements for some positions of the mouse but after a hour of programming, i figured out this was going to take weeks like this. Does anybody know a better and/or easier way to do this?

1 Answers1

2

You can use transform: rotate(angle). And calculate angle using atan2

const mousePos = { x: 10, y: 10 }
const carPos = { x: 30, y: 20 }
const vector = { x: mousePos.x - carPos.x, y: mousePos.y - carPos.y }
const angle = Math.atan2(vector.y, vector.x) * 180 / Math.PI;

Maybe you will need to add 90 degrees or something like that. Untested.

Konrad Linkowski
  • 2,351
  • 1
  • 20
  • 33