I never tried to learn trigonometry before I started trying to program and that is bound to show, but I don't think that this a is particularly easy thing to get your head around. I'm trying to learn as much as I can, but right now, I have no maths in my brain and I would really appreciate help with this. I don't just want to make one object face another, so much as I want an object to rotate towards a given target until it is just about facing that target.
if (target != null)
{
if (DistanceTwoPoints(xPos, yPos, target.x, target.y) < 312)
{
var direction:Number = (angle * (180 / Math.PI)) + 90;
var targetDirection:Number = Math.atan2(yPos - target.y, xPos - target.x) * (180 / Math.PI);
if (direction-10 > targetDirection) { RotateLeft();}
else if (direction+10 < targetDirection) { RotateRight(); }
}
}
In my top down space game, the above code currently makes my enemies turn and face the player. The obvious problem is that once the targetDirection moves past 0 or 360, the enemy rotates towards them the long way around.
I think that about covers the problem but I've never asked for help on a site like this before so if I've missed anything let me know. I'll be keeping an eye out for responses.
Thanks very much.
/* EDIT */
Ok. Through a lot of semi-educated guesswork and some wild stabbing in the dark, I've eventually got it working perfectly... but I am going to hate the code until I know that there isn't a far better ways to do this. If anyone would like to suggest a better way I am very open to suggestions. Here is my current code.
if (target != null)
{
if (DistanceTwoPoints(xPos, yPos, target.x, target.y) < 312)
{
if (angle * (180 / Math.PI) +90 > 180) { angle = angle - (360 / (180 / Math.PI));}
if (angle * (180 / Math.PI) +90 < -180) { angle = angle + (360 / (180 / Math.PI));}
var direction:Number = (angle * (180 / Math.PI)) +90;
var targetDirection:Number = Math.atan2(yPos - target.y, xPos - target.x) * (180 / Math.PI);
if (direction-targetDirection < -180 || direction-targetDirection > 180)
{
if (direction-2 > targetDirection) { RotateRight(); }
else if (direction+2 < targetDirection) { RotateLeft(); }
}
else
{
if (direction-2 > targetDirection) { RotateLeft();}
else if (direction+2 < targetDirection) { RotateRight(); }
}
}
}