我正在创建一个迷宫游戏,我希望游戏的墙壁是不可逾越的。我的光标后面有一个图像,我想知道什么元素最适合我正在做的事情。我试过一个 div,但它真的很难让它发挥作用。我根本不希望图像能够进入元素。让图像远离元素的最简单方法是什么?我更喜欢 jQuery,但我对纯 js 很灵活。
代码:
var startMove;
$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
$("#drop").mouseenter(function(){
if(startMove)
alert("Success");
});
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
z-index: 100;
height:auto;
}
#drop{
width:100px;
height:100px;
background:aqua;
position: absolute;
left:200px;
top: 300px;
z-index:99
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div id="drop">
</div>
Jsfiddle:https://jsfiddle.net/3x7cgLdr/27/
最好在您的解决方案中添加一个 jsfiddle,这样我就可以使用它。
最佳答案
试试这个碰撞检查:
function collisionCheck(ax,ay) {
var collide = true;
var aminY = ay;
var aminX = ax;
var amaxX = aminX + $('#image').width();
var amaxY = aminY + $('#image').height();
$('.maze').each(function(){
collide = true;
var bminY = $(this).offset().top - $(window).scrollTop();
var bminX = $(this).offset().left - $(window).scrollLeft();
var bmaxX = bminX + $(this).width();
var bmaxY = bminY + $(this).height();
if (amaxX < bminX) collide = false; // a is left of b
if (aminX > bmaxX) collide = false; // a is right of b
if (amaxY < bminY) collide = false; // a is above b
if (aminY > bmaxY) collide = false; // a is below b
if (collide) {
return collide;
}
});
return collide;
}
JSFiddle:Collision Check
关于javascript - 如何将图像保留在元素之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37450877/