Back to StarCatcher Project

StarCatcher - JS file additions

Additional Scripts Two

Instructions:

Use the block of code below to add a class for the stars in your scScripts.js file. This code will be create a class that is used to create star images and hold their positions, speeds, visibility, updating movement functions, resizing functions, and more. Copy and paste this first block of code at the very top of your js file. You will not need the star image load lines from before.

 var star = {
    _x: null,
    _y: null,
    _xSpeed: null,
    _ySpeed: null,

    //Create new star object with given starting position and speed
    //class functions exist to set other private variables
    //All inputs are double and function returns a new star
    create: function (x, y, xSpeed, ySpeed) {
        var obj = Object.create(this);
        obj._x = x;
        obj._y = y;
        obj._xSpeed=xSpeed;
        obj._ySpeed=ySpeed;
        obj._img = new Image();
        obj._img.src="images/star.jpg";
        return obj;
    },

    setImage: function(img){
        this._img.src=img;
    },

    //Update the new x and y of the star based on the speed.
    //drawing functionality is left for calling class
    //no input or return
    update: function () {
        this._x+=this._xSpeed;
        this._y+=this._ySpeed;
    },
};
           

Instructions:

Next, use the block of code below to load up all your star information into a single array. Place this information just below the other lines of code that load up the player images. Again, you will not need the star image load lines from before.

    // our stars are created using a single array with a class of information
    var starCount=5;
    var starArray=[];

    // Create an array of stars
    for (var i = 0; i < starCount; i++) {
        // this assigns each element in the array all the information for the star by 
        // using the 'star' class, pass the starting x,y locations 
        //  and speeds into the array.
        starArray.push(star.create(20,i+50,Math.random()*5,Math.random()*5));
    }
           

Instructions:

Finally, this block of code is our new starUpdate commands. Copy this code and REPLACE the entire previous code in your starUpdate function.

    ctx.drawImage(background,0,0,w,h);
        
    //  draw star on screen only if visible
        for (var i = 0; i < starCount; i++) {
            starArray[i].update();
            ctx.drawImage(starArray[i]._img, starArray[i]._x, starArray[i]._y, 20, 20);
            if (starArray[i]._x>w || starArray[i]._x<0) {starArray[i]._xSpeed = -starArray[i]._xSpeed}
            if (starArray[i]._y>h || starArray[i]._y<0) {starArray[i]._ySpeed = -starArray[i]._ySpeed}
            if (Math.abs(p1x-starArray[i]._x)<20 & Math.abs(p1y-starArray[i]._y)<20) {starArray[i].setSize(20,20);}
        }//endFor
           
David Johns and Electric Teaching ~ All Rights Reserved 2015