Earlier, I was trying to find out how to rotate a line around a pivot using p5.js, and I played with the code a little bit to make the line point towards the mouse using the atan2 function. It worked fine, and I decided to see what it would look like if I used linear interpolation (lerp) to make the animation look smoother. What was weird is that it seemed once the line passed a certain point, it jumped to the other side instead of just moving to that point. example image of issue

以下是我遇到问题的代码:

let angle = 0;

let rot = 0;

function setup() {
  createCanvas(600, 300);
}

function draw() {
  let v1 = createVector(width / 2 - 50, height / 2);
  let v2 = createVector(width / 2 + 50, height / 2);

  background(255);
  stroke(0);
  strokeWeight(4);

  rot = lerp(rot, atan2(mouseY - v1.y, mouseX - v1.x), 0.1);

  push();
  translate(v1.x, v1.y);
  rotate(rot);
  translate(-v1.x, -v1.y);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
  let p1 = point(v1.x, v1.y);
  let p2 = point(v2.x, v2.y);
  pop();
}

我如何才能使这个动画看起来流畅,而不是奇怪的 skip ?

推荐答案

问题是,因为atan2返回-Math.PI+Math.PI之间的值,所以在表达式target_angle = atan2(mouseY - v1.y, mouseX - v1.x)的线性内插失败的地方有一个 skip .

这就是为什么,为了使当前的rottarget_angle之间的最短路径,我们应该归一化两者之间的差异,以便覆盖其abs值的距离应该小于Math.PI(半个圆)

let angle = 0;

let rot = 0;

function setup() {
  createCanvas(600, 300);
}

function draw() {
  let v1 = createVector(width / 2 - 50, height / 2);
  let v2 = createVector(width / 2 + 50, height / 2);

  background(255);
  stroke(0);
  strokeWeight(4);


  let target = atan2(mouseY - v1.y, mouseX - v1.x);

  while (target - rot > Math.PI) {
    target -= 2 * Math.PI;
  }

  while (target - rot < -Math.PI) {
    target += 2 * Math.PI;
  }

  rot = lerp(rot, target, 0.1);

  push();
  translate(v1.x, v1.y);
  rotate(rot);
  translate(-v1.x, -v1.y);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
  let p1 = point(v1.x, v1.y);
  let p2 = point(v2.x, v2.y);
  pop();
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.9.0/lib/p5.js"></script>

Javascript相关问答推荐

如何解决这个未能在响应上执行json:body stream已读问题?

如何在使用fast-xml-parser构建ML时包括属性值?

在网页上添加谷歌亵渎词

构造HTML表单以使用表单数据创建对象数组

还原器未正确更新状态

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

正则表达式,允许我匹配除已定义的子字符串之外的所有内容

用于在路径之间移动图像的查询

更新动态数据中对象或数组中的所有值字符串

如何将数据块添加到d3力有向图中?

如何在和IF语句中使用||和&;&;?

我想使用GAS和HTML将从Electron 表格中获得的信息插入到文本字段的初始值中

输入的值的类型脚本array.排序()

ngOnChanges仅在第二次调用时才触发

React Refs不与高阶组件(HOC)中的动态生成组件一起工作

按特定顺序将4个数组组合在一起,按ID分组

Angel Auth Guard-用户只有在未登录时才能访问登录页面,只有在登录时才能访问其他页面

Plotly.js栏为x轴栏添加辅助文本

JSON Web令牌(JWT)错误:RSA密钥对的签名无效

带元素数组的Mongo聚合