gpt4 book ai didi

javascript - 寻找余弦曲线上与另一个位置指定距离的位置 JS

转载 作者:行者123 更新时间:2023-11-28 08:16:30 28 4
gpt4 key购买 nike

我正在开发一款“拉力赛”游戏,其中一辆汽车在由余弦曲线组成的山丘上行驶。我知道汽车当前的xspeed(没有山),但问题是我需要知道汽车在山上的xspeed才能绘制车轮在正确的位置并保持速度稳定。

目前我的解决方案如下所示。

function drawWheelOnBasicHill(hillStart, xLocWheel, wheelNro) {
var cw = 400 //the width of the hill
t_max = 2*Math.PI;
var scale = 80, step = cw, inc = t_max/step;

var t1 = (xLocWheel-hillStart)*inc
var y1 = -scale*0.5 * Math.cos(t1);

if(wheelNro == 1 ){ //backwheel
drawRotatedImage(wheel, car.wheel1x, car.wheel1y-y1-45,sx);
//drawing the wheel on canvas
} else { //frontwheel
drawRotatedImage(wheel, car.wheel2x, car.wheel2y-y1-45,sx);
}


for(var i=1; i<=car.speed; i++){ //finding the next xlocation of the wheel with the
//same distance (on the curve) to the previous location as the speed of the car(=the
//distance to the new point on the flat ground)
var t2 = (xLocWheel + i -hillStart)*inc
var y2 = -scale*0.5 * Math.cos(t2);

if(Math.round(Math.sqrt(i^2+(y2-y1)^2))==car.speed){
sx = sx+i; //the new xcoordinate break;
}
}

}

for 循环就是问题所在。它可能太慢(帧率 24 的动画)。我不明白为什么 if 语句目前不起作用。有时它会起作用,但大多数时候更新的条件值会达到实际的xspeed

是否有一些更有效、更简单的方法来做到这一点?或者这段代码是否包含一些错误?我真的很感谢你为解决这个问题所做的努力!我一整天都在看这段代码..

最佳答案

所以 i 是变量并且

x2=x1+i
t2=t1+i*inc
y1=-scale*0.5 * Math.cos(t1)
y2=-scale*0.5 * Math.cos(t2)

这有点奇怪。景观应该与时间无关,即 y 应该只是 x 的函数。时间步长是外部的,由动画循环的速度决定。因此,更合乎逻辑的模型将 dx 作为变量,并且

dt = t2-t1
x2 = x1 + dx
y1 = f(x1) = -0.5*scale*cos(x1)
y2 = f(x2) = -0.5*scale*cos(x2)

你会寻找

的交集
(x2-x1)^2+(y2-y1)^2 = (speed*dt)^2

简化为

(speed*dt)^2=dx^2+0.25*scale^2*(cos(x1+dx)-cos(x1))^2

对于较小的 dx 值,如果 dt 或 speed*dt 很小,就会出现这种情况,

cos(x1+dx)-cos(x1) is approx. -sin(x1)*dx

导致

dx = (speed*dt) / sqrt( 1+0.25*scale^2*sin(x1)^2 )

为了更接近曲线和圆的交点,您可以迭代定点方程

dydx = 0.5*scale*(cos(x1+dx)-cos(x1))/dx
dx = (speed*dt) / ( 1+dydx^2 )

少量的次数。

关于javascript - 寻找余弦曲线上与另一个位置指定距离的位置 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23526732/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com