- Home /
Object not moving in direction of target
So I am instantiating a missile with this script. The object is instantiating and moving but it's moving in a weird direction and NOT towards specified target object.
I thought it might be the transform of the target might be buggy so I had the script get the transform of another object in the scene, but the missile still goes in a weird direction.
How do I get this missile object to travel in the direction of the target? What am I doing wrong?
public class FireMissile : MonoBehaviour {
public Transform target;
public Vector3 dir;
public float speed = 2f;
// Use this for initialization
void Start ()
{
speed = 2f;
target = GameObject.Find("ship").transform;
dir = target.position;
Invoke ("elimin", 3);
}
void Update()
{
dir = transform.position - target.position;
dir.Normalize ();
transform.Translate (dir * speed * Time.deltaTime);
}
void elimin()
{
Destroy (this.gameObject);
}
}
Answer by Xarbrough · Jul 13, 2015 at 12:45 AM
dir = target.position - transform.position;
Will give you the correct result. Direction = Subtraction of your position from target position.
Your answer
Follow this Question
Related Questions
Projectile speed changing by distance to target 1 Answer
Translate issue with Vector3.MoveTowards 1 Answer
Projectile reflection 1 Answer
How to teleport gameobject (instantly change transform.position) 3 Answers
How to get the forward vector normal to the camera's forward vector regardless of camera pitch 1 Answer