您好,我嘗試通過繪製子彈來實施拍攝。我創建了函數SHOOt,並從鍵盤檢測條件調用它....但是,當我按下鍵拍攝一切都停止了,沒有射擊,沒有子彈....發生了什麼?!任何幫助讚賞謝謝。嘗試實施子彈射擊
<html>
<head>
<title>Spaceman Invaders</title>
<script>
window.onload = function() {
var posx = 20;
var posy = 0;
var go_right = true;
var go_down = false;
var canvas = document.getElementById("screen");
context = canvas.getContext("2d");
context2 = canvas.getContext("2d");
var Alien = function(x, y) {
this.x = x;
this.y = y;
this.posx = 30 + x*30;
this.posy = 90 + y*30;
this.go_right = true;
this.go_down = false;
}
function Player() {
this.x=0, this.y = 0, this.w = 20, this.h = 20;
this.render = function(){
context.fillStyle = "orange";
context.fillRect(this.x, this.y, this.w, this.h);
}
}
var X2=223;
var Y2=320;
function shoot(){
context2.fillStyle = "white";
context2.fillRect = (X2, Y2--, 5,10);
context2.fillStyle = "yellow";
context2.fillRect = (X2, Y2, 5,10);
if (Y2>=0) {
timer=setTimeout("shoot()", 5);
}
}
var player = new Player();
Alien.prototype.move = function() {
if (!this.go_down) {
if(this.posx + (2-this.x) * 30 < 250 && this.go_right) {
this.posx += 3;
} else if(this.posx < 30 + this.x*30) {
this.go_right = true;
this.go_down = true;
} else if(!this.go_right) {
this.posx -= 3;
} else {
this.go_right = false;
this.go_down = true;
}
} else {
//if(posy <= 30)
this.posy += 30;
this.go_down = false;
}
}
Alien.prototype.draw = function(context) {
if(this.x == 0) {
context.fillStyle = "red";
} else if(this.x == 1) {
context.fillStyle = "yellow";
} else {
context.fillStyle = "blue";
}
context.beginPath();
context.fillRect(this.posx, this.posy, 20 , 20);
context.fill();
}
var canvas = document.getElementById("screen");
context = canvas.getContext("2d");
if (canvas.getContext) {
//init the aliens array
var aliens = [];
for(var i = 0; i < 3; i++) {
for(var j = 0; j < 3; j++) {
aliens.push(new Alien(j, i));
}
}
player.x=100;
player.y= 480;
setInterval(function() {
context.fillStyle="black";
context.fillRect(0,0,canvas.width, canvas.height);
/*context.fillStyle = "white";
context.fillRect(100, 460, 30 , 30);*/
player.render();
//move all aliens & draw all aliens
for(var i = 0; i < 9; i++) {
aliens[i].move(),
aliens[i].draw(context);
}
}, 20);
document.addEventListener('keydown', function(event){
var key_press = String.fromCharCode(event.keyCode);
// alert(event.keyCode + " | " + key_press);
if (key_press == "D") {
if (player.x >=(280)){
player.x=(280);
}
else {
player.x +=3;
}
} else
if (key_press=="A"){
if (player.x<0){
player.x=(0);
}
else {player.x -=3;}
} else
if (key_press="W") {
//alert("Pah-pah");
shoot();
}
});
}
};
</script>
</head>
<body>
<canvas id="screen" width="300" height="500"/>
</body>
</html>
你在開始時是否有'doctype'標籤? – Progo
nope我沒有 – user3247903
把這個放在開頭:'<!DOCTYPE html>' – Progo