How do I generate a random X value for each “projectile” in my falling objects game using Javascript?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am coding a game that is currently in its very early stages for a project to try to learn more about coding. In my game, objects generate randomly (green squares), and the player (red square), avoids them. I am having trouble trying to get the green squares to generate from a random position on the x-axis. I already have a formula to generate a random number for X, but after it selects a number randomly, all the "projectiles" generate there, rather than all generating from a different area. How would I get all the "projectiles" to generate from different positions on the x-axis randomly?



   var randomX = Math.floor(Math.random() * 480) + 15;

function updateGameArea() {
var x, y;
for (i = 0; i < projectiles.length; i += 1) {
if (player.crashWith(projectiles[i])) {
gameArea.stop();
return;
}
}
gameArea.clear();
gameArea.frameNo += 1;
if (gameArea.frameNo == 1 || everyinterval(150)) {
x = randomX;
y = gameArea.canvas.height;
projectiles.push(new component(40, 40, "green", x, y));
}
for (i = 0; i < projectiles.length; i += 1) {
projectiles[i].y += -1; // the shape is using its coordinates to build downward from its y position
projectiles[i].update();
}
player.newPos();
player.update();
}

function everyinterval(n) {
if ((gameArea.frameNo / n) % 1 == 0) {return true;}
return false;


Expected: Green squares generate in random positions on the x- axis every 3 seconds and move upwards



Actual: Green squares all generate from the same random position on the X-axis.










share|improve this question































    0















    I am coding a game that is currently in its very early stages for a project to try to learn more about coding. In my game, objects generate randomly (green squares), and the player (red square), avoids them. I am having trouble trying to get the green squares to generate from a random position on the x-axis. I already have a formula to generate a random number for X, but after it selects a number randomly, all the "projectiles" generate there, rather than all generating from a different area. How would I get all the "projectiles" to generate from different positions on the x-axis randomly?



       var randomX = Math.floor(Math.random() * 480) + 15;

    function updateGameArea() {
    var x, y;
    for (i = 0; i < projectiles.length; i += 1) {
    if (player.crashWith(projectiles[i])) {
    gameArea.stop();
    return;
    }
    }
    gameArea.clear();
    gameArea.frameNo += 1;
    if (gameArea.frameNo == 1 || everyinterval(150)) {
    x = randomX;
    y = gameArea.canvas.height;
    projectiles.push(new component(40, 40, "green", x, y));
    }
    for (i = 0; i < projectiles.length; i += 1) {
    projectiles[i].y += -1; // the shape is using its coordinates to build downward from its y position
    projectiles[i].update();
    }
    player.newPos();
    player.update();
    }

    function everyinterval(n) {
    if ((gameArea.frameNo / n) % 1 == 0) {return true;}
    return false;


    Expected: Green squares generate in random positions on the x- axis every 3 seconds and move upwards



    Actual: Green squares all generate from the same random position on the X-axis.










    share|improve this question



























      0












      0








      0








      I am coding a game that is currently in its very early stages for a project to try to learn more about coding. In my game, objects generate randomly (green squares), and the player (red square), avoids them. I am having trouble trying to get the green squares to generate from a random position on the x-axis. I already have a formula to generate a random number for X, but after it selects a number randomly, all the "projectiles" generate there, rather than all generating from a different area. How would I get all the "projectiles" to generate from different positions on the x-axis randomly?



         var randomX = Math.floor(Math.random() * 480) + 15;

      function updateGameArea() {
      var x, y;
      for (i = 0; i < projectiles.length; i += 1) {
      if (player.crashWith(projectiles[i])) {
      gameArea.stop();
      return;
      }
      }
      gameArea.clear();
      gameArea.frameNo += 1;
      if (gameArea.frameNo == 1 || everyinterval(150)) {
      x = randomX;
      y = gameArea.canvas.height;
      projectiles.push(new component(40, 40, "green", x, y));
      }
      for (i = 0; i < projectiles.length; i += 1) {
      projectiles[i].y += -1; // the shape is using its coordinates to build downward from its y position
      projectiles[i].update();
      }
      player.newPos();
      player.update();
      }

      function everyinterval(n) {
      if ((gameArea.frameNo / n) % 1 == 0) {return true;}
      return false;


      Expected: Green squares generate in random positions on the x- axis every 3 seconds and move upwards



      Actual: Green squares all generate from the same random position on the X-axis.










      share|improve this question
















      I am coding a game that is currently in its very early stages for a project to try to learn more about coding. In my game, objects generate randomly (green squares), and the player (red square), avoids them. I am having trouble trying to get the green squares to generate from a random position on the x-axis. I already have a formula to generate a random number for X, but after it selects a number randomly, all the "projectiles" generate there, rather than all generating from a different area. How would I get all the "projectiles" to generate from different positions on the x-axis randomly?



         var randomX = Math.floor(Math.random() * 480) + 15;

      function updateGameArea() {
      var x, y;
      for (i = 0; i < projectiles.length; i += 1) {
      if (player.crashWith(projectiles[i])) {
      gameArea.stop();
      return;
      }
      }
      gameArea.clear();
      gameArea.frameNo += 1;
      if (gameArea.frameNo == 1 || everyinterval(150)) {
      x = randomX;
      y = gameArea.canvas.height;
      projectiles.push(new component(40, 40, "green", x, y));
      }
      for (i = 0; i < projectiles.length; i += 1) {
      projectiles[i].y += -1; // the shape is using its coordinates to build downward from its y position
      projectiles[i].update();
      }
      player.newPos();
      player.update();
      }

      function everyinterval(n) {
      if ((gameArea.frameNo / n) % 1 == 0) {return true;}
      return false;


      Expected: Green squares generate in random positions on the x- axis every 3 seconds and move upwards



      Actual: Green squares all generate from the same random position on the X-axis.







      javascript html5






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 4 at 5:10









      Ali

      1,1871421




      1,1871421










      asked Jan 4 at 4:52









      Sage Sage

      11




      11
























          3 Answers
          3






          active

          oldest

          votes


















          1














          You should reset X every time you're adding a new projectile:



          if (gameArea.frameNo == 1 || everyinterval(150)) {
          randomX = Math.floor(Math.random() * 480) + 15;
          x = randomX;
          y = gameArea.canvas.height;
          projectiles.push(new component(40, 40, "green", x, y));
          }


          Otherwise, the randomX value stays constant as the value originally evaluated on line 1 when the interpreter reached it.






          share|improve this answer































            0














            Here's your problem:



            var randomX = Math.floor(Math.random() * 480) + 15;
            // Generates a random number and stores it to randomX
            // Called using 'randomX'


            You need to turn it into a function if you want it to run each time:



            var randomX = function() { Math.floor(Math.random() * 480) + 15 }; 
            // Returns a new number each time
            // Called using 'randomX()'





            share|improve this answer































              0














              Both shivashriganesh mahato and natelouisdev have, essentially responded to how to fix the issue but since you are learning coding here is a tip. When you code, the code will run in a particular order. If you want something to be reassigned repeatedly, in this case a randomized number being used, and you want it to occur only after an event, you need to make sure that it gets trigger within each event.



              natelouisdev has a good approach because, by using it as a function, you can call your randomizer more cleanly in your code and make it reassign the value of x each time.



              Since you are building a game, it is also a good idea to compartmentalize your code. It'll make it easier to keep your ideas in order for each event trigger.



              Example:




              • function gameLoss(){} - Define event return upon game loss. You can
                then create editable rules to reason for loss without having to edit
                the loss

              • function gameActive(){} - Defines what is normal gameplay. everything that occurs during normal gameplay should be managed here.


              • function gameArea(){} - Defines game canvas that function more for UI than for gameplay (scores, lifes, size of screen, etc)



              Had you created individual functions you'd realize you only need a randomized 'x' value upon regular play thus you'd assign it within the gameActive() function and not as a global variable. Then you'd call the gameActive() function as many times as needed within a time interval to ensure a unique value is created each time.



              -Side note: Don't litter unnecessary global variables. It'll make a mess off of your code when debugging. -






              share|improve this answer
























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54033283%2fhow-do-i-generate-a-random-x-value-for-each-projectile-in-my-falling-objects-g%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                1














                You should reset X every time you're adding a new projectile:



                if (gameArea.frameNo == 1 || everyinterval(150)) {
                randomX = Math.floor(Math.random() * 480) + 15;
                x = randomX;
                y = gameArea.canvas.height;
                projectiles.push(new component(40, 40, "green", x, y));
                }


                Otherwise, the randomX value stays constant as the value originally evaluated on line 1 when the interpreter reached it.






                share|improve this answer




























                  1














                  You should reset X every time you're adding a new projectile:



                  if (gameArea.frameNo == 1 || everyinterval(150)) {
                  randomX = Math.floor(Math.random() * 480) + 15;
                  x = randomX;
                  y = gameArea.canvas.height;
                  projectiles.push(new component(40, 40, "green", x, y));
                  }


                  Otherwise, the randomX value stays constant as the value originally evaluated on line 1 when the interpreter reached it.






                  share|improve this answer


























                    1












                    1








                    1







                    You should reset X every time you're adding a new projectile:



                    if (gameArea.frameNo == 1 || everyinterval(150)) {
                    randomX = Math.floor(Math.random() * 480) + 15;
                    x = randomX;
                    y = gameArea.canvas.height;
                    projectiles.push(new component(40, 40, "green", x, y));
                    }


                    Otherwise, the randomX value stays constant as the value originally evaluated on line 1 when the interpreter reached it.






                    share|improve this answer













                    You should reset X every time you're adding a new projectile:



                    if (gameArea.frameNo == 1 || everyinterval(150)) {
                    randomX = Math.floor(Math.random() * 480) + 15;
                    x = randomX;
                    y = gameArea.canvas.height;
                    projectiles.push(new component(40, 40, "green", x, y));
                    }


                    Otherwise, the randomX value stays constant as the value originally evaluated on line 1 when the interpreter reached it.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 4 at 5:15









                    Shivashriganesh MahatoShivashriganesh Mahato

                    1571314




                    1571314

























                        0














                        Here's your problem:



                        var randomX = Math.floor(Math.random() * 480) + 15;
                        // Generates a random number and stores it to randomX
                        // Called using 'randomX'


                        You need to turn it into a function if you want it to run each time:



                        var randomX = function() { Math.floor(Math.random() * 480) + 15 }; 
                        // Returns a new number each time
                        // Called using 'randomX()'





                        share|improve this answer




























                          0














                          Here's your problem:



                          var randomX = Math.floor(Math.random() * 480) + 15;
                          // Generates a random number and stores it to randomX
                          // Called using 'randomX'


                          You need to turn it into a function if you want it to run each time:



                          var randomX = function() { Math.floor(Math.random() * 480) + 15 }; 
                          // Returns a new number each time
                          // Called using 'randomX()'





                          share|improve this answer


























                            0












                            0








                            0







                            Here's your problem:



                            var randomX = Math.floor(Math.random() * 480) + 15;
                            // Generates a random number and stores it to randomX
                            // Called using 'randomX'


                            You need to turn it into a function if you want it to run each time:



                            var randomX = function() { Math.floor(Math.random() * 480) + 15 }; 
                            // Returns a new number each time
                            // Called using 'randomX()'





                            share|improve this answer













                            Here's your problem:



                            var randomX = Math.floor(Math.random() * 480) + 15;
                            // Generates a random number and stores it to randomX
                            // Called using 'randomX'


                            You need to turn it into a function if you want it to run each time:



                            var randomX = function() { Math.floor(Math.random() * 480) + 15 }; 
                            // Returns a new number each time
                            // Called using 'randomX()'






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 4 at 5:21









                            natelouisdevnatelouisdev

                            1




                            1























                                0














                                Both shivashriganesh mahato and natelouisdev have, essentially responded to how to fix the issue but since you are learning coding here is a tip. When you code, the code will run in a particular order. If you want something to be reassigned repeatedly, in this case a randomized number being used, and you want it to occur only after an event, you need to make sure that it gets trigger within each event.



                                natelouisdev has a good approach because, by using it as a function, you can call your randomizer more cleanly in your code and make it reassign the value of x each time.



                                Since you are building a game, it is also a good idea to compartmentalize your code. It'll make it easier to keep your ideas in order for each event trigger.



                                Example:




                                • function gameLoss(){} - Define event return upon game loss. You can
                                  then create editable rules to reason for loss without having to edit
                                  the loss

                                • function gameActive(){} - Defines what is normal gameplay. everything that occurs during normal gameplay should be managed here.


                                • function gameArea(){} - Defines game canvas that function more for UI than for gameplay (scores, lifes, size of screen, etc)



                                Had you created individual functions you'd realize you only need a randomized 'x' value upon regular play thus you'd assign it within the gameActive() function and not as a global variable. Then you'd call the gameActive() function as many times as needed within a time interval to ensure a unique value is created each time.



                                -Side note: Don't litter unnecessary global variables. It'll make a mess off of your code when debugging. -






                                share|improve this answer




























                                  0














                                  Both shivashriganesh mahato and natelouisdev have, essentially responded to how to fix the issue but since you are learning coding here is a tip. When you code, the code will run in a particular order. If you want something to be reassigned repeatedly, in this case a randomized number being used, and you want it to occur only after an event, you need to make sure that it gets trigger within each event.



                                  natelouisdev has a good approach because, by using it as a function, you can call your randomizer more cleanly in your code and make it reassign the value of x each time.



                                  Since you are building a game, it is also a good idea to compartmentalize your code. It'll make it easier to keep your ideas in order for each event trigger.



                                  Example:




                                  • function gameLoss(){} - Define event return upon game loss. You can
                                    then create editable rules to reason for loss without having to edit
                                    the loss

                                  • function gameActive(){} - Defines what is normal gameplay. everything that occurs during normal gameplay should be managed here.


                                  • function gameArea(){} - Defines game canvas that function more for UI than for gameplay (scores, lifes, size of screen, etc)



                                  Had you created individual functions you'd realize you only need a randomized 'x' value upon regular play thus you'd assign it within the gameActive() function and not as a global variable. Then you'd call the gameActive() function as many times as needed within a time interval to ensure a unique value is created each time.



                                  -Side note: Don't litter unnecessary global variables. It'll make a mess off of your code when debugging. -






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    Both shivashriganesh mahato and natelouisdev have, essentially responded to how to fix the issue but since you are learning coding here is a tip. When you code, the code will run in a particular order. If you want something to be reassigned repeatedly, in this case a randomized number being used, and you want it to occur only after an event, you need to make sure that it gets trigger within each event.



                                    natelouisdev has a good approach because, by using it as a function, you can call your randomizer more cleanly in your code and make it reassign the value of x each time.



                                    Since you are building a game, it is also a good idea to compartmentalize your code. It'll make it easier to keep your ideas in order for each event trigger.



                                    Example:




                                    • function gameLoss(){} - Define event return upon game loss. You can
                                      then create editable rules to reason for loss without having to edit
                                      the loss

                                    • function gameActive(){} - Defines what is normal gameplay. everything that occurs during normal gameplay should be managed here.


                                    • function gameArea(){} - Defines game canvas that function more for UI than for gameplay (scores, lifes, size of screen, etc)



                                    Had you created individual functions you'd realize you only need a randomized 'x' value upon regular play thus you'd assign it within the gameActive() function and not as a global variable. Then you'd call the gameActive() function as many times as needed within a time interval to ensure a unique value is created each time.



                                    -Side note: Don't litter unnecessary global variables. It'll make a mess off of your code when debugging. -






                                    share|improve this answer













                                    Both shivashriganesh mahato and natelouisdev have, essentially responded to how to fix the issue but since you are learning coding here is a tip. When you code, the code will run in a particular order. If you want something to be reassigned repeatedly, in this case a randomized number being used, and you want it to occur only after an event, you need to make sure that it gets trigger within each event.



                                    natelouisdev has a good approach because, by using it as a function, you can call your randomizer more cleanly in your code and make it reassign the value of x each time.



                                    Since you are building a game, it is also a good idea to compartmentalize your code. It'll make it easier to keep your ideas in order for each event trigger.



                                    Example:




                                    • function gameLoss(){} - Define event return upon game loss. You can
                                      then create editable rules to reason for loss without having to edit
                                      the loss

                                    • function gameActive(){} - Defines what is normal gameplay. everything that occurs during normal gameplay should be managed here.


                                    • function gameArea(){} - Defines game canvas that function more for UI than for gameplay (scores, lifes, size of screen, etc)



                                    Had you created individual functions you'd realize you only need a randomized 'x' value upon regular play thus you'd assign it within the gameActive() function and not as a global variable. Then you'd call the gameActive() function as many times as needed within a time interval to ensure a unique value is created each time.



                                    -Side note: Don't litter unnecessary global variables. It'll make a mess off of your code when debugging. -







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jan 4 at 5:47









                                    Jonathan VargasJonathan Vargas

                                    62




                                    62






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54033283%2fhow-do-i-generate-a-random-x-value-for-each-projectile-in-my-falling-objects-g%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Monofisismo

                                        Angular Downloading a file using contenturl with Basic Authentication

                                        Olmecas