2D faux gravity

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

I’m trying , to make a Player walk on a planet , through searching , I figured out that I can achieve this effect using Faux gravity , I tried to Implement it , but it’s not working as intended:

Planet a StaticBody with a sphere collider:

extends StaticBody2D

var _gravity := 10.0

func attract(body : RigidBody2D, deltaTime):
	var gravityVector = (global_position - body.global_position).normalized()
	var rotation = Vector2.DOWN.angle_to((gravityVector))
	body.apply_central_impulse(gravityVector * _gravity)
	body.rotation = rotation

and the Player is a RigidBody2D with CustomIntegration turned on:

extends RigidBody2D

export var Attractor : NodePath
onready var attractor = get_node(Attractor)

func _integrate_forces(state):

	attractor.attract(self, state.step)
	var velocity = state.get_linear_velocity()

	if Input.is_action_pressed("ui_left"):
		state.set_linear_velocity(Vector2(-50, 0) )
	elif Input.is_action_pressed("ui_right"):
		state.set_linear_velocity(Vector2(50, 0) )

the Player seems to be rotated and attracted correctly , when I move from the Editor, but when I add a linear velocity to it , it start floating , how can make it work correctly?

:bust_in_silhouette: Reply From: Inces

Is it really necessary to use custom integrator ? It negates forces and impulses created by planet. Also, I don’t think You want to move arbitrary left and right - what if your player approaches side of a planet ot walks it upside down ?

I think You should code movement in one place and consequently. I would try to use apply impulses for movement, by a Vector tangent to gravity, positive or negative depending on input. If You use some friction ( like 0.9 ) and tweak movement speed, your player won’t slide or accelerate on surface of the planet