# This script controls a top-down player character using input and rotates towards the mouse or right stick. extends CharacterBody2D # Player movement speed (pixels per second) @export var speed = 200 @export var friction = 16 # Rotation speed (radians per second) - adjust for desired rotation speed @export var rotation_speed = PI * 4 # Rotate 2 full circles per second # Use mouse for rotation? If false, uses gamepad right stick. @export var rotate_with_mouse = true # Called every physics frame. 'delta' is the elapsed time since the previous frame. func _physics_process(delta): # --- Movement Logic --- var input_vector = Input.get_vector("move_left", "move_right", "move_up", "move_down") # Set the velocity based on input if input_vector != Vector2.ZERO: velocity = input_vector * speed else: # If no input, stop the player (optional, you might want friction instead) velocity = lerp(velocity, Vector2.ZERO, friction * delta) # Move the player and handle collisions using CharacterBody2D's move_and_slide move_and_slide() # --- Rotation Logic --- var target_rotation_direction = Vector2.ZERO if rotate_with_mouse: # Get the mouse position in world coordinates var mouse_position = get_global_mouse_position() # Calculate the direction vector from the player to the mouse target_rotation_direction = global_position.direction_to(mouse_position) else: # Get right analog stick input target_rotation_direction = Input.get_vector("rotate_left", "rotate_right", "rotate_up", "rotate_down") # If there is a valid rotation direction (either from mouse or stick input) if target_rotation_direction != Vector2.ZERO: # Calculate the target rotation angle in radians var target_angle = target_rotation_direction.angle() # Smoothly rotate the player towards the target angle # Using lerp_angle for smooth interpolation of angles rotation = lerp_angle(rotation, target_angle, rotation_speed * delta) # Note: Make sure you have input actions configured in Project Settings -> Input Map: # - "move_up", "move_down", "move_left", "move_right" for movement. # - If not using mouse rotation, add "rotate_up", "rotate_down", "rotate_left", "rotate_right" # and map them to the right analog stick axes (e.g., Joy Axis 4- for left, Joy Axis 4+ for right, etc.)