从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和其最大速度之间的空间。每个动作都可以是上/下/左/右。
我知道我必须使用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
最后一件需要处理的事情是边界条件。你需要检查新的位置是否超过了你的"板"的末端,然后将其停在边缘,或者将其包裹到另一边,或者你想做的任何事情。
相关文章:
- 如何在JS中随机化backgroundPosition而不使用鼠标移动来制作万花筒的动画
- 随机jquery移动/角度内部错误与安卓浏览器
- 如何在Javascript中在桌子周围随机移动图像
- 使用单选按钮使 Div 在页面上随机移动
- 如何让 Div 使用单选按钮随机移动
- 不透明度+随机移动的随机计时
- 使用JavaScript和html将图像和超链接从一个位置随机移动到另一个位置
- 鼠标下移页面X,页面Y和鼠标移动页面X后页面Y不一样,随机发生
- 一些潜水器的起始位置和随机移动
- 如何让数组对象随机移动
- 用鼠标移动随机放置的盒子
- 如何移动一个图像随机当你点击另一个图像使用html &javascript
- 谷歌地图API移动到远标记在每次渲染(似乎随机)
- 使用原型继承模式的随机移动动画
- Kineticjs:画布中图像的随机移动动画
- 精灵图像的随机移动位置
- 使图像随机移动,点击
- 从Javascript中的坐标随机移动
- 随机移动的图像被屏幕的左上角吸引
- 在固定区域中随机移动图像