Nicholas Mansfield
Nicholas Mansfield

Reputation: 140

My trigonometry always returns 90 degrees, despite my formula seeming correct, and my variables working out correctly

I am writing a simple flash game which requires an angle to be calculated between one object and another. I have checked and my variables seem to be correct, and I know my law of cosines formula is correct. However, it always returns 90 degrees. Maybe you guys can see what is wrong with it. BTW, I used the mouse instead of an object as a reference point.

onClipEvent (enterFrame) {

var xdiff:Number = Math.abs(_root._xmouse - this._x);
var ydiff:Number = Math.abs(_root._ymouse  - this._y);
var xd2:Number = xdiff * xdiff;
var yd2:Number = ydiff * ydiff;
var hypot:Number = Math.sqrt(xd2+yd2);
var angle:Number = Math.acos((xd2 + yd2 - hypot * hypot) / (2*xdiff * ydiff))*180/Math.PI ;

trace("xdiff:"+xdiff);
trace("ydiff:"+ydiff);
trace("xd2:"+xd2);
trace("yd2:"+yd2);
trace("hypot:"+hypot);
trace(angle);

}

Upvotes: 0

Views: 146

Answers (2)

djna
djna

Reputation: 55907

Isn't

xd2 + yd2 - hypot * hypot

going to be always zero, hence acos(0) is 90.

Cos is Adjacent/Hypotenuse so, assuming you're calculating the gradient of the line between the two objects,

acos(xdiff/hypot)

then convert from radians with your 180/pi.

Upvotes: 1

madth3
madth3

Reputation: 7344

What does it mean to you an angle between two objects?

An angle can be calculated between two lines. You are calculating the angle between the x side and the y side of a right triangle and that is always 90 degrees.

Upvotes: 1

Related Questions