如何让数组对象随机移动
How do I make my array objects move randomly?
根据我的教授,我需要使dotArray中的点随机移动。我创建了一个绘制函数,该函数根据xrate和yrate分配dotArray中点的xpos和ypos。但是当我加载html页面时,控制台窗口显示一条错误消息,说"无法读取未定义的属性'xpos'"。这些点不动。有人能告诉我这个代码有什么问题吗?
var randInt = function (lim){
return Math.floor(lim*Math.random());
};
// Generate random hsl color
var color = "hsl("+[0,0,0].map(function(){
return Math.round(100*Math.random())+"%"; }).join(',')+")";
// Qn1. Create array of dots
var dotArray = [1,100]
var i = 0; //initialize array
// Qn3 Create map function
var x = randInt(2) // x is a random number between 0 & 1
var map = function(x,a,b,n,m){
// String to link x,a,b,n,m
return n + (m-n)*(x-a)/(b-a);
};
// Creates 100 dots
while (i < 100){
dotArray[i] = paper.circle(randInt(pWidth), randInt(pWidth), 20)
dotArray[i].attr({
"fill": color, // Qn5 Initialize color to a random hue
"opacity": 0.5,// Qn6 Made the dots semi-transparent by changing its opacity attribute
});
// Initialize position of dots
dotArray[i].xpos = randInt(pWidth);
dotArray[i].ypos = randInt(pHeight);
// Initialize rate
dotArray[i].xrate = 5;
dotArray[i].yrate = 5;
// Draw function to change xpos and ypos of dots according to xrate and yrate.
var draw = function(){
dotArray[i].xpos += dotArray[i].xrate;
dotArray[i].ypos += dotArray[i].yrate;
dotArray[i].attr({'cx': dotArray[i].xpos, 'cy': dotArray[i].ypos});
if (dotArray[i].xpos > pWidth) {dotArray[i].xrate = -dotArray[i].xrate;}
if (dotArray[i].ypos > pHeight) {dotArray[i].yrate = - dotArray[i].yrate};
if (dotArray[i].xpos < 0) {dotArray[i].xrate = -dotArray[i].xrate;}
if (dotArray[i].ypos < 0) (dotArray[i].yrate = - dotArray[i].yrate);
};
console.log("dotArray is " + dotArray[i]); // Console msg to keep track of dots in the array
i++; // Increment of i at end of loop.
};
// Calls draw function
setInterval(draw, 20);
在你的draw函数中,i的值总是100。您应该将draw函数移出while循环,并使用参数调用它以达到单个dot编辑;把你的draw函数改成:
var draw = function(){
for (i = 0; i < dotArray.length; ++i) {
dotArray[i].xpos += dotArray[i].xrate;
dotArray[i].ypos += dotArray[i].yrate;
dotArray[i].attr({'cx': dotArray[i].xpos, 'cy': dotArray[i].ypos});
if (dotArray[i].xpos > pWidth) {dotArray[i].xrate = -dotArray[i].xrate;}
if (dotArray[i].ypos > pHeight) {dotArray[i].yrate = - dotArray[i].yrate};
if (dotArray[i].xpos < 0) {dotArray[i].xrate = -dotArray[i].xrate;}
if (dotArray[i].ypos < 0) (dotArray[i].yrate = - dotArray[i].yrate);
}
}
在您的情况下只需要复制粘贴即可,但您也应该将该函数从while循环中取出。这样,同一个函数就不会在每次while循环迭代中被重新定义100次。
相关文章:
- 如何在JS中随机化backgroundPosition而不使用鼠标移动来制作万花筒的动画
- 随机jquery移动/角度内部错误与安卓浏览器
- 如何在Javascript中在桌子周围随机移动图像
- 使用单选按钮使 Div 在页面上随机移动
- 如何让 Div 使用单选按钮随机移动
- 不透明度+随机移动的随机计时
- 使用JavaScript和html将图像和超链接从一个位置随机移动到另一个位置
- 鼠标下移页面X,页面Y和鼠标移动页面X后页面Y不一样,随机发生
- 一些潜水器的起始位置和随机移动
- 如何让数组对象随机移动
- 用鼠标移动随机放置的盒子
- 如何移动一个图像随机当你点击另一个图像使用html &javascript
- 谷歌地图API移动到远标记在每次渲染(似乎随机)
- 使用原型继承模式的随机移动动画
- Kineticjs:画布中图像的随机移动动画
- 精灵图像的随机移动位置
- 使图像随机移动,点击
- 从Javascript中的坐标随机移动
- 随机移动的图像被屏幕的左上角吸引
- 在固定区域中随机移动图像