+1 vote

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)
asked Jul 9 in Engine by Panda_Scientist (25 points)

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.

1 Answer

0 votes

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

answered Jul 16 by Siandfrance (39 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.