How to apply an initial velocity to a body in a planet simulator using Kinematic Bodies

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Panda_Scientist

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)

Kinematicbodies don’t have a velocity property because technically it doesn’t need it, it’s all under your control so the velocity should be worked out before move_and_slide is called.
I can’t provide the maths (I would’ve parented them to a center point and relied on rotation_degrees.y for rotations) but you’ll be better off using Rigidbodies for setting initial velocities.

Magso | 2020-07-09 22:09

:bust_in_silhouette: Reply From: Siandfrance

If you don’t reset the velocity you exported (line 12: velocity = Vector2.ZERO), it should work (set the velocity variable in the editor).