首页 > 解决方案 > P5 用数学旋转一个形状

问题描述

我正在尝试使用一些数学在 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>

标签: javascriptp5.js

解决方案


    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>

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


推荐阅读