以一定间隔为游戏创建项目符号

时间:2018-05-16 21:44:05

标签: javascript arrays object

我有一个游戏,其中有一个主要的,可控制的角色,然后是射击角色的敌人。对于敌人来说,当他们向后射击时,我希望他们每隔一段时间射击,这样它就不仅仅是一个巨大的子弹块,并且它与一个setInterval合作,但是当第二个敌人进来时他们不会射击。只有两个中的一个会。如果有人有一个很棒的解决方案!

            function enemies() {
        if (enemy_soldiers.length == 0) {
            level += 0.2;
            for (var i = 0; i<(1 + Math.floor(Math.round(level))); i++) {
                var gx = 1450
                var gy = getRandom(430, 630);
                enemy_soldiers.push({
                    x: gx,
                    y: gy,
                    l: gl,
                    d: getRandom(350, 600),
                    shooting: false,
                    interval: setInterval (function() {enemy.shooting = true;},fire_rate),
                    shoot: function() {
                        enemy_bullets.push({
                            x: enemy.x+40,
                            y: enemy.y+87,
                            vel: 10,
                    });
                    }
                });
            }
        }
        var enemy;
        gctx.clearRect(0, 0, 1400, 800);
        for (var i in enemy_soldiers) {
            enemy = enemy_soldiers[i];
            drawenemy(enemy.x, enemy.y, enemy.l);
            //ai
            if (distance(enemy.x, enemy.y, cx, cy) >= enemy.d && enemy.x>cx) {
                enemy.x-=vel;
            }
            else if (distance(enemy.x, enemy.y, cx, cy) >= enemy.d && enemy.x<cx) {
                enemy.x+=vel;
            }
            if (distance(enemy.x, enemy.y, cx, cy) <= 600) {
                if (enemy.shooting == true) {
                    enemy.shoot(enemy.x,enemy.y);
                    enemy.shooting = false;
                }
                gbctx.clearRect(0, 0, 1400, 800);
                for (var j in enemy_bullets) {
                    enemy_bullet = enemy_bullets[j];
                    enemy_bullet.x -= enemy_bullet.vel;
                if (enemy_bullet.x > 1400 || enemy_bullet.x < -5 || enemy_bullet.y > 800 || enemy_bullet.y < -5) {
                    enemy_bullets.splice(j,1);
                }
                drawEnemyBullet(enemy_bullet.x, enemy_bullet.y);
            }
        }
    }}

1 个答案:

答案 0 :(得分:0)

此解决方案依赖于函数Date.now(),它返回当前时间(以毫秒为单位)。每个敌人都有可能跟踪他们下次必须开火的时间,并且每个敌人之间的射击时间可能会有不同的延迟。

我只添加了一张图片来显示他们何时开枪,但这很容易改变为像射线投射或产生射弹粒子的东西。

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			body {
				background-color: black;
			}
			
			canvas {
				position: absolute;
				margin-left: auto;
				margin-right: auto;
				left: 0;
				right: 0;
				border: solid 1px white;
				border-radius: 1px;
			}
		</style>
	</head>
	
	<body>
		<canvas id="canvas"></canvas>
		<script type="application/javascript">
		
		// Enemy constructor
		function Enemy(x,y) {
			this.x = x;
			this.y = y;
			this.isFiring = false;
			this.fireDelay = (500 + Math.random() * 500) | 0; // Time between shots
			this.lastFired = Date.now(); // Last time at which the enemy fired
		}
		
		/*
			Enemy prototype
			(All objects created using the constructor share these properties)
		
			E.G.
			
				var e1 = new Enemy(10,0);
				var e2 = new Enemy(20,0);
				
				if (e1.__proto__ === e2.__proto__) {
					console.log("Match");
				}
				
				prints "Match"
		*/
		Enemy.prototype = {
			WIDTH: 10,
			HEIGHT: 20,
			
			FIRE_DURATION: 100, // Amount of time 'fire' graphic is shown
			FIRE_WIDTH: 10,
			FIRE_HEIGHT: 10,
		
			update: function() {
				// If current time - time when I last fired > the amount of time between shots
				if (Date.now() - this.lastFired > this.fireDelay) {
					this.lastFired = Date.now();
					this.isFiring = true;
					
					// If you were using projectile particles, this is where you would spawn one
				}
				
				if (this.isFiring && Date.now() - this.lastFired > this.FIRE_DURATION) {
					this.isFiring = false;
				}
			},
			
			render: function(ctx) {
				ctx.fillStyle = "darkred";
				ctx.strokeStyle = "black";
				ctx.lineWidth = 2;
				ctx.beginPath();
				
				ctx.rect(
					this.x,
					this.y,
					this.WIDTH,
					this.HEIGHT
				);
				
				ctx.fill();
				ctx.stroke();
				
				if (this.isFiring) {
					ctx.fillStyle = "yellow";
					ctx.strokeStyle = "darkyellow";
					ctx.lineWidth = 3;
					ctx.beginPath();
					
					ctx.rect(
						this.x + this.WIDTH,
						this.y + this.HEIGHT * 0.5 - this.FIRE_HEIGHT * 0.5,
						this.FIRE_WIDTH,
						this.FIRE_HEIGHT
					);
					
					ctx.fill();
					ctx.stroke();
				}
			}
		};
		
		var canvasWidth = 180;
		var canvasHeight = 160;
		var canvas = null;
		var ctx = null;
		
		var enemies = [];
		
		window.onload = function() {
			canvas = document.getElementById("canvas");
			canvas.width = canvasWidth;
			canvas.height = canvasHeight;
			ctx = canvas.getContext("2d");
			
			for (var i = 0; i < 5; ++i) {
				enemies[i] = new Enemy(20 + i * 3,10 + i * 30);
			}
			
			loop();
		}
		
		function loop() {
			// Update
			for (var i = 0; i < enemies.length; ++i) {
				enemies[i].update();
			}
			
			// Render
			ctx.fillStyle = "gray";
			ctx.fillRect(0,0,canvasWidth,canvasHeight);
			
			for (var i = 0; i < enemies.length; ++i) {
				enemies[i].render(ctx);
			}
			
			//
			requestAnimationFrame(loop);
		}
		
		</script>
	</body>
</html>