Gravity center on position (X0,Y0)

Hi guys imagine that i have a planet it center is at X 0 Y 0.

I spawning loot each time i destroy part of terrain and i want this loot to use rigidbody and my custom gravity.

Meaning that gravity will not go towards vector i set in Physics2d.gravity but gravity will go to exact point and then stop.

I attached screen i want all loot to be attracted by green circle in middle.

I like to know you opinion on the simplest way how i can achiev it i pref to not use Update() just like to set “center of gravity” , similar like center of mass if it is possible somehow.

Thanks for your help in advance.

i found Brackeys tutorial about gravity it is working but it is too heavy for my project and i dont like it

Check screen

Get over this silliness. Even the normal physics is done inside of FixedUpdate()… it is just inside Unity’s internal FixedUpdate() so you don’t see it.

What does this mean? Have you attached the profiler and found that your bottleneck has to do with gravity?! I kinda doubt that honestly since gravity is just a scaled vector addition.

If you have enough rigidbodies for the overhead of “adding a FixedUpdate to all of them” to be a performance concern, then processing the physics for all of those rigidbodies is going to be thousands of times larger of a performance concern.

1 Like

I jus think that there should be some easier way then this.Just set some kind of center of gravity and it will work like normal gravity but towards X0,Y0

So it is not possible?

public Transform CenterOfWorld;
public float GravityMagnitude;

void FixedUpdate()
{
  Vector3 toCenter = (transform.position - CenterOfWorld.position).normalized;
  myRigidbody.velocity += toCenter * GravityMagnitude * Time.deltaTime;
}

This code should be attached on all objects i want to be attracted by CenterOfWorld?

Correct.

If those objects do not have a Rigidbody, you can trivially make ballistic script such as:

https://gist.github.com/kurtdekker/8055d18ee64877e4ceca78305e7f15c9

to move things around.

NOTE: the code above assumes constant attraction regardless of distance from object. If you need a distance to magnitude function, then use Vector3.Distance() to calculate distance and compute the magnitude however you like, such as the traditional G / R^2.

1 Like

Thanks i will try it tomorow , this you posted should work for me.

Hello your code solved my issue, thanks.

 public class Attractor : MonoBehaviour
    {
        Rigidbody2D rb;
        Vector3 center = new Vector3(0, 0, 0);
        float GravityMagnitude = -1;


        void Awake()
        {
            rb = gameObject.GetComponent<Rigidbody2D>();
        }
        void FixedUpdate()
        {
            Vector2 toCenter = (transform.position - center).normalized;
            rb.velocity += toCenter * GravityMagnitude * Time.deltaTime;
        }

    }

Then it is working in my as intended .Thanks