1

I need help finishing a function that shoots bullets after pressing 'space'.

I tried using these

  • var b = new bullet();
  • var bullets = []
  • bullets.push(b)

Then a for loop like this:

  • for (var i = 0; i < 6; i++) {

but I cant get it to work. Basically a function that every time a bullet is made, it is stored in an array then space loops through the array making new bullets on space press.

fiddle: https://jsfiddle.net/tmanrocks999/7mLpo8uj/652/

code:

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:4px solid #d3d3d3;
    background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>

var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullet;
var myEnemy1Hp = 10;
var damage = 1;
var playerExp = 0;

function startGame() {
    myGameArea.start();
    myGamePiece = new component(30, 30, "red", 0, 240);
    endGoalPiece = new component(30, 30, "black", 450, 240);
    myEnemy1 = new component(30, 30, "green", 200, 240);
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            myGameArea.key = e.keyCode;
        })
        window.addEventListener('keyup', function (e) {
            myGameArea.key = false;
        })
    },
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y) {
    this.gamearea = myGameArea;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    //this.gravity = 0.05;
    //this.gravitySpeed = 0;
    this.x = x;
    this.y = y;
    this.color = color;
    this.update = function() {
        ctx = myGameArea.context;
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY; //+ this.gravitySpeed;        
    }  

}
}


function jump() {
  myGamePiece.gravitySpeed=-1;
}

}

function shootGun(){
  bullet = new component(11, 5, "blue", myGamePiece.x+27 , myGamePiece.y+13 );
  bullet.newPos();
  bullet.speedX=1;
}

function updateGameArea() {
    myGameArea.clear();
    myGamePiece.speedX = 0;
    myGamePiece.speedY = 0;
    if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }//left
    if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }//right
    if (myGameArea.key && myGameArea.key == 38) {myGamePiece.gravitySpeed = -1; }//jump
    if (myGameArea.key && myGameArea.key == 32) {shootGun()}//shoot gun
   //if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
    myEnemy1.update();
    endGoalPiece.update();
    myGamePiece.newPos();
    myGamePiece.update();
    bullet.newPos();
    bullet.update();
}
</script>

<p>use the arrow keys on you keyboard to move the red square.</p>
<span id="myEnemy1Hp">10</span> <br>
<span id="playerExp">0<span><br> / <span id = "playerMaxExp">100</span>

</body>
</html>

I expect on space press for bullets to keep being created by looping through the array but at the moment after space press only 1 bullet is made and position is reset every time you press space ( I know why this is I don't need it explained).

How can I get the illusion of a shooter.

wazz
  • 4,953
  • 5
  • 20
  • 34
  • I like this question but I am not sure I understand the requirement. What should happen on key press exactly? You want to fire multiple bullets or...? It's not very clear from your description. – peter.petrov Oct 22 '19 at 23:14
  • Some comments on your code: function constructor names, should always start with a capital letter: function Component. For game animation, you should probably use the [requestAnimationFrame API](https://stackoverflow.com/questions/38709923/why-is-requestanimationframe-better-than-setinterval-or-settimeout) instead of setInterval. – Kostas Minaidis Oct 22 '19 at 23:24

1 Answers1

1

Take a look at this code:

<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>STACKOVERFLOW</title>
    <style>
        canvas {
            border: 4px solid #d3d3d3;
            background-color: #f1f1f1;
        }
    </style>
</head>

<body onload="startGame()">
    <p>use the arrow keys on you keyboard to move the red square.</p>
    <span id="myEnemy1Hp">10</span> <br>
    <span id="playerExp">0<span><br> / <span id = "playerMaxExp">100</span>

    <script>
        var myGamePiece;
        var endGoalPiece;
        var myEnemy1;
        var bullets = [];
        var myEnemy1Hp = 10;
        var damage = 1;
        var playerExp = 0;

        function startGame() {
            myGameArea.start();
            myGamePiece = new component(30, 30, "red", 0, 240);
            endGoalPiece = new component(30, 30, "black", 450, 240);
            myEnemy1 = new component(30, 30, "green", 200, 240);
        }

        var myGameArea = {
            canvas: document.createElement("canvas"),
            start: function() {
                this.canvas.width = 480;
                this.canvas.height = 270;
                this.context = this.canvas.getContext("2d");
                document.body.insertBefore(this.canvas, document.body.childNodes[0]);
                this.interval = setInterval(updateGameArea, 20);
                window.addEventListener('keydown', function(e) {
                    myGameArea.key = e.keyCode;
                })
                window.addEventListener('keyup', function(e) {
                    myGameArea.key = false;
                })
            },
            clear: function() {
                this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
            }
        }

        function component(width, height, color, x, y) {
            this.gamearea = myGameArea;
            this.width = width;
            this.height = height;
            this.speedX = 0;
            this.speedY = 0;
            //this.gravity = 0.05;
            //this.gravitySpeed = 0;
            this.x = x;
            this.y = y;
            this.color = color;
            this.update = function() {
                ctx = myGameArea.context;
                ctx.fillStyle = this.color;
                ctx.fillRect(this.x, this.y, this.width, this.height);
            }
            this.newPos = function() {
                this.gravitySpeed += this.gravity;
                this.x += this.speedX;
                this.y += this.speedY; //+ this.gravitySpeed;

            }



        }

        function jump() {
            myGamePiece.gravitySpeed = -1;
        }

        function shootGun() {

            let bullet = new component(11, 5, "blue", myGamePiece.x + 27, myGamePiece.y + 13);
            bullet.newPos();
            bullet.speedX = 1;
            bullets.push( bullet );
        }


        function updateGameArea() {
            myGameArea.clear();
            myGamePiece.speedX = 0;
            myGamePiece.speedY = 0;
            if (myGameArea.key && myGameArea.key == 37) {
                myGamePiece.speedX = -1;
            } //left
            if (myGameArea.key && myGameArea.key == 39) {
                myGamePiece.speedX = 1;
            } //right
            if (myGameArea.key && myGameArea.key == 38) {
                myGamePiece.gravitySpeed = -1;
            } //jump
            if (myGameArea.key && myGameArea.key == 32) {
                shootGun()
            } //shoot gun
            //if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
            myEnemy1.update();
            endGoalPiece.update();
            myGamePiece.newPos();
            myGamePiece.update();
            bullets.forEach( (bullet)=> {
                bullet.newPos() 
                bullet.update();
            });
            // bullet.newPos();
            // bullet.update();
        }
    </script>
</body>

</html>

Codepen

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
  • wow thanks . and this uses lambdas. I just learned about this in my java 2 class – tmanrocks909 Oct 23 '19 at 13:49
  • I will try to figure it out on my own but is there a way to prevent a person from holding down space ? or do a settimeout so bullets shoots 1 then waits some time then shoots another? preventing holding down space might be the easiest solution. – tmanrocks909 Oct 23 '19 at 14:29