- Home /
 
 
               Question by 
               SylverLocks · Apr 11, 2017 at 05:26 PM · 
                physicsparticlesgravityaddforcesimulation  
              
 
              Can't Get gravity function to work
I want to have one "particle" attract other particles to it. So to test it, I created two spheres. One of which I added the following code to: [RequireComponent(typeof(Rigidbody))] public class Attraction : MonoBehaviour { public float pullRadius = 2; public float pullForce = 1;
     public void FixedUpdate()
     {
         foreach (Collider collider in Physics.OverlapSphere(transform.position, pullRadius)) {
             // calculate direction from target to me
             Vector3 forceDirection = transform.position - collider.transform.position;
 
             // apply force on target towards me
            collider.GetComponent<Rigidbody>().AddForce(forceDirection.normalized * pullForce * Time.fixedDeltaTime);
         }
     }
 }
 
               But what ends up happening is nothing. I tried making the radius of pull greater, and the other sphere wouldn't move toward the initial one, and I have no idea why. It just didn't move. Help!
               Comment
              
 
               
              Answer by Just_Jim_98 · Apr 17, 2017 at 07:17 PM
Here this should help, I normally go around it by finding Rigid body's in a sphere however to keep it simple below should work,(using deltatime instead of fixeddeltatime)
 using UnityEngine;
 
 public class Gravity : MonoBehaviour {
 
     //Create Public Variables
     public float pullForce = 2f;
     public float pullRange = 10f;
 
     void Update () {
         //First lets find all colliders in the shere
         foreach(Collider coll in Physics.OverlapSphere(transform.position, pullRange))
         {
             //Get the Direction
             Vector3 pullDirection = transform.position - coll.gameObject.transform.position;
 
             //Aplly the force onto the object but multiply it by delta time instead of fixeddeltatime
             coll.gameObject.GetComponent<Rigidbody>().AddForce(pullDirection.normalized * pullForce * Time.deltaTime);
         }
     }
 }
 
              Your answer