This code will move your kinematic body sort of like a car in old school top down GTA games - i think that was the effect you were going for. I commented it pretty heavily, let me know if you have any questions on it. This code also assumes Player is a KinematicBody2D node!
var player_movement_speed = 50
var movement_vector = Vector2.ONE
var magnitude = 1
func _ready():
OS.set_window_size(Vector2(OS.get_screen_size().x, OS.get_screen_size().y))
add_child(player)
func _physics_process(_delta):
if Input.is_key_pressed(KEY_W):
# changing directions? reset magnitude
if magnitude < 0:
magnitude = 0
magnitude += 1
if Input.is_key_pressed(KEY_S):
# changing directions? reset magnitude
if magnitude > 0:
magnitude = 0
magnitude -= 1
if Input.is_key_pressed(KEY_A):
player.rotation_degrees -= 2.5
if Input.is_key_pressed(KEY_D):
player.rotation_degrees += 2.5
# rotation_degrees * (PI/180) converts degrees to radians
var rotation_radians = player.rotation_degrees * (PI/180.0)
# get the direction vector assuming the base kinematic body sprite faces up
# change Vector2.UP accordingly if your sprite does not
# .normalized() makes sure the vector is a unit vector (length = 1)
var direction_vector = Vector2.UP.rotated(rotation_radians).normalized()
# multiply our direction vector with our magnitude (how long the player has been holding
# down the direction) and our player_movement_speed and scale the vector to keep it
# in step with our physics frames so movement is consistent across different frame rates
movement_vector = direction_vector * magnitude * player_movement_speed * _delta
# use the move_and_slide() function to move out kinematicbody
# also look into using move_and_collide() and move_and_slide_with_snap()
# to get your desired movement behavior
movement_vector = player.move_and_slide(movement_vector)
How can you make this code be a little more like a character controller instead of a car controller?
slightly_seasoned | 2021-04-27 19:21
Maybe changing how changing directions is handled so a character has to slow down before moving backwards?
if Input.is_key_pressed(KEY_W):
magnitude += 1
if Input.is_key_pressed(KEY_S):
magnitude -= 1
I’m not entirely sure what kind of effect you’re looking for with the controls.