Detecting overlapping: No collisions and no physics required!

Knowledgebase / Detecting overlapping: No collisions and no physics required!

We’re going to find an alternate method of detecting when an object touches another object by detecting overlapping instead. This tutorial builds on concepts covered in Picking Up Objects using Collision detection and Pow! Shooting projectiles (missiles, bullets, lasers).

Step 1: The collision problem

In this example game, the player flies along to collect stars.

ezgif-2885398418

The stars are collected when they detect a collision using the “When I am touched get toucher” block. Unfortunately the stars block the player from travelling through them. Here’s the script the stars use:

Screen Shot 2016-07-07 at 4.05.20 pm

We could attempt to solve this by disabling the collisions or disabling physics on the stars, but then they wouldn’t be able to detect the collision that allows the plane to collect them! So we need to find another solution…

Step 2: The overlapping solution

Instead of “When I am touched get toucher”, we’ll use “myself overlaps instance toucher” from Sensing. Grab that block, and drag it out into the work space.

Screen Shot 2016-07-07 at 5.03.41 pm

This block checks for the condition “is myself overlapping an instance?” We can use an if-statement to check if that condition is true. Since we already have our previous “if” block from the original script, we can detach the “instance toucher has tag plane” block from the “if” block, and replace it with the “myself overlaps instance” block. And since we aren’t going to be detecting when this object is touched, we can get rid of the “When I am touched get toucher block”, but keep the blocks that are inside it by dragging them out.

Screen Shot 2016-07-07 at 5.31.59 pm

We don’t want to be detecting “instance toucher”, instead we want to be detecting the object with the tag “plane” (or whatever tag your player character has). Replace the “instance toucher” block by dragging in the “first instance by tag tag name” block from Sensing. Make sure you type the correct tag in that block.

Screen Shot 2016-07-07 at 5.42.51 pm

Step 3: Which event block?

We were using the “When I am touched get toucher” event block, but now we need a new one. Since there is no “When I am overlapped” event, we’ll just need constantly check that condition, so grab the “Constantly” block from Events, and drag the “if” block inside it.

Screen Shot 2016-07-07 at 4.21.47 pm

Lastly, we need to stop collisions so that the objects can overlap each other. The easiest way to do this is with the “Set physics enabled false” block from Physics, so drag that into the when created block.

Now test out your game.

ezgif-1513084476

Congratulations! You’ve found a new way to detect when objects collide without physically blocking each other.