Picking Up Objects using Collision detection

Knowledgebase / Picking Up Objects using Collision detection

We’re going to make it so an object can “collect” other objects by colliding with them. In this example we’ll have a bunch of apples that Newton can collect. This tutorial follows on from Move it! Physics movement and the constantly loop.

Step 1: Place a bunch of apples

Select the apple from the Game Objects sidebar, and place a bunch of them around in your level.

Screen Shot 2016-05-26 at 9.42.05 am

Note: if you don’t have the apple object from Newton’s Orchard pack, here’s how to get it.

Step 2: Detecting touch

Right-click on the object you want to collect the apples (Newton, if you’re following the previous tutorials) and select Edit Script.

We can use a block to detect when any other object touches this object. That block is under Physics, and is called “When I am touched, get toucher”. Drag this block out into the workspace.

ezgif-158300410

This block is an event block which can trigger the blocks inside it. It will get triggered when any object touches this object.

Step 3: Destroying the toucher

To “collect” the objects that Newton touches, we’ll use the “destroy” block from Control Flow. This block is named “Destroy myself”. Drag it into the “When I am touched, get toucher block”.

ezgif-741738457

If we leave it like this, the block will destroy Newton instead of destroying the apples. We need to target the “toucher” instead of “myself”, so go to the Variables tab, and drag “instance toucher” into the place of the “myself” block. You can then drag the “myself” block into the trash can.

ezgif-1055825980

Now play your game. The apples will all get collected (destroyed) when Newton touches them.