Godot Version
4.3
Question
I have a simple player movement script built off the default one. However the default doesn’t have a section for looking around based on the mouse’s movement. I made my own and used 2 nodes, camera3d and node3d (named Head). Head is used for x rotation and cam for y rotation. When I move forward by only pressing the W button, the x velocity also changes by a small amount, causing me to move left or right slightly. Strangely this only happens when I am looking forward. If I look directly up or down the problem goes away. This is the Player’s code.
extends CharacterBody3D
var speed = 7.0
const JUMP_VELOCITY = 300
var friction = 0.3
var sens = 0.005
@onready var head: Node3D = $Head
@onready var cam: Camera3D = $Head/PlayerCam
@onready var col: CollisionShape3D = $PlayerCol
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventMouseMotion:
cam.rotate_x(-event.relative.y * sens)
head.rotate_y(-event.relative.x * sens)
cam.rotation.x = clamp(cam.rotation.x,deg_to_rad(-80),deg_to_rad(80))
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y += JUMP_VELOCITY * delta
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var input_dir := Input.get_vector("left", "right", "up", "down")
var direction := (head.transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
if direction:
velocity.x = move_toward(velocity.x,direction.x * speed,friction)
velocity.z = move_toward(velocity.z,direction.z * speed,friction)
else:
velocity.x = move_toward(velocity.x, 0, friction)
velocity.z = move_toward(velocity.z, 0, friction)
print(velocity.x)
move_and_slide()