I'm creating a game using Godot Engine and I can't figure out how to create a wall to prevent a player from walking out of the screen.
The player is able to walk out of the screen window. How do I prevent it from happening?
I tried to use the CollisionShape2D node but I don't think I know how to use it properly in a way that it works like I want it to.
Note: What I explain here also holds for the 3D counterpart of these nodes.
CollisionShape2D
and CollisionPolygon2D
do nothing on their own. Their purpose is to provide a shape for a parent CollisionObject2D
.
There are two kinds of CollisionObject2D
s: Area2D
and PhysicsBody2D
.
The Area2D
will detect other bodies or areas, but won't stop them from moving, which is not what you want.
There are three kinds of PhysicsBody2D
:
CharacterBody2D
: which is intended to be moved via script, usually to make character controllers.RigidBody2D
: which is moved by the physics engine, usually to make bodies that can be pushed around by other bodies.StaticBody2D
: which either do not move (or have a predefined motion). This is the one you want.Thus, you would setup a StaticBody2D
with a child CollisionShape2D
or CollisionPolygon2D
.
Now, I'm also going to point out that physic bodies interact with physic bodies. If you, for example, have created your character as an Sprite2D
, since the Sprite2D
only cares about graphics and does not have collisions it will not be stopped by the StaticBody2D
.
So you usually make your character as a body that can collide (usually a CharacterBody2D
, sometimes a RigidBody2D
), and it would, of course, have a child CollisionShape2D
or CollisionPolygon2D
, and also as child it can have your Sprite2D
or whatever else you need.
By making the Sprite2D
and other Node2D
s children of the physics body, they will move with it.
If you haven't decided between CharacterBody2D
and RigidBody2D
, I go into more length on which kind of node to use for what elsewhere. A very good abstract is the following: If something else can push it, use a RigidBody2D
. following the link you get the nuance and what to use for specific cases.
For the CollisionShape2D
to set its shape
property to a Shape2D
.
About making the boundary for the game, the recommendation is to use WorldBoundaryShape2D
for each edge. However, thick enough RectangleShape2D
would also work.
Alternatively, although not recommended, you could use a CollisionPolygon2D
covering the play area, and set its build_mode
to BUILD_SEGMENTS
, which results in a hollow polygon, so other bodies can be inside of it.