【发布时间】:2019-07-03 07:18:36
【问题描述】:
我正在创建一个游戏,用户在墓地周围徘徊并从不同的坟墓中收集故事。这是一款经典的自上而下的游戏。我正在构建一个脚本,如果用户走进坟墓,他们的运动就会停止,但我在设置碰撞时遇到了麻烦。我正在使用 jQuery。这是我目前所拥有的:
var position = -1;
var $char = $('#char');
var keyCode = null;
var fired = false;
var $stones = $('.stones div');
var collision = null;
document.onkeydown = function(e) {
keyCode = e.which || e.keyCode;
if (!fired) {
position = -1;
fired = true;
switch (keyCode) {
case 38: position = 0; break; //up
case 40: position = 1; break; //down
case 37: position = 2; break; //left
case 39: position = 3; break; //right
}
walking();
stepping = setInterval(walking,125);
}
};
document.onkeyup = function(e) {
//standing
clearInterval(stepping);
stepping = 0;
fired = false;
};
function walking() {
$stones.each(function() { //check all the stones...
collision = collision($(this), $char, position); ...for collisions
if (collision) { //if any, then break loop
return false;
}
});
if (!collision) { //check if there was a collision
//if no collision, keep walking x direction
}
function collision($el, $charEl, position) {
var $el = $el[0].getBoundingClientRect();
var $charEl = $charEl[0].getBoundingClientRect();
var elBottom = parseInt($el.bottom);
var elRight = parseInt($el.right);
var elLeft = parseInt($el.left);
var elTop = parseInt($el.top);
var charBottom = parseInt($charEl.bottom);
var charRight = parseInt($charEl.right);
var charLeft = parseInt($charEl.left);
var charTop = parseInt($charEl.top);
//this is where I'm stuck
}
}
我尝试了各种不同的代码,但似乎没有任何效果。我一直有一个问题,如果我向前走,然后撞到墓碑,然后转身,我就会被卡住。这是我的意思的示例代码:
if (position == 0 &&
!(elTop > charBottom ||
elBottom < charTop ||
elRight < charLeft + 1 ||
elLeft > charRight - 1)
) {
return true;
}
if (position == 1 &&
!(elTop > charBottom ||
elBottom < charTop ||
elRight < charLeft + 1 ||
elLeft > charRight - 1)
) {
return true;
}
return false;
我看过this question 和this question 和this question 到目前为止我没有任何运气。有人可以帮助我了解逻辑或提供我需要做什么的示例代码吗?
谢谢。
【问题讨论】:
标签: javascript jquery collision-detection collision boundary