- Home /
Physics-based Homing Missile
How can I calculate the amount of seconds needed, at a certain force, to rotate an object to face another object with AddRelativeTorque?
... I think that's my question.
Basically, I want to make a physics-based homing missile.
Answer by dtoliaferro · Sep 02, 2011 at 11:28 AM
Got it. duckets from the IRC helped me with it. Basically, it's a torque based lookat script.
using UnityEngine; using System.Collections;
// @robotduck 2011 // set the object's rigidbody angular drag to a high value, like 10
public class TorqueLookAt : MonoBehaviour {
public Transform target;
public float force = 0.1f;
// Update is called once per frame
void Update () {
Vector3 targetDelta = target.position - transform.position;
//get the angle between transform.forward and target delta
float angleDiff = Vector3.Angle(transform.forward, targetDelta);
// get its cross product, which is the axis of rotation to
// get from one vector to the other
Vector3 cross = Vector3.Cross(transform.forward, targetDelta);
// apply torque along that axis according to the magnitude of the angle.
rigidbody.AddTorque(cross * angleDiff * force);
}
}
thanks for sharing the answer with the rest of us :) please select your answer as accepted.
No problem. Thanks for the tip. I'm kinda new to this.
Answer by Peelark · Apr 04, 2015 at 04:21 PM
This thread is ancient, but I came across it looking for a way to make this work in Unity 2D for a full physics-based space shooter. I want the enemy ships to track my player.
The issue in 2D is that you can't use a Vector3 to apply torque, so your angle as a Vector2 loses the desired rotation direction - i.e., your enemy always turns the same way. The way I fixed this was to take the normalised cross product and multiply the final float by its sign as follows (note the use of "up" because of the way axes are oriented in Unity2D:
float enemyTurnTorque = 1f;
//find the object you want to track - in my case "player"
Vector3 targetDelta = player.position - transform.position;
//get the angle between transform.forward and target delta
float angleDiff = Vector3.Angle(transform.up, targetDelta);
//get the cross product to determine which way to turn
Vector3 cross = Vector3.Cross(transform.up, targetDelta);
//normalise it and create a float, to hold a -1 or 1 corresponding to the right direction
cross.Normalize ();
float turnDirection = cross.z;
// apply torque along that axis according to the magnitude of the angle.
rb.AddTorque(enemyTurnTorque * turnDirection);