rotate Kinematic Body 3d based on gravity vector affecting it

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

So, i am making a game where a player can move between planets. For gravity i use spherical areas with point gravity at their center. What i am trying to do is rotate Kinematic Body 3d (player) so it’s legs are pointing downward towards the center of the planet and so that the player can walk on the planet. How do I do that? This is my current code:

extends KinematicBody

var gravity = -24.8
var vel = Vector3()
var walk_speed = 7
var run_speed = 10
var jump_speed = 10
var acceleration = 4.5

var gravity_dir = Vector3(0, 1, 0)

var dir = Vector3()

var deacceleration = 16
var max_slope_angle = 30

onready var camera = $RotationHelper
onready var rotation_helper = $RotationHelper/Camera

var mouse_sensitivity = 0.08

func _ready():
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)

func _physics_process(delta):
	process_input(delta)
	process_movement(delta)

func process_input(delta):
	dir = Vector3()
	var cam_xform = camera.get_global_transform()

	var input_movement_vector = Vector2()

	if Input.is_action_pressed("movement_forward"):
		input_movement_vector.y += 1
	if Input.is_action_pressed("movement_backward"):
		input_movement_vector.y -= 1
	if Input.is_action_pressed("movement_left"):
		input_movement_vector.x -= 1
	if Input.is_action_pressed("movement_right"):
		input_movement_vector.x += 1

	input_movement_vector = input_movement_vector.normalized()
	
	dir += -cam_xform.basis.z * input_movement_vector.y
	dir += cam_xform.basis.x * input_movement_vector.x

	if is_on_floor():
		if Input.is_action_just_pressed("movement_jump"):
			vel.y = jump_speed

	if Input.is_action_just_pressed("ui_cancel"):
		if Input.get_mouse_mode() == Input.MOUSE_MODE_VISIBLE:
			Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
		else:
			Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)

func process_movement(delta):
	dir.y = 0
	dir = dir.normalized()

	vel.y += delta * gravity

	var hvel = vel
	hvel.y = 0

	var target = dir
	if Input.is_action_pressed("movement_run"):
		target *= run_speed
	else:
		target *= walk_speed

	var accel
	if dir.dot(hvel) > 0:
		accel = acceleration
	else:
		accel = deacceleration

	hvel = hvel.linear_interpolate(target, accel * delta)
	vel.x = hvel.x
	vel.z = hvel.z
	vel = move_and_slide(vel, gravity_dir, 0.05, 4, deg2rad(max_slope_angle), false)

func _input(event):
	if event is InputEventMouseMotion and Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
		rotation_helper.rotate_x(deg2rad(event.relative.y * mouse_sensitivity * -1))
		self.rotate_y(deg2rad(event.relative.x * mouse_sensitivity * -1))

		var camera_rot = rotation_helper.rotation_degrees
		camera_rot.x = clamp(camera_rot.x, -70, 70)
		rotation_helper.rotation_degrees = camera_rot