Jump to content

Spawning Enemies


Recommended Posts

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!














Link to comment
Share on other sites

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.

//This function will run 'spawnEnemy()' every 'intervalInMilliSeconds'.
setInterval(spawnEnemy, intervalInMilliSeconds);

I hope this clears things up, otherwise I'm glad to help you further.

Link to comment
Share on other sites

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.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...