Player walks straight through obstacle

Godot Version

v.4.2.2

Question

I’m (obviously) very new to Godot, and this is one of my first projects. I’m trying to create an obstacle that the player must move around. Currently, the player walks “beneath” it, despite both being on the same Z index/collision layers. There is no collision taking place.

Both the player and the obstacle are very simple: both have StaticBody2D as their root node, and both use CollisionShape2D (set to Rectangle). Neither have any other physic nodes connected to them.

I control the player using Vector2. I don’t think that would affect anything, but here’s the movement anyways:

func _process(delta):
	var velocity = Vector2.ZERO
	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(duck)
	else:
		$AnimatedSprite2D.stop()
		
	if velocity.x != 0:
		$AnimatedSprite2D.flip_v = false
		$AnimatedSprite2D.flip_h = velocity.x > 0
	
	position += velocity * delta

StaticBodys were designed to be not moved and affect physics. If you wish to move with physics you could try making them AnimatableBody2D and use the move_and_collide() function.

There is another physics node called CharacterBody2D that was designed specifically for this purpose. All you would have to do it not define var velocity because it is already built-in and replace the last line with move_and_slide() instead.

Of course you could also use a RigidBody2D (which I have no experience in),and use its built in apply_force() to move the body so that it follows the rules of physics.

So general rule of thumb, if you want physics to work do not ever directly change the Position of the node, instead use one of the many built-in physics movement functions.

1 Like

That’s not the problem. I think it may be the problem with the node tree. Most likely you’re colliding with the shape and moving it out of the way. The sprite you’re using didn’t stick to the collision shape and stayed in the same spot. You have to make sure the parent is somehow defined. The node tree usually does that.