在余弦曲线上找到与另一个位置有指定距离的位置

Finding a location on cosine curve with a specified distance to another location JS

本文关键字:位置 距离 另一个 曲线 余弦      更新时间:2023-09-26

我正在制作一款"拉力赛"游戏,其中一辆汽车在由余弦曲线组成的山丘上绘图。我知道赛车目前的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循环是问题所在。它可能太慢了(fps 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或速度*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 )