Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


19. March 2015

 

In this tutorial we are going to take a look at two key topics in Godot game development, Collision Detection and Physics Simulations.  Collision Detection is simply detecting if two objects overlap.  Physics on the other hand simulates the movement and interaction of game objects based on physical properties.  This of course also includes handling collisions.  There is also a video of this tutorial and this might be one of those times, due to all of the motion in the results, that you may in fact want to refer to the video even if you prefer text based tutorials.  So if you struggle to understand what I am talking about here, be sure to quickly check the video, it may have the answer.

 

You can watch the video here, or embedded below.

 

Checking for Collisions

 

Let’s start with checking collisions between two objects, in this case, two different Sprite objects.  I have created the following scene:

image

It’s simply two sprite objects side by side.  I then attached a script to the one on the left.  This script updates the position of the left sprite until a collision occurs, at which point it resets to the beginning and does it all over again.  Like so:

anim

 

Let’s take a look at the script now:

extends Sprite

var start_pos = Vector2()
var box1 = null
var box2 = null

func _ready():
   set_process(true)
   start_pos = get_pos()
   box1 = RectangleShape2D.new()
   box2 = RectangleShape2D.new()



func _process(delta):
   # Get a reference to the other sprite
   var sprite2 = get_node("/root/SceneRoot/Sprite 2")
   
   # Update our location
   self.move_local_x(0.1)
   
   # set the boundaries of each RectangleShape2D to those of the texture making up our sprite
   # values are relative to center, thus half width and height
   box1.set_extents(Vector2(self.get_texture().get_size().width/2,self.get_texture().get_size().height/2))
   box2.set_extents(Vector2(
sprite2.get_texture().get_size().width/2,sprite2.get_texture().get_size().height/2)) #Now check to see if box1 at sprite1's pos collided with box2 and sprite2's position if(box1.collide(get_transform(),box2,sprite2.get_transform())): set_pos(start_pos) # it did, so reset position to beginning, what's old is new again!

Essentially what you are doing here is creating a RectangleShape2D using the boundaries of each Sprite’s texture image.  AKA, creating a rectangle the size of the texture.  You then check if box1 at the transformed position of Sprite1 collides with box2 at the transformed position of Sprite2.  Of course, since they both use the same texture map, you don’t actually need to create two different RectangleShape2D objects!  Also, since the size never changes, you don’t actually need to set_extents() in process().  There are a number of simple shape classes that can be used to check for collisions such as concave and convex polygons, circles and even rays ( for mouse picking ).

 

This is one way to check for simple collisions.  However you will quickly find it gets unwieldy as you add more and more objects and have to check them against each other.  Fortunately the physics engine makes this process a whole lot easier.

 

Physics Simulations

 

Now that we looked at a way to test for collisions, lets move on and discuss the physics system.  Basically a physics engine simulates movement using complex math, calculating how items interact with each other and external forces like gravity.  The physics simulation then updates, either on a fixed or per frame basis, a set of objects with the new locations calculated by the simulation.  You then update your visible game objects positions accordingly.  In Godot however, you don’t generally need to perform that last step, it’s done automatically.

 

Let’s start with an extremely simple example, gravity.

 

First we start by creating a RigidBody2D node:

image

 

Next, parented to the RigidBody2D node, create a sprite node.  I am using the default icon.png that comes with Godot.  Your heirarchy should look like this:

image

 

… and that’s it.  You have now created a physics object that gravity will be applied to.  Run your game and you should see:

anim2

 

Now let’s pause a second to see exactly what is happening here.

 

First, let’s start with the RigidBody2D part…  There are three kinds of physics objects you can use in your 2D game world:

image

The biggest difference is how they are dealt with by the simulation.

 

A RigidBody can be thought of as a typical physics object.  It’s the most processing intensive, but it’s also got the most functionality.  Unless you have a reason otherwise, if something needs physics, it’s probably a rigid body.  This is a physics object that can move, can collide with other objects and itself by collided with.

 

Next up is the StaticBody2D.  This is an unmoving object in your world.  Basically things can hit it, it can be hit, but it doesn’t move.  It also takes a lot less processing power to handle.  Generally things like the world, or invisible but unmoving triggers will be static bodies.

 

