Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - How do I rotate a rectangle shape from a specific point in p5.js

translate(width/2,height/1.87)
  rotate(angle);
  angle++;
  rectMode(CENTER)//can i modify the rectmode and make it rotate at other point of the rect
rect(0,0,100,30)

Can I modify the rectMode and make it rotate at other point of the rect?

question from:https://stackoverflow.com/questions/65900807/how-do-i-rotate-a-rectangle-shape-from-a-specific-point-in-p5-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to rotate around a pivot point, you translate() move the rectangle so that the pivot point is at the origin of the coordinate system. After that, rotate() the rectangle and finally translate()it to its place in the world:

translate(target_x, target_y);
rotate(angle);
translate(-pivot_x, -pivot_y);

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

// (-5, 15) measured form the center of the rectangle
let pivot_x = -5, pivot_y = 15;    

// Position at which the pivot point should be moved in the world
let target_x = 150, target_y = 100; 

let angle = 0;
let angle_change = 0.01;

function draw() {
    background(255);
    
    push()

    translate(target_x, target_y);
    rotate(angle);
    translate(-pivot_x, -pivot_y);

    noFill();
    stroke(0)
    rectMode(CENTER)
    rect(0,0,100,30);

    pop();
    
    noStroke();
    fill(255, 0, 0);
    circle(target_x, target_y, 5)
    
    angle += angle_change;
    if (abs(angle) > 0.5)
        angle_change *= -1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...