I need to make few planets that produce gravity and a lot of objects that moves in that fields. I can't use Area2D because it's gravity not feels like real: I need a real gravity that depends on mass and squared distance.

So, my question is how to make it in adequate way? I thought about using groups: one for gravity sources and another for gravity receivers. Then I can iterate through group object to calculate and apply forces. I suggest, I should to use C++ for biggest performance.

Is it good way? Or can I do it in more simplier way? I need an advice about it.

How to realise a real newtonian 2d gravity with a lot of bodies without performance issues?

in Engine

Have you looked at a RigidBody2D? It utilizes mass, inertia, and gravity. The inverse square law is probably taken into account under the hood (i.e. in the engine's Phyiscs 2D server). It could be implemented such that it does a good job of simulating physics, but I don't know for sure.

Yes, I'm using RigidBody2D. But I should add custom gravitation (because native in Godot is ugly).

So, I need to tell some RigidBody2D and some StaticBody2D that it should be used in gravity vector calculation and then tell to other RigidBody2D that I will calculate and apply to it custom gravity vector.

So, my questions are:

1. How to divide all objects on scene into this two groups.
2. How to select all scene objects of one specific group and effictively iterate through it to calculate and apply gravity vectors.

I have planets and asteroids and want to make it move in natural way. Gravity of Area2D can't do it in right way.

Reading Area2D documentation I guess you could

my_area.gravity_point = true

And next

my_area.gravity_vec  = my_area.position

Not sure as the docs say 'If gravity is a point (see gravity_point), this will be the point of attraction.'

Testing myself I did not manage to make a planet attract an object.

Have you found a solution yourself?

@clemens.tolboom there is not what I am seeking. That gravity strength doesn't depend from distance to center.

So you did not found a solution? My approach would be to do it in GDScript first for ease of writing ... but I guess you need to set gravity off and apply forces yourself. This Unity shows some steps for the func _physics_process() steps which I would use myself.

This Scratch looks good too.

@clemens.tolboom I found. I just made custom script attached to Area2D that applies force to all overlapping bodies in physicsprocess by formula:

F = G * msource * mbody / distancetosource_center^2

Where G is gravity constant,
msource - mass of gravity source
m
body - mass of body
distancetosource_center - distance between their centers.