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
  • 21,590
  • 4
  • 28
  • 64
  • Im guesing that const carpos isn't enough. do i need to const it with a document.queryselector("#car"); and the same for mousepos? –  Aug 21 '20 at 19:02
  • Here you will learn how to get mouse position. It doesn't have to be const or an object. You just need x and y positions. https://stackoverflow.com/questions/7790725/javascript-track-mouse-position – Konrad Aug 21 '20 at 19:15
  • it works but the rotation isn't perfect there is a problem with the math, could you please double check it? –  Sep 27 '20 at 17:44
  • What do you mean by *isn't perfect*? – Konrad Sep 27 '20 at 18:37
  • 1
    nvm i found the problem, thanks for all of your help! –  Sep 27 '20 at 19:03
  • hello sir, i have one last question. When the top and left positions of the object aren't the same it doesnt work, do you know how to fix this? –  Oct 11 '20 at 16:53
  • @a-bad-js-developer what do you mean by this? – Konrad Oct 13 '20 at 13:38
  • If the top and left position aren't the same the div wil move very slow at some points and very fast at others –  Oct 13 '20 at 17:18
  • Add half width of the div to the carPos.x and half height of the div to the carPos.y – Konrad Oct 13 '20 at 17:21
  • that makes it worse –  Oct 13 '20 at 17:44
  • Do you have some online example somewhere? – Konrad Oct 13 '20 at 18:30
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223015/discussion-between-a-bad-js-developer-and-konrad-linkowski). –  Oct 14 '20 at 10:27