- Home /
Move object A towards object B
I want Object A to move towards Object B at a certain speed. If possible I'd also like Object A to rotate towards Object B. If possible, answer so simply that a person who did not even understand the Unity Reference page can understand. Thank you.
Current script on ObjectA.
var speed = 4.0; var ObjectB:GameObject;
function Update () {
}
Please do not link me to reference pages. Because they are never tailored to fit my situation. Thank you.
I'd like to be able to move it in a definite speed. A single speed that does not change depending on how far from the player the object is. Is this possible?
Answer by Kourosh · Apr 25, 2011 at 08:26 PM
var speed = 4.0; var ObjectB:GameObject;
private var increment:float; private var rotation:Quaternion;
function Update () { if(increment <=1) increment += speed/100;
transform.position = Vector3.Lerp(transform.position, ObjectB.transform.position, increment);
//Add this block only if you want the rotation also be transitioned to objectB's rotation. var direction:Vector3 = ObjectB.transform.position - transform.position; rotation = Quaternion.LookRotation(direction); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, increment);
}
Lerp function converts a Vector3 to another while increment goes to 1 from 0.
Couldn you just use transform.LookAt to achieve the rotation, or am I missing something?
Yes, it can be just LookAt, however i think LookAt makes a sudden rotation rather than having a smooth and gradual rotation. I was't sure which type he's looking for so I made the smoothed one :)
Erm, thank you. This does indeed work. However, this movement is kind of uncontrollable. It starts out slow no matter what "speed" is on and then accelerates to an undefined speed that is not exactly how I want it. This also seems to get extremely faster should some distance be put between the objects. Is there some way that I could see some code that would only and simply move the object towards the other in a single definite velocity? I'll handle acceleration myself with changing the speed variable. If that is what the code is supposed to do, then I apologize. It does not.
And what exactly does Vector3.Lerp do?
http://unity3d.com/support/documentation/ScriptReference/Vector3.Lerp.html
What is it this page is trying to tell me but that I clearly do not understand?
Could you also just replace the increment variable with a "Time.deltaTime * Speed" to achieve the same effect?