javascript - 根据轴承计算 x 和 y

标签 javascript math rotation geometry trigonometry

我有一个屏幕,我想根据 Angular 计算下一个 x 和 y。 第一步是此示例从第 1 步开始。 如何计算下一个脚步,我想向前增加 120,而侧步需要穿入和穿出大约 60。

enter image description here

请记住,起点可以是 x = 100,y = 100, Angular 为 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);
}

最佳答案

图表:

enter image description here

步进方向(黑线)由 (cos θ, sin θ) 给出。步长偏移方向(小蓝线)由 (sin θ, -cos θ)

给出

位置递归由下式给出:

enter image description here

s 确定下一个脚印在黑线的哪一侧,即 -1 表示左脚,+1 表示右脚。

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

enter image description here

每一步都在双脚之间交替。

在你的图表示例中,参数是 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);
}

关于javascript - 根据轴承计算 x 和 y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441897/

相关文章:

javascript - Angular 拖放表单构建器

javascript - 用户滚动时创建一个javascript弹出框

algorithm - 确定 map 中的比例因子

javascript - 三个js键盘旋转

javascript - 两个箭头在圆圈内旋转

c# - 在 C# 中向鼠标旋转无法正常工作

javascript - Rails 中的 JQuery 文件上传 - 表单仍在发送 HTML 请求?

javascript - 无法从 Button 访问 IIFE 内部函数

java - 按时间间隔计算日内烛台

java - 总是向下舍入一个数字