JQuery Collision Detection

折月煮酒 提交于 2019-12-25 08:48:37

问题


Not sure if I'm on the right track here, but I figured this should work:

    function collides(a, b) {
              return a.x < b.x + b.width &&
                a.x + a.width > b.x &&
                a.y < b.y + b.height &&
                a.y + a.height > b.y;
    }
    function handleCollisions() {
      $('#player').forEach(function(player) {
        $('#powerUp').forEach(function(powerup) {
          if(collides(player, powerup)) {
           $('#player').hide(); 
          }
        });
      });
    }    
    handleCollisions();
    }

Basically I have my player running around the game and the object at a fix position. When the player collides with the object he should disappear. I will provide a fiddle if needed but I figured that there is something visibly wrong with the code. Any suggestions?

Edit:

  function collides(a, b) {
              return a.offset() < b.offset() + b.width() &&
                a.offset() + a.width() > b.offset() &&
                a.position() < b.position() + b.height() &&
                a.position() + a.height() > b.position();
    }

    function handleCollisions() {
        if (collides($('#player'), $('#powerUp'))) {
           $('#player').append("<p>collided</p>"); // hide player onCollision
          }
    }    
    handleCollisions();
    }


`

来源:https://stackoverflow.com/questions/25374189/jquery-collision-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!