Jump to content

How do I do "if Collision" statements


En929
 Share

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!

 

 

 

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...