Spherical Coordinated Camera

edited March 2016 in Questions about Code

hello there,

trying to create my own class for spherical movement of camera (based on mouse movement), i am experiencing a problem setting the up vector for the camera: when scrolling the camera on the up and down the matrix (x and y) seem to flip.

don't seem to have this problem with the horizontal scroll.

help anyone?

thanks

float camX, camY, camZ;
float camRad = width*20;
float camTheta, camPhi;
float camDragX, camDragY;
float newCamX = 50;
float newCamY = 600;
boolean moveCam = false;
PVector up;

void cam() {                                                                                            //camera
  camPhi   = map(newCamX, 0, width, PI, -PI);                              //phi is the horizontal angle 0-2PI    
  camTheta = map(newCamY, 0, height, HALF_PI, -HALF_PI);        //theta is the vertical angle 0-PI
  up    = new PVector (sin(camPhi), cos(camPhi));


  camX = camRad*sin(camTheta)*sin(camPhi);
  camY = camRad*sin(camTheta)*cos(camPhi);  
  camZ = camRad*cos(camTheta);

  camera(camX, camY, camZ, 0, 0, 0, up.x, up.y, up.z);
}

void mousePressed() {
  if (mouseButton == RIGHT) {
    camDragX = mouseX - newCamX;
    camDragY = mouseY - newCamY;
    moveCam = true;
  }
}

void mouseDragged() {
  if (mouseButton == RIGHT) {
    if (moveCam) {
      newCamX = mouseX - camDragX;
      newCamY = mouseY - camDragY;
    }
  }
}

void mouseReleased() {
  moveCam = false;
}

void mouseWheel(MouseEvent event) {
  float zoom = event.getCount();
  zoom = zoom*50;
  camRad += zoom;
}

void setup () {
  size (500, 500, P3D);
  colorMode(HSB, 360, 1, 1, 1);  
}


void draw() {
  background (0, 0, 1);  
  drawAxis();
  cam();
  fill(1,0,0);
  ellipse (width/2, height/2, 250, 250);
}

void drawAxis() {
  stroke (0, 1, 1);
  line (0, 0, 0, 1000, 0, 0);
  stroke (90, 1, 1);
  line (0, 0, 0, 0, 1000, 0);
  stroke (210, 1, 1);
  line (0, 0, 0, 0, 0, 1000);
  noStroke();
}

Answers

  • Highlight code, press ctrl-o

  • Have you seen the peasycam library?

  • yes i am aware of it, but in this exercise i'm trying to develop my own class.

  • When you rotate up

    The image is upsidedown

    Not a bug only logical - camera turns

    You can compensate by saying up.y = -1 or something - test it

  • Probably with if....camTheta....

  • Answer ✓

    solved, by adding:

    if (camZ<0) up.mult(-1);

    (before the camera command)

    this works and generates a 3d spherical coordinates with the Z axis facing up, though there's obviously something i'm missing in the math which forces me to introduce the condition.

    thanks for the help

Sign In or Register to comment.