Koppany
Koppany

Reputation: 57

Calculating Angle after randomly given margin-left and margin-top

Got a simple question. I have an application where logos of plains fly randomly across. (They get a random new position of left-margin and top-margin at every X second). The next challenge to rotate them, in order that the head of the planes would stand towards the angle they are flying.

Didnt really find a solution how to do that. What we know only:

MARGIN-LEFT

MARGIN-TOP

But these values constantly changing as planes randomly flying. Any ideas or suggestions?

UPDATE (in order to be more obvious) here is chunk of code:

  var nh = Math.floor(Math.random() * $(window).height() - 50);
  var nw = Math.floor(Math.random() * $(window).width() - 50);
  $('#plane').animate({ top: nh, left: nw}, 10000, function(){});
  $('#plane').css({"transform" : "rotate(" + Math.atan2(nh,nw)/Math.PI*180 +"deg)"});

Upvotes: 0

Views: 41

Answers (1)

Manuel Otto
Manuel Otto

Reputation: 6540

It's not very clear what you're trying to achieve.

In order to calculate the angle based on the margins, you can use Math.atan2()

function getAngle(x1,y1,x2,y2){
    return Math.atan2(y2-y1,x2-x1)/Math.PI*180
}
var angle = getAngle(MARGIN-LEFT, MARGIN-TOP);
console.log('the angle is',angle,'degrees')

Upvotes: 1

Related Questions