gpt4 book ai didi

javascript - Canvas JS 上的墙壁检测

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:27 24 4
gpt4 key购买 nike

我制作了这个脚本,它在它的父容器内移动了一个较小的 div,但我需要它,这样它就不会越过父容器的边界(由 1px 黑线边框表示)。有人可以帮助我吗?

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;

function anim(e) {
if (e.keyCode == 39) {
guyLeft += 2;
guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37) {
guyLeft -= 2;
guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40) {
y += 2;
guy.style.top = y + "px";
}
else if (e.keyCode == 38) {
y -= 2;
guy.style.top = y + "px";
}
}

document.onkeydown = anim;
#container {
height:300px;
width:300px;
outline: 2px solid black;
position:relative;
}

#guy {
position:absolute;
height:20px;
width:20px;
outline: 1px solid black;
background-color:red; left: 0;
}
<div id="container">
<div id="guy"></div>
</div>

最佳答案

您可以使用 IF 语句来检测 Angular 色何时位于边缘。

在您的示例中,您的 JavaScript 将变为:

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}

} document.onkeydown = anim;

这是一个工作示例:

var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}

} document.onkeydown = anim;
#container {
height:300px;
width:300px;
outline: 2px solid black;
position:relative; }

#guy {
position:absolute;
height:20px;
width:20px;
outline: 1px solid black;
background-color:red; left: 0;
}
<div id="container"> <div id="guy"></div></div>

关于javascript - Canvas JS 上的墙壁检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47631393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com