WokerHead
WokerHead

Reputation: 967

Why does gravity script pull objects so fast then slows, not constant

How do I get a constant speed for this gravity script. The objects start off so fast then slows down as near the target. I just want a constant speed but I thought I was achieving it.

private Rigidbody ownBody;
private float maxVelocityOfInfluence = 10.2f;
private float rangeOfInfluence = 20000.0f;
public bool allowRangeGizmo = false;

private void OnEnable()
{
    ownBody = GetComponent<Rigidbody>();
}

private void FixedUpdate()
{
    Collider[] cols = Physics.OverlapSphere(transform.position, rangeOfInfluence);
    List<Rigidbody> rbs = new List<Rigidbody>();

    foreach (Collider c in cols)
    {
        Rigidbody otherBody = c.attachedRigidbody;
        if (otherBody != null && otherBody != ownBody && !rbs.Contains(otherBody) && (otherBody.transform.gameObject.tag == "Enemy1" || otherBody.transform.gameObject.tag == "Enemy2" || otherBody.transform.gameObject.tag == "Enemy3" || otherBody.transform.gameObject.tag == "Enemy4"))
        {
            rbs.Add(otherBody);

            Vector3 offset = transform.position - c.transform.position;
            otherBody.AddForce(offset * ownBody.mass);

            //  Control speed of Enemy
            if (otherBody.velocity.magnitude > maxVelocityOfInfluence)
            {
                otherBody.velocity = otherBody.velocity.normalized * maxVelocityOfInfluence;
            }
        }
    }
}

Could it be this code? It seems the offset changes the speed?

Vector3 offset = transform.position - c.transform.position;
otherBody.AddForce(offset * ownBody.mass);

Upvotes: 0

Views: 81

Answers (1)

leo Quint
leo Quint

Reputation: 787

Yes the offset value is greater the further your are so the force added will be greater. You can normalize the offset vector so its a direction vector instead (offset.normalized * ownBody.mass).

Upvotes: 1

Related Questions