【问题标题】:Rotating around a point, object consistently getting further围绕一个点旋转,物体不断地走得更远
【发布时间】:2021-01-24 02:05:53
【问题描述】:

我正在 Unity 中制作游戏,需要一个敌人围绕一个点旋转。我正在使用 atan2 来获得指向点的方向,添加 90 度,然后使用 cos 和 sin 来改变位置。在发现对象确实旋转后,但离题更远,我决定在 p5js 中尝试一下。但是我遇到了同样的问题。
代码如下:

let x = 100;
let y = 100;
let speed = 5

function setup() {
  createCanvas(400, 400);
  angleMode(DEGREES)
}

function draw() {
  background(220);
  let dir = atan2(y - height / 2, x - width / 2);
  x += cos(dir + 90) * speed;
  y += sin(dir + 90) * speed;
  rect(x, y, 20, 20);
  console.log(dir)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

【问题讨论】:

  • 到底是javascript还是C#
  • 帖子里没有问题。您的意思是要问如何统一地围绕另一个位置旋转一个位置?该逻辑不起作用,因为您正在向圆上的切线方向移动 speed 单位,但这并不描述圆周运动。基本上与this answer 中解决的问题相同。您需要采取不同的方法。
  • 两者兼而有之。我最初是统一做的,然后去看看我是否用 js 得到相同的结果,但我发现问题出在我的方法上。我该怎么做呢,获取当前坐标,转换为极坐标并调整 theta 然后再转换回笛卡尔坐标会更好吗?

标签: javascript processing p5.js


【解决方案1】:

[...] 但要远离点 [...]

当然。你不会在一个圆圈上移动。你沿着圆的切线移动。切线上的每一步都会增加与圆心的距离。因此,每帧到中心的距离都会增加。

您可以通过使用原始距离和当前距离的比率缩放距离矢量来轻松检查这一点:

let x = 100;
let y = 100;
let speed = 5
let dist;

function setup() {
    createCanvas(400, 400);
    angleMode(DEGREES)
    dist = sqrt(pow(y - height/2, 2) + pow(x - width/2, 2));
}

function draw() {
    background(220);
    let dir = atan2(y - height / 2, x - width / 2);
    x += cos(dir + 90) * speed;
    y += sin(dir + 90) * speed;
    
    let newDist = sqrt(pow(y - height/2, 2) + pow(x - width/2, 2));
    x = (x - width/2) * dist/newDist + width/2
    y = (y - height/2) * dist/newDist + height/2
    
    rect(x, y, 20, 20);
    console.log(dir)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

【讨论】:

  • @matidfk 这是一个选项。其实我并没有提出解决方案,我只是指出了问题。
  • 您认为哪一个在性能方面会更好,因为您的代码工作,但使用了很多平方/平方根,而我的使用 sin 和 cos。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多