JordanIbanez Posted March 29, 2016 Share Posted March 29, 2016 Hi guys! I'm new to coding & to the forum, and I'd like some assistance in creating a function that spawns a new enemy at regular intervals at random locations on the screen. Attached is the code I've been tweaking with & all related content needed to run the game.html, but I am simply unsure how to go about creating this function, or how to call it at regular intervals. Thanks in advance! Jordan game.html gamemain1.js jquery.min.js NewGame.js processing.min.js Quote Link to comment Share on other sites More sharing options...
Rembrandt Posted April 4, 2016 Share Posted April 4, 2016 To spawn an enemy in a random location at regular intervals you could do something like this. var stageWidth = 1000; var stageHeight = 1000; var intervalInMilliseconds = 5000; var enemies = []; var enemyWidth = 50; var enemyHeight = 100; function spawnEnemy(){ console.log('Spawn a new enemy!'); // Generate a random x position. var randomXPosition = Math.floor(Math.random() * (stageWidth - enemyWidth)) + 1; // Generate a random y position. var randomYPosition = Math.floor(Math.random() * (stageHeight - enemyHeight)) + 1; //Create a new Enemy instance and use above coordinates to place it in a random spot. //Fill the rest of this object like you did with var bullet = {...}. var newEnemy = { xPosition: randomXPosition, yPosition: randomYPosition }; // Push your new enemy in the enemies array so you can render them all at once in the draw loop. enemies.push(newEnemy); } //This function will run 'spawnEnemy()' every 'intervalInMilliSeconds'. setInterval(spawnEnemy, intervalInMilliSeconds); I hope this clears things up, otherwise I'm glad to help you further. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.