As you can see from the video above, my character moves on his own constantly even without keyboard input. It’s simply guided by my Camera3D. I have a feeling I know the source of the error, the get_facing_direction function always returns the vector, (0, 0, 1) at minimum, so there is no ZERO vector at all. I tried forcing a ZERO vector by making use of if statements, so that if there is no keyboard input then use a ZERO vector as the direction vector. However, that didn’t work well since whenever I try clicking the keys it would follow the directions of the x and z axis, instead of following where the camera is facing.
extends CharacterBody3D
signal noInput
@export var speed = 5.0
@export var jump_speed = 4.5
@export var g = 12.81
var camera3dScript = Camera3D.new()
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
var theVelocity = Vector3.ZERO
func _physics_process(delta):
$"../CameraPivot".position = position
var direction = $"../CameraPivot/Camera3D".get_facing_direction()
# Add the gravity.
# print(gravity)
#var direction = camera3dScript.get_facing_direction()
#print(direction)
if Input.is_action_pressed("move_left"):
direction.x -= 1
if Input.is_action_pressed("move_right"):
direction.x += 1
if Input.is_action_pressed("move_up"):
direction.z -= 1
if Input.is_action_pressed("move_down"):
direction.z += 1
if direction != Vector3.ZERO:
direction = direction.normalized()
$Pivot.basis = Basis.looking_at(direction)
theVelocity.x = direction.x * speed
theVelocity.z = direction.z * speed
if not is_on_floor():
theVelocity.y -= g * delta
elif is_on_floor() and Input.is_action_pressed("jump"):
theVelocity.y = jump_speed
velocity = theVelocity
move_and_slide()
Above is the CharacterBody3D code, and below is the Camera3D code,
extends Camera3D
# Sensitivity of the mouse
var sensitivity = 0.1
# Rotation angles
var rotation_x = 0.0
var rotation_y = 0.0
func _ready():
# Capture the mouse pointer
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func get_facing_direction():
# The direction the camera is facing is the negative z-axis of the camera's transform
#print(-global_transform.basis.z)
return -global_transform.basis.z
func _unhandled_input(event):
#print(event)
if event is InputEventMouseMotion:
var direction = get_facing_direction()
#print("Camera is facing: ", direction)
_rotate_camera(event.relative)
func _rotate_camera(mouse_delta):
# Update rotation angles based on mouse movement
rotation_x -= mouse_delta.y * 1
rotation_y -= mouse_delta.x * 1
# Clamp the x rotation to avoid flipping the camera
rotation_x = clamp(rotation_x, -90, 90 )
# Apply rotation
rotation_degrees = Vector3(rotation_x, rotation_y, 0)
Any help is appreciated, and thank you!