How to make CharacterBody3D move only on X-Axis

Godot Version

4.4

Question

Hello everyone! I’ve had an issue with trying to code an enemy for my game, and I need help! I’m trying to get the CharacterBody3D to move left and right while facing the player, but I can only get them to move forward. Is there any way I can get them to move how I’d like? Below is the script for the basic forward movement.

func _process(delta):
	match currentState:
      states.WALKTOWARDS:
			$PunchZone/CollisionShape3D.set_deferred("disabled", false)
			$AnimationPlayer.play("Walk")
			$Fire.play("RESET")
			velocity = Vector3.ZERO
			nav_agent.set_target_position(player.global_transform.origin)
			var next_nav_point = nav_agent.get_next_path_position()
			velocity = (next_nav_point - global_transform.origin).normalized() * RUN_SPEED
			
			look_at(Vector3(player.global_position.x, global_position.y, player.global_position.z), Vector3.UP)

From the code the enemy will move towards the player and looking to the player too.
De direction applied is based on that. You need to split direction and velocity and re calculate a new velocity based on the new direction which should be perpendicular to the calculated at WALKTOWARDS.
Lets say:
var direction : Vector3 = (next_nav_point - global_transform.origin).normalized()
direction = direction.rotated(Vector3.UP, PI/2)
velocity = direction * RUN_SPEED

Thanks! This worked great!

1 Like