Hello! I’m trying make my Character move in only 4 directions (up, down, left, right) with any method of control whether that’s keyboard, mouse, joystick, or D-Pad. Currently, I have a basic script to move my player, but it is the standard 8-way diagonal movements.
extends CharacterBody2D
var speed = 600
func _physics_process(delta):
var direction = Input.get_vector("left", "right", "up", "down")
velocity = direction * speed
move_and_slide()
This works perfectly fine for diagonal movement, but I want to keep the player restricted. Thanks in advance!
That makes total sense! Not sure why I overlooked that! Thank you
EDIT: Wanted to provide my solution for others that might run into the same problem later in the development cycle of Godot Engine 4 I’m also very aware there is probably a more programmatically better way to do this, but this is my first time learning any sort of coding so this was my way of fixing my issue. Any critiques are welcome!
extends CharacterBody2D
# speed in pixels/sec
var speed = 500
func _physics_process(delta):
# setup direction of movement
var direction = Input.get_vector("left", "right", "up", "down")
# stop diagonal movement by listening for input then setting axis to zero
if Input.is_action_pressed("right") || Input.is_action_pressed("left"):
direction.y = 0
elif Input.is_action_pressed("up") || Input.is_action_pressed("down"):
direction.x = 0
else:
direction = Vector2.ZERO
#normalize the directional movement
direction = direction.normalized()
# setup the actual movement
velocity = (direction * speed)
move_and_slide()