I think my brain isn’t working this morning, something in my math is wrong. The missile either doesn’t rotate at all, or quickly oscillates between two angles.
Here is my script:
function GetNewRotationAngle(){
var targetAngle : float = Angle2D(Vector2(transform.position.x, transform.position.y), Vector2(target.x, target.y));
var angleDiff : float = transform.eulerAngles.x - targetAngle;
if(angleDiff >= 180f){
angleDiff -= 360f;
}else{
if(angleDiff <= -180f){
angleDiff += 360f;
}
}
var turnSpeed : float = rotationDegreesPerSecond*Time.deltaTime;
var result : float;
if(turnSpeed<Mathf.Abs(angleDiff)){
result = transform.eulerAngles.x + (turnSpeed * angleDiff);
}else{
result = targetAngle;
}
angleDebug = angleDiff;
return result;
}
function Angle2D(current : Vector2, target : Vector2){
return Mathf.Atan2(target.y-current.y, target.x-current.x) * Mathf.Rad2Deg;
}
Note that I’m doing this in the 3D engine. Thanks for the help guys
EDIT:
thanks to bigmisterb for the solution. here is the code i ended up with that worked for me. note that i’m doing this on rigidbodies
rotation:
function GetNewRotationAngle(){
var targetDir : Vector3 = target - rigidbody.position;
targetDir.z = 0f;
var newRotation = Quaternion.LookRotation(targetDir, Vector3.forward);
var deltaRotation : Quaternion = Quaternion.RotateTowards(rigidbody.rotation, newRotation, rotationDegreesPerSecond*Time.deltaTime);
rigidbody.MoveRotation(deltaRotation);
}
movement: (in order to get it to work on one axis, i had to clamp the z position of the rigidbody)
function UpdateMovement(){
var movement : Vector3 = rigidbody.position + transform.forward * (moveSpeed * Time.deltaTime);
movement.z = 0f;
rigidbody.MovePosition(movement);
}