JSFiddle - React, Tailwind, and code Playground
HTML
<img src="http://i.imgur.com/8jV4DEn.png" id="player" alt="hero">
CSS
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#player{
position: absolute;
top: 200px;
left: 200px;
width: 40px;
height: 60px;
}
JavaScript
var angles = [];
function calculateAngle(){
var player = $('#player');
//Checks to see which key is pressed down
$(window).on('mousemove', function (e) {
//Current position
var p1 = {
//add width and height of image
x: player.offset().left,
y: player.offset().top,
};
//Future position
var p2 = {
x: e.offsetX,
y: e.offsetY,
};
var dist=100;
if (Distance (p1,p2)<dist){
return
}
//Angle between them in degrees
var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;
angleDeg -= 90;
//Animate the whole thing
player.css('-webkit-transform', 'rotate(' + angleDeg + 'deg)');
});
}
function Distance( p1, p2 ){
var x,y = 0;
x = p2.x - p1.x;
x = x * x;
y = p2.y - p1.y;
y = y * y;
return Math.sqrt( x + y );
}
$(document).ready(function(){
calculateAngle();
});