提问者:小点点

每秒从数组中随机选择一个新数字


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)

这都是我的密码。 我想随机移动背景上的立方体。 现在它只在一个随机的方向上移动。 但我想让它每一秒都改变这个方向。 为此,dX和dY必须每秒改变一次。


共3个答案

匿名用户

使用setInterval()https://javascript.info/setTimeout-setInterval

var myArray = [-3.5,0,3.5];
var dX, dY

setInterval(() => {
  dX = myArray[Math.floor(Math.random()*myArray.length)];
  dY = myArray[Math.floor(Math.random()*myArray.length)];
}, 1000)

匿名用户

我个人会选择使用array.prototype添加一个方法,该方法将获取数组的随机元素,然后使用setInterval每秒更新值:

null

Array.prototype.getRandom = function() {
  let index = Math.floor(Math.random() * this.length);
  return this[index];
}

var myArray = [-3.5,0,3.5];
var dX, dY;

function updateDerivatives() {
  dX = myArray.getRandom(),
  dY = myArray.getRandom();
  console.log("Updated values:", { dX, dY });
}

setInterval(updateDerivatives, 1000);

匿名用户

var myArray = [-3.5,0,3.5];

var dX;
var dY;

setInterval(() => { // you could also use setInterval(function(){...},...)
    dX = myArray[Math.floor(Math.random()*myArray.length)];
    dY = myArray[Math.floor(Math.random()*myArray.length)];
}, 1000) // 1000 milliseconds