Clamp Both Axes
Part of the Input and Movement section of Coddy's Godot journey. Lesson 22 of 28.
A top down hero can leave the screen on four sides. A Vector2 has its own clamp that keeps both numbers in range:
position = position.clamp(Vector2(16, 16), Vector2(624, 344))The first vector is the top left corner. The second is the bottom right corner. Each number of position stays between the matching numbers of the two corners.
The hero is a circle about 32 pixels across. So its middle stays 16 pixels from each edge of the 640 by 360 screen.
Challenge
EasyKeep the hero on the screen on all four sides.
- After
move_and_slide(), setpositionwithposition.clamp(). - Clamp it between
Vector2(16, 16)andVector2(624, 344).
Press Play and walk into a corner: the hero stops there, fully on screen. Then Check.
Try it yourself
extends CharacterBody2D
var speed = 200
func _physics_process(delta):
velocity = Input.get_vector("move_left", "move_right", "move_up", "move_down") * speed
move_and_slide()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground