Skip to content

Instantly share code, notes, and snippets.

@aindong
Created February 6, 2022 02:56
Show Gist options
  • Save aindong/d99cfa3268d866cfe33c466b8198b1d6 to your computer and use it in GitHub Desktop.
Save aindong/d99cfa3268d866cfe33c466b8198b1d6 to your computer and use it in GitHub Desktop.
Limit the movement of sprite to screen only (CLAMP)
extends Area2D
export var speed = 400.0
var screen_size = Vector2.ZERO
# Called when the node enters the scene tree for the first time.
func _ready():
screen_size = get_viewport_rect().size
print(screen_size)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
var direction = Vector2.ZERO
if Input.is_action_pressed("move_right"):
direction.x += 1
if Input.is_action_pressed("move_left"):
direction.x -= 1
if Input.is_action_pressed("move_down"):
direction.y += 1
if Input.is_action_pressed("move_up"):
direction.y -= 1
if direction.length() > 1:
direction = direction.normalized()
position += direction * speed * delta
position.x = clamp(position.x, 0, screen_size.x)
position.y = clamp(position.x, 0, screen_size.y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment