- Home /
Decrease distance between 2 objects
How can I decrease the distance of 2 objects? Only one of the objects has to be moved, the other one kepps its position.
If this helps: The object which moves always looks at the not-moving object.
Maybe I can simply change the X and Z coords. But I've no idea how..
Answer by Screenhog · Feb 07, 2013 at 07:43 PM
For moving a fixed distance, there's also Vector3.MoveTowards. While it has some drawbacks compared to Lerp (wanting to smooth the animations based on a curve, for instance), I find it to be the simplest way to move one object at a constant rate towards a second point.
Answer by robertbu · Feb 07, 2013 at 12:00 PM
if Pos1 and pos2 are Vector3's representing the position of the two objects. You can use Lerp():
Pos2 = Vector3.Lerp(Pos1, Pos2, 0.75);
This will move Pos2 1/4 closer to Pos1. You can also do the calculation yourself (untested):
Pos2 = Pos1 + (Pos2 - Pos1) * .75;
This worked fine. Can I also move it a fixed distance? The function will not be called only once and then the moving distance is at the beginning maybe 500 and the last time only 30.
You can move them a fixed distance by calculating the fraction. You can get the distance between two points are apart by:
distApart = (pos2 - pos1).magnitude;
If you want to move pos2 by a fixed distance (delta) you can do:
fraction = (distApart + delta) / distapart;
Pos2 = Pos1 + (Pos2 - Pos1) * fraction;
Negative deltas move the objects closer together.
Thank you Very $$anonymous$$uch for sharing this 8 years ago. Was searching for hours for a way to do this. Works.
For moving a fixed distance, there's also Vector3.$$anonymous$$oveTowards.
Answer by Zarenityx · Feb 07, 2013 at 12:04 PM
When you are using Transform.LookAt, it will always point the positive Z axis. If you don't want to worry about collisions, just use Transform.Translate. Try this if you don't want it jittering when it gets really close, or if you want it stopping within a radius.
var target : Transform;
var speed : float;
var radius : float;
function Update(){
transform.LookAt(target.position);
if(Vector3.Distance(transform.position,target.position)>radius){
transform.Translate(0,0,speed);
}
}
What does Translate exactly do? There is a speed? I don't need a smooth following. It can also teleport to the new position, this doesn't matter :)