How to make character only move left and right using mouse to move movement?

Godot Version

4.3

Question

How to make character only move left and right using mouse to move movement?

My code is working however I would like the characterbode2D to move only in two directions



@onready var avg_speed : float = 200.0
@onready var inc_speed : float = 350.0
@onready var run_distance : float = 200.0


func _physics_process(delta):
	if global_position.distance_to(get_global_mouse_position()) < 10: return
	
func _process(delta):
	var cursor_pos: Vector2 = get_viewport().get_mouse_position()
	var distance_to_cursor: float = position.distance_to(cursor_pos)
	
	

	var speed : float =  avg_speed if distance_to_cursor < run_distance else inc_speed


	# Cursor moves left and right
	if distance_to_cursor > 1:
		var direction : Vector2 = (get_global_mouse_position() - global_position).normalized()
		velocity = direction * speed
	# if cursor is far away from Angel, Angel speeds up
	else: 
		velocity = Vector2.ZERO
	
	move_and_slide()

just set “velocity.y = 0” before move_and_slide

Or just set velocity.x rather than velocity

Or change this

var direction : Vector2 = (get_global_mouse_position() - global_position).normalized()

To this

var direction : Vector2 = (get_global_mouse_position().x - global_position.x,0).normalized()

1 Like

Thank you!

1 Like