尝试将一个小游戏放在一起练习,我遇到了一个问题。重点是抓住妖精,但我不知道如何让游戏检测到玩家已经击中了地精。
到目前为止,如果您的位置Y和X与敌人轴匹配,则只能检测到触摸。如何增加两者的宽度或更好的检测触摸方式。
在这里试试:https://jsfiddle.net/acbkk7cs/4/
风格:
#map{
margin: 0 auto;
height: 510px;
width: 510px;
background-image:url(background.png);
}
.character{
background-image:url(character.png);
z-index:1;
position: relative;
top: 150px;
left: 150px;
height: 32px;
width: 33px;
}
.monster{
background-image:url(monster.png);
position: relative;
height: 32px;
width: 30px;
}
使用Javascript:
$(document).ready(function(){
var char = {
player : $(".character"),
x: 150,
y: 150
};
var monster = {
npc : $(".monster"),
x: 100,
y: 100
};
var keypush = {};
$(document).on("keydown keyup", function(e){
var keyN = e.which;
keypush[keyN] = e.type === "keydown";
});
function moveCharacter(){
if (keypush[37]) char.x -=2;
if (keypush[38]) char.y -=2;
if (keypush[39]) char.x +=2;
if (keypush[40]) char.y +=2;
char.player.css({transform:"translate3D("+ char.x +"px, "+ char.y +"px, 0)"});
monster.npc.css({transform:"translate3D("+ monster.x +"px, "+ monster.y +"px, 0)"});
var playerPosX = char.player.position().top;
var monsterPosX = monster.npc.position().top;
var playerPosY = char.player.position().left;
var monsterPosY = monster.npc.position().left;
if ( playerPosX === monsterPosX
&& playerPosY === monsterPosY
){
document.getElementById("pos").innerHTML="Touched";
} else {
document.getElementById("pos").innerHTML="Off";
}
//backend logs
console.log(char.x);
}
(function engine(){
moveCharacter();
window.requestAnimationFrame(engine);
}());
});
HTML:
<div id = "map">
<div class = "character">
</div>
<div class = "monster">
<p id = "pos" style = "color:yellow;font- weight:bold;position:relative;left:5px;font-size:20px;">Position: </p>
</div>
</div>
答案 0 :(得分:0)
最简单快捷的方法是计算角色与怪物之间的距离:fiddle using circle collision。
var dx = playerPosX - monsterPosX,
dy = playerPosY - monsterPosY,
touchDistance = 30;
if ( Math.sqrt( dx * dx + dy * dy ) < touchDistance )
document.getElementById("pos").innerHTML="Touched";
else
document.getElementById("pos").innerHTML="Off";
在这里,我对touchDistance
进行了观察,但它的实际值应该是玩家精灵的半径和怪物精灵的半径之和。如果它们是圆形,则效果最佳:
/**
* (ax,ay) and (bx,by) are the center positions, and ar, br their radii.
*/
function circleCollision( ax, ay, ar, bx, by, br ) {
return Math.sqrt( (ax-bx)*(ax-bx) + (ay-by)*(ay-by) ) <= ar + br;
}
确定碰撞的第二种常用方法是使用&#39;边界框&#39;,或者在这种情况下,使用矩形/正方形:Fiddle using rectangle collision。
function rectangleCollision( pLeft, pTop, pRight, pBottom, mLeft, mTop, mRight, mBottom ) {
return
( (pLeft >= mLeft && pLeft < mRight ) || (pRight >= mLeft && pRight < mRight ) )
&& ( (pBottom >= mTop && pBottom < mBottom) || (pTop >= mTop && pTop < mBottom) )
}