到目前为止,我已经创建了可以移动的框,您可以按上,下,左,和右箭头键。但是现在,我想把子弹连接到盒子上,这样每当我按下空格键时,它就会发射子弹。关于如何做到这一点,我有点迷失(空格键的键码是32)。
gameTime.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WOMP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="gameTime.css">
</head>
<body>
<canvas id="canvas" height="400" width="400"></canvas>
<div id="bullet"></div>
<script type="text/javascript" src="gameTime.js"></script>
</body>
</html>
gameTime.css
#bullet {
background: #8A2BE2;
width: 10px;
height: 35px;
position: absolute;
margin-left: 340px;
}
gameTime.js
var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');
var xPos = 0;
var yPos = 0;
context.rect(xPos,yPos,50,50);
context.stroke();
function movement(e) {
if(e.keyCode == 39) {
xPos += 5;
}
if(e.keyCode == 37) {
xPos -= 5;
}
if(e.keyCode == 38) {
yPos -=5;
}
if(e.keyCode == 40) {
yPos +=5;
}
canvas.width = canvas.width;
context.rect(xPos,yPos,50,50);
context.stroke();
}
document.onkeydown = movement;