-3

Ok I got 2 images one of a player that I make jump and another one of a barrel that rolls towards the player. I searched on google to get all the code that I have together. The problem is I can't find a code that can detect collisions. I need that code so when the barrel hits the player its game over.

GamePlay press the start button and the barrel rolls towards the player , press anywhere onscreen to make player jump. The source code is here if you want to try it http://sourceforge.net/projects/pfbw/files/Platformer.zip/download Thanks for any help you can afford me. Every code I tried didnt work for collision detection.

<!DOCTYPEhtml>

<html>
    <head>
        <script>
        function jump() { // controls player jump
            document.getElementById("m").style.top = "250px";
            setTimeout(function () {
                document.getElementById("m").style.top = "390px";
            }, 1500)
        }

        function moving() { // controls barrel movement
            var pp = document.getElementById("b");
            var left = parseInt(pp.style.left);
            var tim = setTimeout("moving()", 50); // controls the speed
            left = left - 25; // move by 50 pixels
            pp.style.left = left + "px";
        }
        </script>
    </head>
    <body>
        <img src="back.png" onclick="jump()" style="position:absolute;top:0;left:0; height:570px;width:1200px;zdepth:1;" />
        <img id="m" src="Mario.png" style="position:absolute;top:390px;left:75px;height:80px;width:80px;zdepth:2;" />
        <img id="b" src="barrel.png" style="position:absolute;top:390px;left:1000px;height:80px;width:80px;zdepth:2;" />
        <img id="s" src="start.png" onclick="moving()" style="position:absolute;top:0px;left:500px;height:80px;width:80px;zdepth:2;" />
    </body>
