Creating Local Gravity To Attract Specific GameObjects?

Hi,
I’m having little trouble with this. I want to create a magnet effect to draw my Coins gameObject towards the player.

using UnityEngine;
using System.Collections;

public class MagnetScript : MonoBehaviour {

	public GameObject attractedTo;
	public float strengthOfAttraction = 5.0f;

	
	void Update()
	{
		Vector3 direction = attractedTo.transform.position - transform.position;
		rigidbody2D.AddForce(strengthOfAttraction * direction);
		
	}
}

This is my code, but the problem is that all the other gameObjects are moving in the direction. Please help me with this

Hi

First up, your code would definitely only have an effect on an object that had your script as one of the components AND attractedTo was referencing the same target object in all of them. If this isn’t what you think is going on then I’d suggest running the game and checking the objects that are moving to see what components they have attached. I’m guessing there’s a bug somewhere else in your code / setup that is resulting in all objects having that script.

Next, if what you want is to simulate the effect of gravity (crucially, allowing things to go ‘into orbit’ then you will want to modfiy your code slightly to be:

//get the offset between the objects
Vector3 offset = attractedTo.transform.position - 
transform.position;

//we're doing 2d physics, so don't want to try and apply z forces!
offset.z = 0;

//get the squared distance between the objects
float magsqr = offset.sqrMagnitude;

//check distance is more than 0 (to avoid division by 0) and then apply a gravitational force to the object
//note the force is applied as an acceleration, as acceleration created by gravity is independent of the mass of the object
if(magsqr > 0.0001f)
       rigidbody2D.AddForce(strengthOfAttraction * offset.normalized / magsqr, ForceMode.Acceleration);

As I said though, the only way for your code to be applying that force to every object is if every object has that script assigned to it.

One more note - one cause for error is that you’re using 2d physics, meaning your scene needs to be setup with objects positioned around the XY plain, using Z just as a depth to avoid things overlapping. If you’ve inadvertently got objects scattered around the XZ plain instead this would cause problems.

@thieberson
Line 47

  • rForce is what?
    It’s not in the script
    help me plz,@thieberson
    Line 47
  • rForce is what?

For a 3D aproach:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class gravity : MonoBehaviour {
	public float GC = 6.67408 * 10e11; // Gravitational Constant OBS: the Newton's Universal Gravitational Constant is 6.67408 * 10e11
	List<Rigidbody> rigidBodyObjects; // List of all RigidBody objects on the scene
	public GameObject centerOfMassObject; // Set the object that represents the center of mass
	
	void Start () {
		// Instantiate the list of RigidBody Objects
		rigidBodyObjects = new List<Rigidbody>();

		// It searchs for all RigidBody Objects on the scene and it stores them in the "rigidBodyObjects" variable
		foreach (Collider collider in Physics.OverlapSphere(transform.position, Mathf.Infinity)) {
			if (collider.transform.GetComponent<Rigidbody> ()) {
				rigidBodyObjects.Add(collider.transform.GetComponent<Rigidbody> ());
			}
		}
	}		
	
	// OPTIONAL: Set the position of the center of mass 
	Vector3 centerOfMass(){		
		Vector3 sumMassXPosition = Vector3.zero;
		float totalMass = 0;
		foreach (Rigidbody RB in rigidBodyObjects) {
			sumMassXPosition += RB.mass * RB.transform.position;
			totalMass += RB.mass;
		}
		return sumMassXPosition / totalMass;
	}
	
	void Update () {
		// Go through the "rigidBodyObjects" list
		foreach (Rigidbody RB in rigidBodyObjects) {
			// Resultant Force over each rigid body object set to zero at each frame
			Vector3 resultForce = Vector3.zero;
			foreach (Rigidbody RB2 in rigidBodyObjects) {
				//  Calculates the force over each object by all the other objects
				if (RB.name != RB2.name) { 
					Vector3 forceDirection = RB.transform.position - RB2.transform.position;
					// Summarises each force in the resultant force 
					resultForce += GC * forceDirection.normalized * ((RB.mass * RB2.mass) / (forceDirection.magnitude * forceDirection.magnitude));
				}
			}
			// Add the resultant force into each rigid body object
			RB.AddForce (- resultForce);
		}

		#region Optional - Center of Mass
		
		centerOfMassObject.transform.position = centerOfMassObject();
		
		#endregion
	}
}