"Magnetized" Game Objects using Constant Force

The project I am working on right now consists of grouping game objects together based a shared point of data. For my example I am using people as the objects (Sphere Game-objects) and sorting them based on job title, I.E. Coder/Artist/Financial/CEO.

I have everything sorting itself and creating a “GroupGO” which is the parent object and all the people are children of it.

What I would like to do is have the people be magnetized towards the GroupGO and push each other away out of the way as they try to clump with other people objects that share the same data point.

I was thinking of using a RigidBody/Constant Force to always push them towards the GroupGO but I am not having any luck.

    void FixedUpdate()
    {
        if (_mag == true)
        {
            this.gameObject.rigidbody.AddForce(GroupLookAt.transform.forward * 2000);
        }
    }

    public void target(GameObject target)
    {
        GroupLookAt = target; //Designates the GameObject that will be used as the focal point/position
    }

Take a look at Joints like the Spring Joint or Hinge Joint that can connect Rigidbodies together

You apply the forward vector as force, that has nothing to do with a vector that points towards the center point :wink:

In general it would look like this:

rigidbody.AddForce((GroupLookAt.transform.position - transform.position).normalized * force);

However since you added your rigidbodies as child objects to the center object, you just need the localPosition of the object which is the vector from the center to your rigidbody. The downside is that this vector is in localspace of the group object, if the group object isn’t rotated in relation to the world you can simply use:

rigidbody.AddForce(-transform.localPosition.normalized * force);

If the parent is rotated, the direction needs to be transformed into world space

rigidbody.AddForce(GroupLookAt.transform.TransformDirection(-transform.localPosition).normalized * force);

Which isn’t any shorter than the first way :wink:

edit
Just in case someone wants to waste some time, here’s something to play around with:
I’ve created a sample project how it could look like.