All lessons
Lesson 04

Mouse Aiming

Turn the player to face wherever the mouse goes, swap the cursor for a crosshair, and click the targets to pop them.

Loading the game engine. This takes a moment the first time.

The player still walks with WASD, but now it also turns to face the mouse every single frame. The normal mouse arrow is hidden, and a crosshair drawn in the scene follows the mouse in its place. Click a red target and it pops: that half is target.gd, which listens to the mouse instead of the keyboard.

The scenes

UI node · 2D node · % unique name · .tscn instanced scene

mouse_aiming.tscn
  • MouseAiming Node2D
  • AimPlayer CharacterBody2D player.tscn
  • Target1 Area2D target.tscn
  • Target2 Area2D target.tscn
  • Target3 Area2D target.tscn
  • Target4 Area2D target.tscn
  • Target5 Area2D target.tscn
  • Crosshair Node2D crosshair.tscn
crosshair.tscn
  • Crosshair Node2D crosshair.gd
  • HLine ColorRect
  • VLine ColorRect
  • Circle ColorRect
player.tscn
  • AimPlayer CharacterBody2D player.gd
  • Body Sprite2D
  • Pointer ColorRect
  • CollisionShape2D
target.tscn
  • Target Area2D target.gd
  • Outer ColorRect
  • Inner ColorRect
  • CollisionShape2D
extends CharacterBody2D

## How fast the player moves.
@export var speed: float = 180.0

# "_physics_process()" runs about 60 times a second. Godot calls it for you.
func _physics_process(_delta: float) -> void:
	# Move with WASD, exactly like every other lesson.
	var direction: Vector2 = Input.get_vector(
		"move_left", "move_right", "move_up", "move_down"
	)
	velocity = direction * speed
	move_and_slide()

	# "get_global_mouse_position()" asks where the mouse is on screen.
	# "look_at()" then turns the player to face that spot. Doing it every
	# frame is what makes the player track the mouse everywhere it goes.
	look_at(get_global_mouse_position())

	# Aiming left would turn the picture upside down, so mirror it back.
	$Body.flip_v = abs(rotation) > PI / 2