【问题标题】:Moving the circle in the directing of another circle revolving around it in canvas沿着画布中围绕它旋转的另一个圆圈的方向移动圆圈
【发布时间】:2021-03-16 07:33:33
【问题描述】:

按下按钮时,我遇到了将大圆圈向小圆圈方向移动的问题。谁能帮忙?

目标:

  1. 在画布上画一个圆圈 [完成]
  2. 画一个围绕大圆旋转的小圆[完成]
  3. 在当时指向小圆圈的方向按下按钮时,将大圆圈移动5个像素[待定]
  4. 在移动时添加绘图效果 [待定]

我们可以在按下按钮时使用下面的x和y坐标并沿方向移动主圆吗?如果我错了,请纠正我

let x = r *2* cos(angle);


let y = r *2* sin(angle);

let angle = 0;


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



function draw() {
  background(0);
  stroke(255);
  strokeWeight(4);
  let cir = createVector(200,200);
  let velocity = createVector();
  
  
  
  
  let r = 10;
  k = circle(cir.x, cir.y, r * 2);

  strokeWeight(4);
  stroke(255);
  let x = r *2* cos(angle);
  let y = r *2* sin(angle);
  translate(200,200);
  point(x, y);
  angle += 0.01;
  
  if(mouseIsPressed){
    k.x += x;
    k.y += y;
  }
}
<html>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.js"></script>
</html>

【问题讨论】:

    标签: javascript animation dom canvas p5.js


    【解决方案1】:

    您可以通过跟踪大圆的中心来使大圆向小圆的方向移动,同时保持小圆围绕大圆运行。

    将变量 cir 移到 draw 之外,以便我们保留对其所做的任何更改。

    我们还需要计算从大圆的中心到小圆的直线段的 5px 移动。为此,我们可以使用此解决方案中的公式to find a point on a line segment

    为了防止小圆圈在移动过程中旋转,我们只能在鼠标未按下时增加旋转角度。

    let angle = 0;
    let cir;
    
    function setup() {
      createCanvas(400, 400);
      cir = createVector(200,200);
    }
    
    function draw() {
      background(0);
      stroke(255);
      strokeWeight(4);
      let r = 10;
      circle(cir.x, cir.y, r * 2);
      strokeWeight(4);
      stroke(255);
      let x = r *2* cos(angle);
      let y = r *2* sin(angle);
      point(x +cir.x, y+cir.y);
     
      
      if(mouseIsPressed){ 
        cir.x = (1-0.025)*cir.x+0.025*(x+cir.x);
        cir.y = (1-0.025)*cir.y+0.025*(y+cir.y);
      } else {
       angle += 0.01;
      }
    }
    &lt;script src="https://cdn.jsdelivr.net/npm/p5@1.3.0/lib/p5.js"&gt;&lt;/script&gt;

    【讨论】:

    • 非常感谢。你能解释一下cir.x = (1-0.025)*cir.x+0.025*(x+cir.x);这一行以及你为什么采用这些值吗?
    • 是否可以在移动时停止小圆圈的旋转,停止后恢复?
    • 是的,看我修改过的代码。要停止旋转,我们只是跳过增加角度。
    • cir.x = (1-0.025)*cir.x+0.025*(x+cir.x);通过将大圆中心点和小圆位置代入在线段上求点的公式中,计算大圆的新 x pos。有关详细信息,请参阅链接。
    • 谢谢,快速提问,我们如何为此添加加速?我试过添加,它正在加速,但它没有改变它的方向。当我只是增加 0.025 的值时它正在工作,但我需要稳定地增加它的速度。你能帮忙吗
    猜你喜欢
    • 2019-04-25
    • 2021-06-24
    • 2019-09-04
    • 1970-01-01
    • 2021-07-30
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多