# How do I do "if Collision" statements

## Recommended Posts

When I did 2D coding game coding, in my games I had a "if collision" function statement that stated "if" a specific object collided with another specific object then something happens as in the code function below (I wrote notes in the code below to explain what the entities do):

``````//Note that the "o" means object as in "Object X;" oy means "Object Y," and so forth.
//Also note that "e" means enemy as in "Enemy X;" ey means "Enemy Y," and so forth.

function Collision(ox, oy, ow, oh, ex, ey, ew, eh) {

if (ox > ex && ox < ex + ew && oy > ey && oy < ey + eh) {
return true;
}
if (ox + ow < ex + ew && ox + ow > ex && oy > ey && oy < ey + eh) {
return true;
}
if (oy + oh > ey && oy + oh < ey + eh && ox > ex && ox < ex + ew) {
return true;
}
if (oy + oh > ey && oy + oh < ey + eh && ox + ow < ex + ew && ox + ow > ex) {
return true;
}
}``````

Then I would just call the above function as in let's say getting a "player" character and an "enemy" character to collide:

``````//

if (Collision(playerX, playerY, playerWidth, playerHeight, enemyX, enemyY, enemyWidth, enemyHeight)){

//Here is where we'd choose what happens when the player and an enemy collides

} ``````

And I could call on the same collision function throughout my game if I wanted an event to happen after a collision. Thus, I was trying to figure out how to do a similar type of "if collision" process/statement in Babylon.js. Does anybody know one? Thanks!

BTW, if anybody is doing 2D game programming in JavaScript, feel free to use the above collision code if you need one. It's a rectangle collision code that works well. Thanks again!

##### Share on other sites

Hi,

This is already implemented in the framework. You can find info here:

Or using the physics engine:

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.