Javascript 慢慢地改变一个角度到另一个角度
Javascript 慢慢地改变一个角度到另一个角度,javascript,math,trigonometry,Javascript,Math,Trigonometry,我正在创建一个与鼠标交互的有趣脚本。我决定要一个物体慢慢地移动鼠标。我制作了这样一个物体,它具有以下特性: speed - current speed of the object speed change ratio - derivative of the speed function: "How's the speed changing now?" direction - radian angle upon which the object is moving direction change
我正在创建一个与鼠标交互的有趣脚本。我决定要一个物体慢慢地移动鼠标。我制作了这样一个物体,它具有以下特性:
speed - current speed of the object
speed change ratio - derivative of the speed function: "How's the speed changing now?"
direction - radian angle upon which the object is moving
direction change - same as for speed, this is used to change the direction
变化率随机生成并添加到速度
和方向
:
//Do not do it allways
if(rand(0,5)>3) {
speed+=speed_change;
direction+=dir_change;
//Only sometimes, so that they actually have some time to take effect
if(rand(0,10)<=3) {
dir_change = rand(-1,1);
speed_change = rand(-2,2)/10;
}
}
现在,我想要的是改变dir\u change
而不是direction
,这样,如果目标发生变化(鼠标光标一直在变化),它将不会立即平稳转动(有点像汽车)
我尝试过这样的计算:
dir_change -= (direction-my_angle)/Math.PI;
/Math.PI
旨在减少更改大小,-
应产生差异。不起作用
,希望您不要因为不清楚而跳过这个问题。谢谢你的帮助
好吧,这里有一个解决方案的工作小提琴->你没有使用的小提琴链接
矢量角度和矢量大小,为什么你在调用数学.atan2
时要减去Pi?出于某种原因,数学.atan2
已经返回了oposite方向-将对象从目标点引开。可能应该替换参数中的x-y
。你所说的vectorSize
和vectorAngle
是什么意思?在我的脚本中,向量大小是速度,角度是方向。嗯,你在脚本中定义了这两个函数,但你没有在任何地方调用它们:)(因此,它们是“未使用的”)啊,这些。。。是的,我不用。我忘了把它们从小提琴上删除。不知道你是否完成了,我的回答是否回答了你的问题:)
if(Math.abs(speed)>6) {
//Dividing speed by |speed| leads +1 or -1, but it's pretty unefective
speed_change = (-1)*(speed/Math.abs(speed));
}
dir_change -= (direction-my_angle)/Math.PI;
var my_angle = Math.atan2(flyPos[1]-flyTo[1],
flyPos[0]-flyTo[0]) -Math.PI;
var my_angle = Math.atan2(flyTo[1]-flyPos[1],
flyTo[0]-flyPos[0]);
setInterval( letter.flyAway, refreshEvery );
if ( Math.abs(angle_to_target - direction) > dPhi )
if (angle_to_target > direction)
direction += dPhi;
else
direction -= dPhi;
else
direction = angle_to_target;
if (direction - Math.PI > angle_to_target )
angle_to_target += 2*Math.PI;
if (angle_to_target - Math.PI > direction )
direction += 2*Math.PI;