So I wanted to create a simple solar system simulator to simulate a binary star system that I designed, and I'm running into some problems. I started with Area2D
nodes to try out some of their functionality with the gravity point and stuff, but that behaved really strange so I decided to program my own physics for it. It was pretty simple, all I needed to implement was one equation, Newton's Law of Universal Gravitation, and I slid Kinematic Bodies around and it works great!
The problem:
I need to implement a way to give a velocity to the bodies to start an orbit, but since I'm using Kinematic Bodies I don't have the Linear Velocity section. If you would like to scan the code, I'll put it right here.
extends KinematicBody2D
export var velocity : Vector2
export var mass : float = 500
var force : float
var force_direction_vector : Vector2
func _physics_process(delta):
# Reset member variables
force_direction_vector = Vector2.ZERO
force = 0
velocity = Vector2.ZERO
for i in get_parent().get_children():
if i != self:
force_direction_vector = i.position - self.position
if force_direction_vector.length_squared():
# Law of universal gravitation
force += (self.mass * i.mass) / force_direction_vector.length_squared()
# Convert force to velocity (kinda)
velocity += force_direction_vector.normalized() * force * delta * 100
velocity = move_and_slide(velocity, Vector2.ZERO)