Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

jquery - Detecting div collision?

This is what I am doing right now:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>untitled</title>
    <meta name="generator" content="TextMate http://macromates.com/">
    <style type="text/css" media="screen">

        body { font-family:"HelveticaNeue-Light"; margin: 0px; }
        input { width: 75%; }
    #wrap { background: #f1f1f1; border: 1px solid #d9d9d9;  padding: 0px; }

/*    #sprite { position: relative; background: #909090; width: 20px; height: 20px; padding: 20px; }*/
        #spriteChatBubble { position: relative; background: #fff; border: 1px solid #000; font-size: 10px; max-width: 200px; }

        #controlArea { margin-top: 50px; }

        .button { background: #fff; color: #0080ff; padding: 5px; border: 1px solid #0050ff; text-decoration: none; }
        .button:active { background: #0080ff; color: #fff; }

    </style>

    <script type="text/javascript" charset="utf-8">

        $(document).ready(function() {

            // on load
            updatePos();

            // get it ready

            $("#sprite").css("background-image", "url(left100by100.png)");



            // our main block

            function detectCollision() {


        var spritePos = $("#sprite").position();
        var spritePosLeft = spritePos.left;
        var spritePosTop = spritePos.top;

        var chunkPos = $("#chunk").position();
        var chunkPosLeft = chunkPos.left;
        var chunkPosTop = chunkPos.top;


        // show the chunk's position values (test)
        $("#posLeftChunk").text(posLeftChunk);

              if (spritePosLeft == chunkPosLeft || spritePosTop == chunkPosTop) {


          // make it go somewhere random! :D

                var randomLeft = Math.floor(Math.random() * 100);
                var randomTop = Math.floor(Math.random() * -100);

          // $("#chunk").hide();

                $("#chunk").css("top", randomTop + "px");
                $("#chunk").css("left", randomLeft + "px");


          // $("#spriteChatBubble").animate({"top": "-=" + randomTop}, "fast");

              }

            }

            setInterval(detectCollision, 500);


            function insertValues(name){

              var name = "foop";
              var spritePosition = $("#sprite").position();
              var leftVal = spritePosition.left;
              var topVal = spritePosition.top;

            }

            insertValues("");


            function showMessage(message) {

              $("#spriteChatBubble").show('slow');
              $("#messageText").text(message);
              $("#spriteChatBubble").delay(5000).hide('slow');

            }

            function updatePos() {

              var position = $("#sprite").position();
              $("#posLeft").text(position.left);
              $("#posTop").text(position.top);
              // updatePos();

              // insert the values into a database
              insertValues("");

            }



            $(document).keydown(function(ee) {

              $("#spriteChatBubble").hide();  // no need to show this!

              // if ($("#sprite").position.left < 0) {
              //           alert();
              //         }                           // fail

              if (ee.keyCode == 37) {

                // going left!

          $("#sprite").css("background-image", "url(left100by100.png)");
          // alert("going left!");

          $("#sprite").animate({"left": "-=50px"}, "fast");
          $("#spriteChatBubble").animate({"left": "-=50px"}, "fast");
          updatePos();
              } 

              if(ee.keyCode == 39) {

                // going right!

          $("#sprite").css("background-image", "url(right100by100.png)");
          // alert("going right!");

                $("#sprite").animate({"left": "+=50px"}, "fast");
                $("#spriteChatBubble").animate({"left": "+=50px"}, "fast");
          updatePos();
              }

              if(ee.keyCode == 38) {
                $("#sprite").animate({"top": "-=50px"}, "fast");
                $("#spriteChatBubble").animate({"top": "-=50px"}, "fast");
          updatePos();
              }

              if(ee.keyCode == 40) {
                $("#sprite").animate({"top": "+=50px"}, "fast");
                $("#spriteChatBubble").animate({"top": "+=50px"}, "fast");
          updatePos();
              }



            });

            $("#left").click(function() {
              $("#sprite").animate({"left": "-=50px"}, "fast");
         updatePos();
            });

            $("#right").click(function() {
              $("#sprite").animate({"left": "+=50px"}, "fast");
         updatePos();
            });

            $("#talkButton").click(function() {
              showMessage($("#speakField").val());
              $("#speakField").val("") ;
            });

        });




    </script>
    <!-- Date: 2011-05-23 -->
</head>
<body>

  <!-- <div id="spriteChatBubble">
      <a class="mt" id="messageText">message</a>
    </div> -->

  <!-- avatar (you, the player) -->

    <div id="sprite" style="position: relative; background: url('right100by100.png'); width: 100px; height: 100px;">

    </div>


  <!-- chunks -->

    <div id="chunk" style="position: relative; background: #909090; width: 20px; height: 5px; top: 100px; left: 80px;"></div>

    <div id="controlArea">

      position.left: <a id="posLeft">0</a><br>
    position.top: <a id="posTop">0</a><br>
    <br><br>
    position.left (chunk): <a id="posLeftChunk">0</a><br>
    position.top (chunk): <a id="posTopChunk">0</a><br>

      <!-- <input type="text" id="speakField" onchange="javascript:void(0);">
         <a href="javascript:void(0);" class="button" id="talkButton">talk!</a>
         <a href="javascript:void(0);" onclick="showMessage('foo');" class="button" id="">test it</a>

         <br><br>

        <a href="javascript:void(0);" class="button" id="left">(</a>
        <a href="javascript:void(0);" class="button" id="right">)</a>
         -->
    </div>


</body>
</html>

Which moves it by 50 pixels in the desired direction, however detecting div collision (the sprite hitting the "chunk") and then it needs to be relocated. Do you know a better way to detect the divs colliding? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll give you a theoretical answer:

You want to calculate your div's bounds -- get your x,y corner values and see if any other div's boundaries intersect your other div's values. If there's an intersection of coordinates then you have yourself a collision.

How to get location coordinates:

Top: $("#div").offset().top
Left: $("#div").offset().left
Bottom: $("#div").offset().top + $("#div").height()
Right: $("#div").offset().left + $("#div").width()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...