- Home /
Fixed distance between objects?
Is it possible to set it so two objects that are both affected by physics are a fixed distance between each other programmatically (On a 2D plane)? I basically want it so they are always 10 units away from each other. I'm sure that I could do it with joints but i'd rather not and if possible do it like:
if(Vector2.Distance(PointA, PointB)<10 || Vector2.Distance(PointA, PointB)>10){
// DoSomething
}
But I'm not sure what I could do inside the if statement and how I could scale the x and y values so the hypotenuse/distance is always 10. Does anyone have any ideas?
Answer by DaveA · Feb 01, 2011 at 10:53 PM
What if you parented them to the same object, offset by 10 units, then had physics affect the parent?
Answer by Bunny83 · Feb 01, 2011 at 11:24 PM
Why don't you want to use joints? That's what they are made for. If you want to move them manually, you have to care about the right physics yourself. That means you have to add forces to both objects that push them apart or pull them together. But it's not that easy. Forces always have a dynamic behaviour. if you want them always be at a fix distance you have to apply a huge force to compensate the "offset". But that can cause your objects to jitter and if you apply only small forces the "correction" is not instant.
Anyway, you have to decide what you want to do. That's the basic idea:
I guess JS? And i guess you want to move on the x-z-plane? y points upwards.
var secondObject : GameObject; var desiredDistance : float = 10; var force : float = 5;
function FixedUpdate() { var pos1 : Vector3 = transform.position; var pos2 : Vector3 = secondObject.transform.position; var V : Vector3 = pos2 - pos1; float dist = V.magnitude;
float offset = desiredDistance - dist;
rigidbody.AddForce(-V.normalized*offset*force); secondObject.rigidbody.AddForce(V.normalized*offset*force); }
That would apply the same force to both objects, but again: why do you want to do that inefficient and not really physically correct yourself? Unity comes with Nvidia's PhysX engine so why not use a joint?
Thanks for the help! Both of the objects are currently joined by a configurable joint which I am finding challenging to set a hard and fast distance between the two objects. If it's not too much bother do you know of a way of doing it with this kind of joint? Thanks again!
Your answer
Follow this Question
Related Questions
Set plane scaling pivot point? 1 Answer
spawned object wont change scale? 1 Answer
Find center between 4 points 3 Answers
Get new Point from Vector and Angle 1 Answer
finding point on the vector 1 Answer