# 4-way directional movement instead of 8-way

4.2.1 Latest

### Question

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!

Set direction.y to 0 or direction.x to 0 if both of them are not 0.

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()

``````

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.