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);
}
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.