I followed Brackey’s tutorial and it has been very helpful, however I have a problem. For the items to be affected by gravity, they also act on others. I would like to have objects that are affected by gravity but don’t attract other objects.
This is the code I’m using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GravityAttractor : MonoBehaviour
{
public static List Attractors;
public Rigidbody2D rb;
const float G = 66.74f;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
foreach (GravityAttractor attractor in Attractors)
{
if (attractor != this)
{
Attract(attractor);
}
}
}
void OnEnable()
{
if (Attractors == null)
Attractors = new List<GravityAttractor>();
Attractors.Add(this);
}
void OnDisable()
{
Attractors.Remove(this);
}
public void Attract(GravityAttractor objToAttract)
{
Rigidbody2D rbToAttract = objToAttract.rb;
Vector2 direction = rb.position - rbToAttract.position;
float distance = direction.magnitude;
if (distance == 0f)
return;
float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
Vector2 force = direction.normalized * forceMagnitude;
rbToAttract.AddForce(force);
}
}