从Javascript中的坐标随机移动

Random moving from coordinates in Javascript

本文关键字:随机 移动 坐标 Javascript      更新时间:2023-09-26

我正在使用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和其最大速度之间的空间。每个动作都可以是上/下/左/右。

我知道我必须使用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);
};

现在,假设这个位置是x和y坐标的数组,那么如果你只向上、向下、向左或向右移动,那么你首先需要决定你是想在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

最后一件需要处理的事情是边界条件。你需要检查新的位置是否超过了你的"板"的末端,然后将其停在边缘,或者将其包裹到另一边,或者你想做的任何事情。