3D Control with Mouse
in
Programming Questions
•
8 months ago
Hello,
I'm trying to create a camera in a 3D environment that is controlled by a mouse and the WASD keys. So far i can get it to move, but I tried using spherical coordinates to help me control the direct the camera points with the mouse but it is really glitchy. What am I doing wrong? I also wanted to use the robot class to keep the mouse centered in the screen but that is not working either.
- import java.awt.AWTException;
- import java.awt.Robot;
- Robot robot;
- void setup() {
- size(640, 360, P3D);
- noStroke();
- fill(204);
- try{
- robot = new Robot();
- } catch (AWTException e){
- e.printStackTrace();
- }
- noCursor();
- }
- float playerX = 0;
- float playerY = -160;
- float playerZ = 0;
- float focusX = 0;
- float focusY = 0;
- float focusZ = 0;
- long count = 0;
- float currentMouseX = 320;
- float currentMouseY = 180;
- float gamma = 0;
- float phi = 0;
- void draw() {
- //if(count%3 == 0){
- gamma += (currentMouseX - mouseX)/300;
- gamma = (gamma + PI)%(2*PI) - PI;
- phi += -(currentMouseY - mouseY)/30;
- phi = (phi + PI)%(2*PI) - PI;
- focusX = playerX + 10.0*sin(gamma)*cos(phi);
- focusY = playerY + 10.0*sin(gamma)*sin(phi);
- focusZ = playerZ + 10.0*cos(gamma);
- // robot.mouseMove(frame.getLocation().x + width/2, frame.getLocation().y + height/2);
- currentMouseX = mouseX;
- currentMouseY = mouseY;
- //}
- println(gamma + " " + phi);
- count++;
- background(0);
- lights();
- pointLight(256, 256, 256, playerX, playerY, playerZ);
- //spotLight(256, 256, 256, playerX, playerY, playerZ, focusX, focusY, focusZ, PI/2, 2);
- camera(playerX, playerY, playerZ, focusX, focusY, focusZ, 0, 1, 0);
- float distanceX = playerX - focusX;
- float distanceZ = playerZ - focusZ;
- float distanceXZ = distance2D(playerX, playerZ, focusX, focusZ);
- if(keyPressed){
- if(key == 'w' || key == 'W'){
- playerX -= (distanceX*10)/distanceXZ;
- playerZ -= (distanceZ*10)/distanceXZ;
- }
- if(key == 's' || key == 'S'){
- playerX += (distanceX*10)/distanceXZ;
- playerZ += (distanceZ*10)/distanceXZ;
- }
- if(key == 'a' || key == 'A'){
- playerX -= (distanceZ*10)/distanceXZ;
- playerZ += (distanceX*10)/distanceXZ;
- }
- if(key == 'd' || key == 'D'){
- playerX += (distanceZ*10)/distanceXZ;
- playerZ -= (distanceX*10)/distanceXZ;
- }
- }
- pushMatrix();
- translate(0, -80, 0);
- box(160);
- popMatrix();
- pushMatrix();
- translate(160, -240, 0);
- box(160);
- popMatrix();
- pushMatrix();
- translate(-5000, 0, -5000);
- rotateX(PI/2);
- rect(0,0,10000,10000);
- popMatrix();
- /*pushMatrix();
- translate(playerX + 10,playerY + 80 ,playerZ);
- rotateZ(PI/3);
- box(10,160,10);
- popMatrix();*/
- }
- float distance3D(float xa, float ya, float za, float xb, float yb, float zb){
- return sqrt(square(xa-xb) + square(ya-yb) + square(za-zb));
- }
- float distance2D(float xa, float ya, float xb, float yb){
- return sqrt(square(xa-xb) + square(ya-yb));
- }
- float square(float a){
- return a*a;
- }
1