javascript - JS中如何判断一个对象是否接触到另一个对象
问题描述
(对不起,我的英语不好,我今年 13 岁)好吧,即使我今天刚加入 stackoverflow,我已经编码了一段时间。我正在尝试制作一个简单的游戏(以后可能会变得更大)并且我希望锤子(玩家精灵)不能穿过盒子朝向屏幕中间,但我不知道如何. 这是我所拥有的:
var sq = document.getElementById("box");
var posX = 0;
var posY = 0;
var rot = "rotate(0deg)";
var id = null;
function move(object, pixels, xa){
if(xa == true) {
posX+=pixels;
object.style.left = posX + 'px';
}else{
posY+=pixels;
object.style.top = posY + 'px';
}
}
OBJect.style.left = "200px";
OBJect.style.top = "200px";
document.addEventListener('keydown', logKey);
function logKey(e) {
if (`${e.code}` == "ArrowRight") {
rot = "rotate(90deg)";
sq.style.transform = rot;
move(sq, 5, true);
if(posX > 470){
posX = 5;
}
}
if (`${e.code}` == "ArrowLeft") {
rot = "rotate(270deg)";
sq.style.transform = rot;
move(sq, -5, true);
if(posX < 0){
posX = 465;
}
}
if (`${e.code}` == "ArrowDown") {
rot = "rotate(180deg)";
sq.style.transform = rot;
move(sq, 5, false);
if(posY > 465){
posY = 5;
}
}
if (`${e.code}` == "ArrowUp") {
rot = "rotate(0deg)";
sq.style.transform = rot;
move(sq, -5, false);
if(posY < 0){
posY = 470;
}
}
}
setInterval(function(){
xaxis.innerHTML = "x: " + posX;
yaxis.innerHTML = "y: " + posY;
rotate.innerHTML = rot;
},1);
#myContainer {
width: 500px;
height: 500px;
position: relative;
background: black;
outline: red solid 10px;
}
#box {
width: 30px;
height: 30px;
position: absolute;
background-color: gray;
}
#OBJect {
width: 30px;
height: 30px;
position: absolute;
background-color: gray;
}
<!DOCTYPE html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<style>
/*style would go here/*
</style>
<body>
<div id="myContainer">
<img src="https://cdn.glitch.com/7f9c2ae2-9b45-42a1-a387-380de7f5d3bd%2Fhammer.png?v=1615308683807" alt="hammer" id="box">
<div id="OBJect"></div>
</div>
<br><br>
<div id="xaxis"></div>
<div id="yaxis"></div>
<div id="rotate"></div>
<script>
//script would go here
</script>
</body>
</html>
是的,是的,我知道。我确实可以改进,但我只知道基本的东西,其中一些来自 Stackoverflow 或 w3schools,是的,我知道这个问题有很多已解决的答案,但我对它们感到困惑,因为它们太复杂了我。我只是要求易于理解的简单代码(如果不是,请标记内容以便我知道)。
抱歉,如果这太多了,我只需要帮助:/
解决方案
我今天也加入了,我12岁。由于锤子是img,你可以使用css:
我认为你的问题是你想移动锤子,如果是的话:
var left = 0; /*left and top can be edited in your code but*/
var top = 0;/*you have to reset them using the code below*/
var hammer = document.querySelector('#hammer');
hammer.style.left = left + 'px';
hammer.style.top = top + 'px';
#hammer {
position: absolute;
left: 0px;
right: 0px;
}/*set left and right via js*/
<!--just add an id like #hammer to the hammer-->
推荐阅读
- flutter - 使用 SyncfusionPdf Flutter 进行 Pdf 注释
- android - 如何检查字符串是否以 {SOME_STRING} 开头
- ballerina - 将 CRLF 添加到字符串数组中的字符串会在 ballerina.io 中创建一个空格字符
- tinymce - 在 tinymce 页脚中将计数从增加变为减少
- python - 使用条件连接循环中的字符串列表中的元素
- sql-server - 创建在一个字段中处理多个字段的视图
- laravel - 通过 composer 安装 laravel 和 backoffice(全新安装和集成)
- html - 在 Firefox 的 Bootstrap 布局中使用溢出和粘性项目有时会产生不需要的垂直空间
- php - 查询数据库的最后修改日期
- python - 使用opencv-python从不同cpu上的同一视频中获取不同的有效帧号?