dimanche 21 juin 2020

Select a new number from array every second randomly

var canvas = document.createElement("canvas");
        b = canvas.getContext("2d");
        canvas.id = "canvas"
        
        canvas.width = 900;
        canvas.height = 600;
        
        document.body.appendChild(canvas);
        
        
        
        var posX =  430;
        posY = 300;
        
        var myArray = [-3.5,0,3.5];
        
        var dX = myArray[Math.floor(Math.random()*myArray.length)];
        var dY = myArray[Math.floor(Math.random()*myArray.length)];
      
       
        
        setInterval(function (){
                b.fillStyle = "steelblue";
                b.fillRect(0, 0, canvas.width, canvas.height);
                posX += dX;
                posY += dY;
            
                if (posX > 875){
                    dX = 0;
                    posX = 875;
                }
                if (posX < 5){
                    dx = 0;
                    posX = 5;
                }
                if (posY > 575){
                        dY = 0;
                        posY = 575;
                }
                if (posY < 5){
                        dY = 0;
                        posY = 5;
                }
        
        b.fillStyle = "snow";
        b.fillRect(posX, posY, 20, 20);
        }, 20)

This is all my Code. I want to move the cube on the background randomly. Right now it moves in just one random direction. but I want it to change this direction every second. for that dX and dY have to change every each second.




Aucun commentaire:

Enregistrer un commentaire