我正在使用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和maxSpeed之间移动许多空间。每次移动都可以向上/向下/向左/向右。
我知道我必须使用,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
您需要处理的最后一件事是边界条件。您将需要检查新位置是否超出了“木板”的末端,或者将其停在边缘,或者将其包裹在另一侧,或者尝试执行的操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句