</html>
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • 3
    `I need that code` is not generally how you want to phrase a question here... – AstroCB May 13 '14 at 00:53
  • 1
    Sorry if that sounded hostile: I'm just saying that you're begging for downvotes when you phrase your question like that because 1) you're being vague and 2) the way that you've asked your question makes it sound like you're asking us to write your code for you rather than help you solve a problem. – AstroCB May 13 '14 at 01:14
  • 3
    See: `The problem is I can't find a code that can detect collisions` is different from `I can't find an answer because all examples I found were canvas not DOM`. The latter is much more useful to people trying to answer your question. It's vague because this is not a `#{code_dump}: solve my problems` site, this is a Q/A network that helps you solve your programming issues. If you make an effort to provide a [high quality question](http://stackoverflow.com/help/how-to-ask) with as much information as possible and keep it updated, people will help you; there's no need to get angry. – AstroCB May 13 '14 at 01:25
  • @user3630522: Always include [**the code you have currently tried to solve your problem**](http://whathaveyoutried.com) and have issues with. Preferably adding a [**jsFiddle**](http://jsfiddle.net) (or similar) demonstrating how your current code does not work. – Nope May 13 '14 at 07:10
  • 1
    @zeantsoi: So, swearing at someone on SO is okay if it is to clarify the reason you flagged their post? Like _"For the record, you're being an idiot"_? Spoiler: **It's not**. You should know better, having over 10k rep. – Cerbrus May 13 '14 at 07:26
  • @Cerbrus, care to clarify which swear I uttered? So far as I can see – even including deleted comments – the answer is... _none_. – zeantsoi Jul 14 '14 at 20:26
  • @zeantsoi: Do you honestly expect me to remember what it was you said, more than 2 months ago? – Cerbrus Jul 14 '14 at 21:36

2 Answers2

0

You need to check if they are in the same position on the page. You're using top and left to set the coordinates of the images, so you need to check to see if they are at the same top and the same left offsets:

var topEq = document.getElementById('m').style.top === document.getElementById('b').style.top;
var leftEq = document.getElementById('m').style.left === document.getElementById('b').style.left;

if(topEq && leftEq){
  //game over
}

Alternatively, you can run the whole game in a while loop like this:

var playing = true;
while(playing){

  //game

  if(topEq && leftEq){
    playing = false;
  }
}
AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • function hit() { var topEq = document.getElementById('m').style.top === document.getElementById('b').style.top; var leftEq = document.getElementById('m').style.left === document.getElementById('b').style.left; if(topEq && leftEq){ alert("gameover"); } } – user3630522 May 13 '14 at 01:45
  • Did you call `hit()` from within `moving()`? – AstroCB May 13 '14 at 01:48
  • Oh shit I didn't but I just did now and it works!! Do I have to open another topic for another question about this same game? – user3630522 May 13 '14 at 01:53
  • It depends on how related the topic is to this one. It's generally recommended to not carry on a discussion in the comments but if you update your question, people can modify their answers or post new ones. – AstroCB May 13 '14 at 01:54
  • Is there a chatroom type function here ? Basically I tried this code to get the barrel to come back to the right side screen. var barrel = document.getElementById("b"); – user3630522 May 13 '14 at 01:58
  • if( barrel < 0 ) { barrel.style.left= + 1000; } – user3630522 May 13 '14 at 02:00
  • [Yes](http://chat.stackoverflow.com), but you have to have 20 rep to participate. – AstroCB May 13 '14 at 02:04
  • `Barrel` is your element, not a value: change it to `if(barrel.style.left < 0){barrel.style.left += 1000;}` – AstroCB May 13 '14 at 02:06
  • Ok I did that code but it didnt work. I put it in the moving() is there any conflict you see already the var pp = document.getElementById("b"); so instead of barrel I used pp but it didnt work. – user3630522 May 13 '14 at 02:13
  • Damn I used left = left-25; that might cause a problem too . I will change those variables now. – user3630522 May 13 '14 at 02:17
  • Ah: the problem is that `barrel.style.left` gives you `(a number)px`, so you need to do `var str = barrel.style.left.substring(0, this.length - 2); var offset = parseInt(str, 10);` and then `if(offset < 0){ barrel.style.left += 1000; } ` – AstroCB May 13 '14 at 02:27
0

you will need to manually check that the items do not overlap. The simplest way I know of doing this is to test to see that the rectangle of the one does not overlap with the rectangle of the other.

element.getClientRects() which provides top/bottom/left/right. a sample collision detection function might look like this:

function colides(elem1, elem2){
    var cr1 = elem1.getClientRects()[0]; // get the rectangle for the image
    var cr2 = elem2.getClientRects()[0]; // ''
    var heightOffset = (cr1.bottom - cr2.top); // calculate relative positions vert
    var widthOffset = (cr1.right - cr2.left ); // calculate relative positions horiz
    if ( heightOffset < (elem1.clientHeight + elem2.clientHeight) // bottom of one below top of other
        && heightOffset > 0                                       // and not below bottom of other
        && widthOffset < (elem1.clientWidth + elem2.clientWidth)  // left of one further right than right of other 
        && widthOffset > 0)                                       // and not to the right of it 
             return true;                                         // this is a collision.
    return false; // we didn't return true, so it must be false.
}

this will give false positives because your actors do not take up the whole rectangle, but it is a start.

insert the above function into your code, and use it in your moving function like this:

function moving() // controls barrel movement
{

    var barrel = document.getElementById("b"); // get the barrel image
        var mario = document.getElementById("m");  // get the mario image
    var left = parseInt(pp.style.left);        // figure out how far left the barrel is
    if (colides(barrel, mario)){               // if there is a collision
        barrel.style.left = "1000px"       // reset position
        alert ("game over");               // notify player
    } else {                                   // else
        var tim = setTimeout("moving()",50);  // run this code again in 50ms
        left = left-25;  // move by 25 pixels // set the left coordinate down by 25px
        if (left < 0) left = 1000;            // if we would go off the screen, reset
        barrel.style.left = left+"px";        // set the position of the image to match our variable
        }

}

Edit added comments. these should explain the code.

Mobius
  • 2,871
  • 1
  • 19
  • 29
  • Ok thanks I have another question you seem to be great at this I tried to get the barrel to return back to its starting point if it doesnt collide with the player like this if( barrel < 0 ) { barrel.style.left= + 1000; } but it doesn't work what did I do wrong? – user3630522 May 13 '14 at 02:05
  • look at my code, it does this with `if (left <0) left = 1000` – Mobius May 13 '14 at 02:09
  • Yes your code works I am just trying to figure oiut how cause its a bit more complex than my stlye of coding. Where did you learn to code please?? – user3630522 May 13 '14 at 03:01
  • Added comments, hope this helps – Mobius May 13 '14 at 04:57