根据方位计算x和y

And*_*ard 2 javascript math geometry trigonometry rotation

我有一个屏幕,我想根据角度计算下一个x和y。第一个足迹是从第1步开始的示例。如何计算下一个足迹,在该足迹上我要增加120,而旁边的足迹需要编织进出约60。

在此处输入图片说明

请记住,起点可以是x = 100,y = 100,角度为180,因此足迹必须沿着y轴上移。

我尝试了以下Javascript,但足迹似乎很困惑:

this.startingFootPrintX = Math.floor(Math.random() * 1000) + 20; //Random number between 20 and 1000
this.startingFootPrintY = Math.floor(Math.random() * 560) + 20; //Random number between 20 and 560
this.startingAngle = Math.floor(Math.random() * 340) + 20; //Random number between 20 and 340

startFootSteps();

startFootSteps(){
console.log(this.startingFootPrintX);
console.log(this.startingFootPrintY);

this.startingFootPrintX = Math.round(Math.cos(this.startingAngle * Math.PI / 180) * 120 + this.startingFootPrintX);
this.startingFootPrintY = Math.round(Math.sin(this.startingAngle * Math.PI / 180) * 60 + this.startingFootPrintY);

setInterval(function () {
startFootSteps();
}, 3000);
}
Run Code Online (Sandbox Code Playgroud)

meo*_*dog 6

图解:

在此处输入图片说明

步进方向(黑线)由给出(cos ?, sin ?)。步距偏移方向(小蓝线)由下式给出(sin ?, -cos ?)

位置重复性由下式给出:

在此处输入图片说明

s 确定下一个足迹位于黑线的哪一侧,即,左脚为-1,右脚为+1。

如果知道起始位置c0和起始脚s0,则可以通过以下方式给出封闭形式的解决方案:

在此处输入图片说明

每一步在双脚之间交替进行。

在您的图表示例中,参数为w = 60, d = 120, ? = 40°, c0 = (96, 438), s0 = -1(从左脚开始)。


更新:JavaScript代码段

this.startingPosX = Math.floor(Math.random() * 1000) + 20;
this.startingPosY = Math.floor(Math.random() * 560) + 20;
this.startingAngle = Math.floor(Math.random() * 340) + 20;
this.startingFoot = 1 - 2 * Math.round(Math.random());   // select which foot to start with
this.stepSize = 120;
this.stepWidth = 60;

footsteps(0);

footsteps(n) {
    // should actually pre-calculate these outside but oh well
    let a = this.startingAngle * Math.PI / 180;
    let c = Math.cos(a), s = Math.sin(a);

    // current foot
    let d = this.startingFoot * (1 - 2 * (n % 2));

    // apply equations
    this.footprintX = Math.round(   
        this.startingPosX +             // initial
        this.stepSize * n * c +         // step
        this.stepWidth * 0.5 * d * s    // foot offset
    );
    this.footprintY = Math.round(
        this.startingPosY +             // initial
        this.stepSize * n * s -         // step
        this.stepWidth * 0.5 * d * c    // foot offset
    );

    // draw the foot here
    console.log(this.footprintX);
    console.log(this.footprintY);

    // increment the step counter for the next call
    setInterval(function() { footsteps(n+1); }, 3000);
}
Run Code Online (Sandbox Code Playgroud)