Entretoize
Entretoize

Reputation: 2251

Having a rigidBody to follow (match) the position of a gameObject in Unity

I'm trying to use addForceAtPosition to make a rigidBody (the clone) to follow a gameObject (the target), more precisely to go the the same position and rotation. This is my code:

        for(var points=0;points<3;points++)
        {
            Vector3 pr=Vector3.zero;
            switch(points)    //get some test points used as anchors
            {
                case 0: pr= new Vector3(0, 0, 0); break;
                case 1: pr = new Vector3(0, 0.05f, 0); break;
                case 2: pr = new Vector3(0, 0, 0.05f); break;
            }
            p = clone.transform.TransformPoint(pr);    //get the clone test point world position
            v = clone.GetPointVelocity(p);             //and its velocity
            pc = target.transform.TransformPoint(pr);    //get the target body test point world position

            Vector3 dist= (pc - (p + v * kv));    //add a part of the velocity to the position to reduce "elastic effect" (that part works)
            Vector3 force = dist * k;
            clone.AddForceAtPosition(force, p, ForceMode.Impulse);
        }

The clone move to a position around the target but at a given distance and if tha target rotate, the clone move around it keeping a relative position to it. It's seems to be a relative/absolute position problem but I don't see where I made a mistake.

Upvotes: 0

Views: 4173

Answers (2)

Entretoize
Entretoize

Reputation: 2251

The target parent have a scaling of 100 then the target.transform.TransformPoint(pr) returns a point far from the object.

target.transform.TransformPoint(pr*0.01) solved my issue.

Upvotes: 0

derHugo
derHugo

Reputation: 90659

In order to do what you say set a Rigidbody to the same position and rotation. as another object rather use MovePosition and MoveRotation

private void FixedUpdate ()
{
    clone.MovePosition(targetTransform.position);
    clone.MoveRotation(targetTransform.rotation);
}

Upvotes: 1

Related Questions