Trying to make a top-down 2d game, how do I make the motion for the player and why is my code not working?

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

extends CharacterBody2D

@export var move_speed : float = 100

func _physics_process(_delta):
var input_direction = Vector2(Input.get_action_strength(“right”)-Input.get_action_strength(“left”), Input.get_action_strength(“backward”)-Input.get_action_strength(“forward”))
var velocity = input_direction * move_speed

:bust_in_silhouette: Reply From: ShatteredReality

First off, you can use Input.get_vector() for this. Also you want to call normalize() on it too. Second, velocity is already a variable in CharacterBody2D. No need to redefine it. Just remove the var at the start of the line.

:bust_in_silhouette: Reply From: crossbito

You are using a local variable called “velocity”. Instead, you should use the “velocity” variable from “CharacterBody2D”.


var velocity = inputdirection * movespeed


velocity = inputdirection * movespeed

This will ensure that you are modifying the “velocity” variable of the “CharacterBody2D” object instead of creating a new local variable.