从 Javascript 中的坐标随机移动

Random moving from coordinates in Javascript

我正在使用 Javascript 打造我的简陋机器人军队。

// Objet Robot
function Robot(nick, pv, maxSpeed, position) {
  this.nick = nick;
  this.pv = pv;
  this.maxSpeed = maxSpeed;
  this.position = position;
};

//Méthode présentation des robots
Robot.prototype.sePresenter = function() {
  console.log("Bonjour je m'appelle " + this.nick + ". J'ai " + this.pv + "         points de vie." + " Je me déplace à " + this.maxSpeed + " cases par seconde. Je suis à la case de coordonnées " + this.position);
};

//Variables array
var robots = [
  new Robot('Maurice',95,2,[5,8]),
  new Robot('Lilian',76,3,[12,25]),
  new Robot('Ernest',100,1,[11,14]),
  new Robot('Juliette',87,3,[2,17]),
];

//boucle
robots.forEach(function(robot) {
  robot.sePresenter();
});

我想添加机器人运动。每个回合,机器人可以在 1 和它的最大速度之间移动 space。每一步都可以up/down/left/right.

我知道我必须使用 Maths.random 但我无法解释机器人如何移动。

这里是函数的开始

Robot.prototype.seDeplacer = function() {
  var point1X = (this.position(Math.random() * this.maxSpeed+1);
  var point1Y = (this.position(Math.random() * this.maxSpeed)+1;
     console.log("je suis" + point1X + point1Y);
};

robots.forEach(function(robot) {
robot.seDeplacer();
});

我在机器人运动的正确轨道上吗?

我猜你的问题是弄清楚如何让它工作:

Robot.prototype.seDeplacer = function() {
  var point1X = (this.position(Math.random() * this.maxSpeed+1);
  var point1Y = (this.position(Math.random() * this.maxSpeed)+1;
     console.log("je suis" + point1X + point1Y);
};

现在,假设position是一个x和y坐标的数组,那么如果你只是向上、向下、向左或向右移动,那么你首先需要决定你是想在x轴上移动还是在x轴上移动? y 轴:

if (Math.random() > 0.5) {
    // move on X axis
}
else {
    // move on Y axis
}

如果您希望能够沿对角线移动,那么您确实需要 if/else 结构。

现在要在 X 轴上移动(例如),您需要在 -maxSpeed+maxSpeed 之间生成一个随机数,因为您可以在任一方向上移动:

var dx = (Math.random() * this.maxSpeed * 2) - this.maxSpeed;

然后你就可以更新你的位置了:

this.position[0] += dx;   

如果你只需要整数坐标,那么你可以简单地使用Math.floor

您需要处理的最后一件事是边界条件。您需要检查新位置是否超过 "board" 的末尾,然后将其停在边缘,或将其包裹到另一侧,或者您正在尝试做的任何事情。