Godot Prevent Player From Going Out of Screen (2D)

Mar 5, 2021

Use clamp on [Node2D.position]https://docs.godotengine.org/en/stable/classes/class_node2d.html#class-node2d-property-position.

extends KinematicBody2Dconst GRAVITY = 200.0const WALK_SPEED = 200const JUMP_SPEED = 100var screen_sizevar velocity = Vector2()# Called when the node enters the scene tree for the first time.func _ready():    screen_size = get_viewport_rect().sizefunc _physics_process(delta):       # gravity    velocity.y += delta * GRAVITY        # left and right movement    if Input.is_action_pressed("ui_left"):        velocity.x = -WALK_SPEED    elif Input.is_action_pressed("ui_right"):        velocity.x =  WALK_SPEED    else:        velocity.x = 0            # jump    if Input.is_action_pressed("ui_up"):        velocity.y -= JUMP_SPEED            # move current node    move_and_slide(velocity, Vector2(0, -1))         # prevent movement exceed screen    position.x = clamp(position.x, 0, screen_size.x)    position.y = clamp(position.y, 0, screen_size.y)   

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.