P5通过数学旋转形状

时间:2020-08-01 08:21:20

标签: javascript p5.js

我正在尝试使用一些数学方法在P5中旋转一个红色和蓝色的圆圈。它由两个半圆组成。如您所见,这两个圆当前以10像素半径旋转,而不是旋转。如果将半径更改为0,它将失去该关系。我不想使用旋转功能...

let angle = 0; //declare a variable for the initial angle

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

function draw() {
  background(255);
  noStroke;  
  angleMode(DEGREES); 
  ellipseMode(CENTER); 

  let posX = 200; //change the x axis
  let posY = 200; //change the y axis
  let reSize = 200; //change the size
  let rotationSpeed = 1; //change the rotation speed

  let radius = 10;
  let x = radius * cos(angle); 
  let y = radius * sin(angle);

  fill('red'); 
  arc(posX+x, posY+y, reSize, reSize, 0, 180); 

  fill('blue');
  arc(posX+x, posY+y, reSize, reSize, 180, 360); 

  angle += rotationSpeed; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>

1 个答案:

答案 0 :(得分:1)

    let angle = 0; //declare a variable for the initial angle
    let currentAnglePercentage = 0;

    function getCurrentAngle() {
        return map(currentAnglePercentage % 100, 0, 100, 0, 360);
    }

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

    function draw() {
        currentAnglePercentage++;
        background(255);
        noStroke;
        angleMode(DEGREES);
        ellipseMode(CENTER);

        let posX = 200; //change the x axis
        let posY = 200; //change the y axis
        let reSize = 200; //change the size
        let rotationSpeed = 1; //change the rotation speed

        let radius = 10;
        let x = radius * cos(angle);
        let y = radius * sin(angle);

        const c1a1 = 0 + getCurrentAngle();
        const c1a2 = 180 + getCurrentAngle();

        const c2a1 = 180 + getCurrentAngle();
        const c2a2 = 360 + getCurrentAngle();

        fill('red');
        arc(posX + x, posY + y, reSize, reSize, c1a1, c1a2);

        fill('blue');
        arc(posX + x, posY + y, reSize, reSize, c2a1, c2a2);

        angle += rotationSpeed;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>

绘制圆弧时可以更改角度。