Checking for Objects Collision with Distances
-
Prerequisite
Introduction
We often need to check if 2 objects are touching each other. For example, if an avatar is touching a box, we can make the avatar sit on the box.
The easiest way to check if 2 objects are touching is to calculate the distance between them.
Calculating Distance Using X and Y Positions
When both objects are on the ground, we just need to check their distance using X and Y positions:
For example, the direct 2D distance between the avatar and the box is shown below:
Demo Program
In this example project, we put a box at Y of 100.
Then we move the avatar a little bit forward every time we press the “w” key
Try it yourself:
https://play.creaticode.com/projects/836c92f886f791086cf57b1c
Using 3D Distances
Sometimes 2D distances are not accurate enough. For example, suppose an object is floating in the air, and the avatar is right below it. Their 2D distance is close to 0, but they are Not touching each other. To account for the vertical distance, we need to calculate 3D distances:
Demo Program
In this example project, we put the box at Z of 140, and we move the avatar up until its 3D distance to the box is less than 110.
Try it yourself:
https://play.creaticode.com/projects/32f4e2bffc79c532fbeba129
-