I’ve seen other tutorials change the position of the player within the screen region after calling move_and_slide()
like is taught in this lecture, but it feels weird to me and seems as if it could potentially be prone to visual glitches like vibrating. I could be wrong because I’m inexperienced, but it seems like we should avoid moving the player at all if it’s already at the boundary. (Just had a thought while writing this – maybe move_and_slide()
doesn’t take effect until after the _physics_process()
function returns? If so, vibrating wouldn’t be a concern. If someone could confirm this, that would be great!)
To do this, I set my _physics_process()
function up like this:
func _physics_process(delta):
var move = Vector2(0, 0)
var screen_size = get_viewport_rect().size
if Input.is_action_pressed("move_right") and global_position.x < screen_size.x:
move.x += speed
if Input.is_action_pressed("move_left") and global_position.x > 0:
move.x -= speed
if Input.is_action_pressed("move_down") and global_position.y < screen_size.y:
move.y += speed
if Input.is_action_pressed("move_up") and global_position.y > 0:
move.y -= speed
velocity = move
move_and_slide()
This will avoid moving the player to an invalid position at all and doesn’t directly set global_position
. The effect is the same as clamping global_position
. I was just wondering if there’s a reason we should do one approach over the other, or if it’s just a personal preference sort of thing? Again, I’ve seen other tutorials use clamp before, but to me it just seems odd when we could check the values before calling move_and_slide()
to avoid moving to an invalid position to begin with.