Menu
CoddyTech

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 icon

Challenge

Easy

Keep the hero on screen on all four sides. After move_and_slide(), clamp position between Vector2(16, 16) and Vector2(624, 344).

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Input and Movement

Practice on your own: Godot playground