•

Check out our Community Blogs

Register and join over 40,000 other developers!

### Recent Blog Entries

• phi

I love this community !

• JackJames

hi i am jack i am seo expert jack james would love you to read new post

# Javascript Is/If Collision Functions (My Functions)

function javascript

2 replies to this topic

### #1 YoungPythoner

YoungPythoner

CC Newcomer

• Member
• 17 posts
• Location:Turkey, Hatay
• Programming Language:Python, Bash, Others
• Learning:JavaScript, Delphi/Object Pascal

Posted 03 July 2015 - 07:29 PM

Hi! I wrote a is/if collision functions. They're for games and anything. They are includes:

Up, down, left, right collisions.

Hope you like it!

```function IfCollisionDown(x1, y1, w1, h1, x2, y2, w2, h2)
{
if (x1>x2-(w2/2)&&x1<x2+(w2/2)&&y1-(h1/2)<y2+(h2*1.5)&&y1>y2)
{
return true
}
else
{
return false
}
}

function IfCollisionRight(x1, y1, w1, h1, x2, y2, w2, h2)
{
if (y1<y2+(h2/2)&&y1>y2-(h2/2)&&x1-(w1/2)<x2+w2&&x1>x2)
{
return true
}
else
{
return false
}
}
```

• 0

### #2 leon242

leon242

CC Lurker

• Just Joined
• 2 posts

Posted 21 July 2016 - 09:49 AM

Excellent, I'll take it

• 0

### #3 RikRoy

RikRoy

CC Lurker

• New Member
• 4 posts

Posted 15 March 2017 - 06:11 AM

First, it is a bit confusing whether x1, y1, x2, y2  are  the  and Y components of center of the object or of its upper-left corner. Also if the w1, h1, w2, h2 are absolute co-ordinates or are the length from the upper-left corner as different platforms and programmers prefer to use them in different ways. So, you should mention that in your further tutorials

Next up, the function are a bit defective I think because the if conditions are not satisfied unless the first object is halfway through the second object (I may have misinterpreted it and in that case, please correct me). I think a better version of the code would be:

```function collisionDown(x1,y1,w1,h1,x2,y2,w2,h2){ //Only for objects2 below object1
if( ((x1+w1)>x2) && (x1<(x2+w2)) && ((y1+h1)>y2) && (y1<y2) ){
return true;
}else{
return false;
}
}

function collisionRight(x1,y1,w1,h1,x2,y2,w2,h2){ //Only for objects2 on right of object1
if( ((y1+h1)>y2) && (y1<(y2+h2)) && ((x1+w1)>x2) && (x1<x2) ){
return true;
}else{
return false;
}
}
```

where x1, y1, x2, y2 are upper-left co-ordinates of the objects and w1, h1, w2, h2 are the relative heights and widths, that is the distance of the bottom right point to the top-left point

if there are any mistakes in my code, please point out. I've come back in the game after very long. Please forgive any mistakes

and

no offense!

Cheerio

Edited by RikRoy, 15 March 2017 - 06:12 AM.

• 0

### Also tagged with one or more of these keywords: function, javascript

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download