Finally is KinematicBody2D.  This is a physics object that doesn’t have the range of functionality of a rigid body ( for example, you cant apply force to it ), but can move and can collide with other physics objects.  The biggest thing about a Kinematic body is that its motion is generally controlled directly by you no the physics simulation.  Generally this is the character sprite.  You want the physics simulation to react to its actions, but you generally control those movements directly in code.

 

So, those are the three major types of physics objects, now let’s look at global settings.  You notice how gravity is being applied to our simulation automatically?  Where is this coming from?

 

The answer is trust ole project settings:

image

 

So… what do those values means?  Well this is one of the nice things about working entirely in Godot.  In many physics engines like Box2D, you work in meters, then have to translate from meters to pixels when transforming your sprites.  In godot, these values are in pixels.  So a gravity value of 98 means gravity moves at 98 pixels per second.

 

Now what about Rigid Body settings?  Well let’s take a look:

image

 

Mass Friction and Bounce are the most commonly used values.  Hey, aren’t mass and weight the same thing?  Nope, not exactly.  Mass is the amount of “stuff” that composes and object, while weight is the amount that stuff weighs.

 

Consider the classic question “What weighs more, a ton of bricks or a ton of feathers?”  Both objects would have identical weights ( one ton ), but vastly different masses.  In some ways it can be easier to think of mass instead as density. 

 

Friction on the other hand is how it slides in contact with another surface.  Picture sliding a mouse down a surface on a 45 degree angle.  If one surface was rubber and the other was glass, the mouse is going to move at vastly different rates.  Friction controls this.   Bounce is often refered to as restitution.  This is the amount of, well, bounce in an object.  Or how much it reacts to a collision.  A rubber ball has a higher “Bounce” value, while a brick is almost 0.  Another key concept is sleep, this is the ability to turn the Rigid Body off during calculations, determines if it is or isn’t used as part of the over all simulation.  Linear and Angular velocity finally are the default movement values of the object.

 

Collisions Physics Style

 

Now let’s take a look at how collisions are handle using a Physics engine.  Let’s change the above scene to add another physics item, this time a static body, like so:

image

 

The top sprite has a RigidBody2D as it’s parent.  The bottom has a StaticBody2D for a parent.  Now we need to define a collision volume for each one, just like we did back at the beginning.  Simple add a new node to each Body ( not the sprite, it’s parent! ) of type CollisionShape2D, so your hierarchy looks like this:

image

 

Then for each CollisionShape2D, you need to pick a bounding shape.  With the CollisionShape2D selected in Inspector simply select the Shape dropdown and pick the one that is best suited:

image

Finally, size it so it covers the collide-able portions of your sprite:

image

 

Now when you run the game:

anim3

 

Tada!  Collisions calculated by the physics engine.  Now you can play around a bit with the physical properties of your Rigid Body and see how it reacts differently.

 

In this case we used a simple box for our collision detection, and that works well for box shaped objects.  But if your object isn’t box or circle shaped, what do you do?  Enter CollisionPolygon2D:

image

 

It works exactly the same as CollisionShape2D, but you can define the shape yourself.  Remove one of the CollisionShape2D nodes and replace it with a CollisionPolygon2D node.  With the Collision node selected, you will notice a new option in the 2D window:

image

 

Click the pen, and you can now draw a polygon around your object:

image

 

And once closed:

image

A MUCH more accurate representation of your object for collisions!

 

Kinematic Nodes

 

Finally let’s look at KinematicBody2D objects.  These are special in that the physics engine doesn’t control their motion, you do.  They can however collide with entities in the physics world.  Generally speaking, this is how you would create your character.  Unlike RigidBodies you cannot apply forces or impulses.  Instead you move them directly.  Let’s create a simple example:

 

First add a KinimaticBody2D to your scene, add a sprite and collision shape for it, like so:

image

 

Now apply a script to the KinematicBody2D with the following code:

extends KinematicBody2D



func _ready():
   set_process(true)
   
func _process(delta):
   move(Vector2(0.04,0))

We are simply moving the body by 0.4 pixels per update.  As you can see from the results however collisions will occur between your game code controlled object and the physics simulation:

anim4

 

There is obviously quite a bit more to the physics simulation.  You can create joints and springs and define what objects collide with other objects, but that covers most of the basics.  Be sure to watch the video if you struggle, as it covers things in a bit more detail!

 

The Video

 

Programming , ,

blog comments powered by Disqus

Month List

Popular Comments