rotate a cylinder in P3D

edited May 2017 in Library Questions

Hi there, I'm trying to rotate a cylinder based on 2 PVectors, for example, I've got two PVector a and b, and I want the cylinder to be exactly the same position as the line PVector which is defined by a and b code is below, but when I calculate the angle between 2 vectors, I am not sure which axis I need to use in order to rotate the cylinder. May be it is something to do with the centroid?

import peasy.*;
import peasy.org.apache.commons.math.*;
import peasy.org.apache.commons.math.geometry.*;

PeasyCam cam;

PVector a = new PVector (0,0,0);
PVector b = new PVector (100,100,100);

void setup()
{
  size(800,800,P3D);
  cam = new PeasyCam(this, 1000);
  cam.setMinimumDistance(300);
  cam.setMaximumDistance(1000);
}
void draw()
{
  background(125);

  strokeWeight(5);
  stroke(0);
  //the line that I want the cylinder to align with
  line(a.x,a.y,a.z,b.x,b.y,b.z);

  strokeWeight(1);
  stroke(255,0,0);
  line(0,0,0,500,0,0);
  stroke(0,255,0);
  line(0,0,0,0,500,0);
  stroke(0,0,255);
  line(0,0,0,0,0,500);
  noStroke();
  fill(150,0,0);

  //draw cylinder
  cylinder(5,1,PVector.dist(a,b),a,b);
}

void cylinder(int sides, float r, float h, PVector a, PVector b)
{
  pushMatrix();
    translate((a.x+b.x)/2, (a.y+b.y)/2, (a.z+b.z)/2);
    float radians = PVector.angleBetween(PVector.sub(b,a), new PVector(0,0,1));  //radians
    println(radians);
    rotateX(radians);
    rotateY(radians);
    rotateZ(radians);

    float angle = 360 / sides;
    float halfHeight = h / 2;
    // draw top shape
    beginShape();
    for (int i = 0; i < sides; i++) {
        float x = cos( radians( i * angle ) ) * r;
        float y = sin( radians( i * angle ) ) * r;
        vertex( x, y, -halfHeight );    
    }
    endShape(CLOSE);
    // draw bottom shape
    beginShape();
    for (int i = 0; i < sides; i++) {
        float x = cos( radians( i * angle ) ) * r;
        float y = sin( radians( i * angle ) ) * r;
        vertex( x, y, halfHeight );    
    }
    endShape(CLOSE);
    beginShape(TRIANGLE_STRIP);
    for (int i = 0; i < sides + 1; i++) {
    float x = cos( radians( i * angle ) ) * r;
    float y = sin( radians( i * angle ) ) * r;
    vertex( x, y, halfHeight);
    vertex( x, y, -halfHeight);    
    }
    endShape(CLOSE);  
  popMatrix();
}   

Answers

Sign In or Register to comment.