Godot Version
4.2.1
Question
Hello all! I’m following Coding the player — Godot Engine (stable) documentation in English and there are a few things I don’t quite understand about how the character dimentions and clamp work together to keep the char in the boundaries of the screen. The thing that is confusing me the most is that my char ends up half out of the screen regardless of what I do.
Here is what I mean by “half out of the screen”:
It successfully stays within the boundaries but just half of it.
Here are my questions:
- Are the Player (Area2D) and the AnimatedSprite2D the same size?
- Is clamp meant to be applied in relation to the entire game viewport?
- Is clamp applied directly on restricting the Player (Area2D) ?
- If yes, is there some way I can make it take into the account the sprite dimensions?
I tried modifiying the line we get the screen_size
to deduct a plain vector like:
screen_size = get_viewport_rect().size - Vector2(100,100)
I thought that simply reducing the “screen_size” dimentions by the character dimension should do the trick but subtracting a regular vector isn’t affecting this in any way (I tried [1,1] ; [10,10] ; [100,100] ; etc).
but that doesn’t seem to do anything. The rest of the code is exactly the same as the tutorial; I also tried moving the clamp line to the bottom of the function after reading this explanation: Help With Screen Clamping - #2 by apples but that didn’t change anything either.
I’m adding the code here in case it’s necessary:
extends Area2D
# Using the export keyword on the first variable speed allows us to set its value in the Inspector.
@export var speed = 400 # How fast the player will move (pixels/sec).
var screen_size # Size of the game window.
# Called when the node enters the scene tree for the first time.
func _ready():
screen_size = get_viewport_rect().size - Vector2(1,1)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
var velocity = Vector2.ZERO # The player's movement vector.
if Input.is_action_pressed("move_right"):
velocity.x += 1
if Input.is_action_pressed("move_left"):
velocity.x -= 1
if Input.is_action_pressed("move_down"):
velocity.y += 1
if Input.is_action_pressed("move_up"):
velocity.y -= 1
if velocity.length() > 0:
velocity = velocity.normalized() * speed
$AnimatedSprite2D.play()
else:
$AnimatedSprite2D.stop()
# $ returns the node at the relative path
position += velocity * delta
position = position.clamp(Vector2.ZERO, screen_size)
if velocity.x != 0:
$AnimatedSprite2D.animation = "walk"
$AnimatedSprite2D.flip_v = false
$AnimatedSprite2D.flip_h = velocity.x < 0
elif velocity.y != 0:
$AnimatedSprite2D.animation = "up"
$AnimatedSprite2D.flip_v = velocity.y > 0
Thanks for the help!