- Home /
Question by
Malcolm240104 · Mar 21, 2020 at 04:59 PM ·
unity 2dgravity
Faux Gravity
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);
}
}
Comment
What are you trying to achieve specifically because unity has gravity built into its physics engine?
Best Answer
Answer by dougantor · Mar 21, 2020 at 10:31 PM
Just have a public bool which you can set from the inspector which says whether to run the Attract function or not:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GravityAttractor : MonoBehaviour
{ public static List Attractors;
public Rigidbody2D rb;
public bool attractsOthers = true;
const float G = 66.74f;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
if (attractsOthers)
{
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);
}
}