rb3652
rb3652

Reputation: 445

Rotating Line around Point in p5.js

Goal: I'm trying to create a triangle given two angles (a0,b0). To do so, I'm trying to rotate a vector r0 by some angle a0 around one of the vertices of r0. Here's a diagram illustrating my idea. enter image description here Problem: However, when I rotate the line, it seems to rotate around the origin. I've read many, many articles on how to fix this, but none of the suggested solutions (i.e., translate then rotate, push(), pop()) don't seem to work, perhaps because I'm dealing with a line segment here. Below is my code.

MWE Code:

let angle = 0;

function setup() {
  createCanvas(600, 400);
  angleMode(DEGREES);
}

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 r0 = line(v1.x, v1.y, v2.x, v2.y);
  rotate(20);
  let r1 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>

Any help is appreciated.

Upvotes: 3

Views: 2702

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

rotate rotates around the origin of the coordinate system. To rotate around a pivot point, you must:

  • move the pivot to the origin
  • rotate the object
  • move the pivot back to its place in the scene
translate(v1.x, v1.y);
rotate(-1 * mouseX);
translate(-v1.x, -v1.y);

let angle = 0;

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

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

  background(255);
  stroke(0);
  strokeWeight(4);
  
  push();
  translate(v1.x, v1.y);
  rotate(-1 * mouseX);
  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/[email protected]/lib/p5.min.js"></script>

For individual model transformations, you must push() the current matrix before specifying the transformations and pop() the matrix after drawing the objects. So you can draw different objects with different transformations.

Upvotes: 2

Related Questions