My character behaves weirdly. When I rotate it, it sometimes (more often than not) it drifts slightly to a side instead of going straight the direction it is facing.
This is the code I'm using right now:
extends CharacterBody3D
@onready var spring_arm = $SpringArm3D
const GRAVITY = 20.0
const FLY_IMPULSE = 8.0
const MAX_SPEED = 10.0
const ACCELERATION = 20.0
const ROTATION_SPEED = 1.0
var camera_rotation = Vector3.ZERO
var move_direction = Vector3.ZERO
var rotation_direction = 0.0
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
func _physics_process(delta: float) -> void:
# Move the bird downwards at a constant rate
velocity.y -= GRAVITY * delta
velocity.y = clamp(velocity.y, -MAX_SPEED, MAX_SPEED)
if Input.is_action_pressed("move_forward"):
move_direction = (transform.basis * Vector3(0, 0, -1.0)).normalized()
else:
move_direction = Vector3.ZERO
velocity += move_direction
velocity.x = clamp(velocity.x, -MAX_SPEED, MAX_SPEED)
velocity.z = clamp(velocity.z, -MAX_SPEED, MAX_SPEED)
# Flap the bird's wings and go upwards if spacebar is pressed
if Input.is_action_pressed("flap"):
velocity.y = FLY_IMPULSE
# Update the bird's position and rotation
move_and_slide()
# Rotate the bird left or right based on input
rotation_direction = 0.0
if Input.is_action_pressed("move_left"):
rotation_direction = ROTATION_SPEED
if Input.is_action_pressed("move_right"):
rotation_direction = -ROTATION_SPEED
rotation.y += rotation_direction * delta
func _input(event: InputEvent) -> void:
# Handle mouse movement to control camera rotation and speed
if event is InputEventMouseMotion:
camera_rotation.x -= event.relative.y * 0.005
camera_rotation.x = clamp(camera_rotation.x, -1.5, 1.5)
camera_rotation.y -= event.relative.x * 0.005
spring_arm.rotation = Vector3(camera_rotation.x, camera_rotation.y, 0)
Alternatively I tried using the objects direction like so:
# Calculate the bird's forward direction based on its rotation
var forward_direction = -get_global_transform().basis.z
# Move the bird forwards in its own forward direction on the press of the W button
if Input.is_action_pressed("move_forward"):
move_direction = forward_direction * ACCELERATION * delta
else:
move_direction = Vector3.ZERO
This however yielded the same result.
Any idea why this is happing or how I can prevent it? Thanks in advance!