Still trying to realize how to align an object to a vector.
Now I have implemented the method which uses the cross and dot products of the original and targer vector. The code below seems to work except for the rotate method doing strange thing. By replacing theta in line 37 with smaller numbers such as 0.001 and 0.01 I have found that the rotate() does not rotate ok. It also translates and resizes everything. If the 0.001 or 0.01 is in place in line 37, then I can only see the box when I move both points close to each other in the bottom left of the screen, which is reeeeely strange for me. When theta is in place, the box is almost too big to fit on the screen even at that case. The similar (in my mind) method of glRotatef() on contrary, does nothing at all. How to make the rotate() method behave as expected? (use 'qweasd' to move the bottom point and 'uiojkl' to move the upper one).
- import processing.opengl.*;
- PVector v0; // always 0, 0, 1
- PVector v1; // point 1
- PVector v2; // point 2
- PVector v; // resulting vector from v2-v1
- float speed = 4;
- void setup(){
- size(800, 600, OPENGL);
- v1 = new PVector(0, 500, 0);
- v2 = new PVector(0,-500, 0);
- v0 = new PVector(0, 0, 1);
- }
- void draw(){
- background(255, 155, 50);
- strokeWeight(1);
- fill(255);
- translate(width / 2, height / 2, -1000);
- pushMatrix();
- //center the scene
- translate(v1.x + (v2.x - v1.x)/2, v1.y + (v2.y - v1.y)/2, v1.z + (v2.z - v1.z)/2);
- v = new PVector (v2.x - v1.x, v2.y - v1.y, v2.z - v1.z);
- PVector cross = v0.cross(v);
- PVector vn = new PVector(v.x, v.y, v.z);
- vn.normalize();
- float theta = acos(v0.dot(vn));
- //rotation
- rotate(theta, cross.x, cross.y, cross.z);
- //((PGraphicsOpenGL)g).gl.glRotatef(theta, cross.x, cross.y, cross.z);
- // scale(10, 10, 10);
- box(100);
- stroke(255,0,0);
- strokeWeight(3);
- line(0, 0, 0, 200, 0, 0);
- stroke(0, 255,0);
- line(0, 0, 0, 0, 200, 0);
- stroke(0,0,255);
- line(0, 0, 0, 0, 0, 200);
- stroke(155,20,255);
- line(0, 0, 0, vn.x * 100, vn.y * 100, vn.z * 100);
- println("vector : " + v.toString());
- popMatrix();
- stroke(0);
- drawV(v1);
- drawV(v2);
- line(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z);
- controls();
- fill(0);
- }
- void drawV(PVector v){
- pushMatrix();
- translate(v.x, v.y, v.z);
- sphere(30);
- popMatrix();
- }
- void controls(){
- if(keyPressed){
- switch(key){
- // one
- case 'w':
- v1.z -= speed;
- break;
- case 'a':
- v1.x -= speed;
- break;
- case 's':
- v1.z += speed;
- break;
- case 'd':
- v1.x += speed;
- break;
- case 'q':
- v1.y -= speed;
- break;
- case 'e':
- v1.y += speed;
- break;
- //two
- case 'i':
- v2.z -= speed;
- break;
- case 'j':
- v2.x -= speed;
- break;
- case 'k':
- v2.z += speed;
- break;
- case 'l':
- v2.x += speed;
- break;
- case 'u':
- v2.y -= speed;
- break;
- case 'o':
- v2.y += speed;
- break;
- }
- }
- }
1