Avoid setting global_position when out of bounds?

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.

I was thinking the same thing to be honest, and would like to hear if this would be the better approach to avoid the clamp as well. At least I’m not alone with this thought lol

id have to do a bit more digging, but was reading up on an interesting thread that goes through the execution order.
its bound to be in the docs somewhere, but i cant quite find out where :frowning:

< When EXACTLY do _process and _physics_process actually execute relative to another? : godot (reddit.com)>

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms