Menu
CoddyTech

Clamp to the Screen

Part of the Input and Movement section of Coddy's Godot journey. Lesson 21 of 28.

Run left and the hero leaves the screen. clamp(value, low, high) keeps a number between two ends. It returns low if value is below it, high if value is above it, and value otherwise. clamp(700, 14, 626) is 626.

Clamp the position after moving, and store the result:

move_and_slide()
position.x = clamp(position.x, 14, 626)

position is the hero's middle, and the hero is 28 pixels wide. So its middle stays 14 pixels from each edge of the 640 pixel screen, and the whole hero stays in view.

challenge icon

Challenge

Easy

Keep the whole hero on screen. After move_and_slide(), clamp position.x between 14 and 626.

Try it yourself

extends CharacterBody2D

var speed = 220
var acceleration = 900
var friction = 2400
var gravity = 1000
var jump_velocity = -500

func _physics_process(delta):
	velocity.y += gravity * delta
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = jump_velocity
	var direction = Input.get_axis("move_left", "move_right")
	if direction == 0:
		velocity.x = move_toward(velocity.x, 0, friction * delta)
	else:
		velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)
	if direction > 0:
		$Look.scale.x = 1
	if direction < 0:
		$Look.scale.x = -1
	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