【发布时间】:2021-02-05 00:18:57
【问题描述】:
我有一个简单的 JScript HTML 和 CSS 游戏,其中角色必须跳跃,但也可以在按下右箭头时向右移动。我可以使用跳转功能,但是在尝试复制它以创建右箭头功能时,它不起作用。
所需输出: 修正当前代码,以便在按下右箭头时,角色也可以向右移动以及跳跃。按下右箭头键后,角色将继续向右移动。在 keyup 上,它会停止(我是否必须实际为 keyup 和这种可能性创建另一个动画)或者肯定有更简单的方法?
使用更新后的解决方案,它会向右移动,但随后会跳回位置 left:0 而不是停留在移动的位置。
解释:这是一种可接受的编码方式,还是应该将整个代码放在事件监听器中? (例如整个游戏循环)添加额外的关键移动功能的最佳实践是什么。调用像这样的 CSS 动画是可以接受的还是不好的做法,如果不是,为什么?
我的 JavaScript
var character = document.getElementById("character");
var enemy = document.getElementById("enemy");
function jump(){
if(character.classlist!="animate"){
character.classList.add("animate");
}
setTimeout(function(){
character.classList.remove("animate");
},500);
}
function right(){
if(character.classlist!="right"){
character.classList.add("right");
}
setTimeout(function(){
character.classList.remove("right");
},500);
}
var checkDead =setInterval(function(){
var characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
var enemyLeft = parseInt(window.getComputedStyle(enemy).getPropertyValue("left"));
console.log(characterTop);
//commented this out while working on css
/*
if(
enemyLeft<30 && enemyLeft>0 && characterTop>=360
)
{
enemy.style.animation="none"; //remove the animation
enemy.style.display="none";
alert("Poke.....I got you there!");
}
*/
},10);
addEventListener("keyup", function(e) {
if(e.keyCode == 38) jump()
})
addEventListener("keyright", function(e) {
if(e.keyCode == 40) right()
})
我为 keyright 添加的事件监听器基于 keyup 的事件监听器(有效)。
addEventListener("keyright", function(e) {
if(e.keyCode == 40) right()
})
动画在 CSS 中生成
*{
padding:0;
margin:22;
}
#game{
width:500px;
height:500px;
border:4px solid #171918;
}
#character{
width:30px;
height:120px;
background-color:green;
position:relative;
top:320px;
border-radius:20px;
/*animation: jump 300ms */
}
/* new class called animate */
.animate{
animation: jump 500ms;
}
.right{
animation: right 500ms;
}
#enemy{
width:60px;
height:60px;
background-color:red;
border-radius:14px;
position:relative;
top:320px;
left:440px;
animation: moveenemy 1s infinite linear;
}
@keyframes moveenemy{
0%{left:440px;}
50%{top:58px;}
100%{left:0px; top:320x;}
}
@keyframes jump{
0%{top:380px;}
30%{top:50px;}
50%{top:40px;}
100%{top:380px;}
}
@keyframes right{
0%{left:0px;}
100%{left:30px;}
}
/* adding sky*/
#sky{
width:500px;
height:340px;
background-color:skyblue;
position:absolute;
top:118px;
}
/* adding ground */
#ground{
width:500px;
height:170px;
background-color:bisque;
position:absolute;
top:450px;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>B</h1>
<p>Fight</p>
<div id="game">
<div id="sky"></div>
<div id="ground"></div>
<div id="enemy"></div>
<div id="character"></div>
</div>
<script src="script.js"></script>
</body>
</html>
【问题讨论】:
标签: javascript html css addeventlistener keycode