我第一次使用html,尽管mygamepiece停在地面,但它穿过画布的侧面和顶部。有谁知道如何解决这一问题?这是我正在使用的代码。
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<style>
canvas {
border:10px solid skyblue;
background-color: powderblue;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
function startGame() {
myGamePiece = new component(30,30,"purple",80,75);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),start : function() {
this.canvas.width = 1550;
this.canvas.height = 745;
this.context = this.canvas.getcontext("2d");
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
this.interval = setInterval(updateGameArea,20);
window.addEventListener('keydown',function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup',function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},clear : function(){
this.context.clearRect(0,this.canvas.width,this.canvas.height);
}
}
function component(width,height,color,x,y,type) {
this.type = type;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.1;
this.gravitySpeed = 0;
this.bounce = 0.5;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x,this.y,this.width,this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = -(this.gravitySpeed * this.bounce);
}
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -2; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 2; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -3; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 4; }
myGamePiece.newPos();
myGamePiece.update();
}
</script>
</body>
</html>
希望这能使您对我的工作有所了解,希望任何人都能提出建议。