Hello! im trying to create a 3D camera that rotates when mouse is dragged.
I created something that works, but the movement feels very strange.
Here’s my code:
Planet p = new Planet(new PVector(width / 2, height / 2, 100), 15);
PVector camPos = new PVector(width / 2, height / 2, 0);
PVector camDir = new PVector(width / 2, height / 2, 100);
float aYZ = 0;
float aXZ = 0;
void setup() {
size(900, 900, P3D);
perspective(PI / 2, float(width) / float(height), 0.1, 1000000);
}
void draw() {
background(0);
float camDirX = 100 * sin(aYZ) * cos(aXZ) + camPos.x;
float camDirY = 100 * sin(aYZ) * sin(aXZ) + camPos.y;
float camDirZ = 100 * cos(aYZ) + camPos.z;
camDir = new PVector(camDirX, camDirY, camDirZ);
println(sin(aYZ));
camera(camPos.x, camPos.y, camPos.z, camDir.x, camDir.y, camDir.z, 0, 1, 0);
if (keyPressed) {
if (key == 'w') {
camPos = camPos.add(camDir.copy().sub(camPos).normalize());
camDir = camDir.add(camDir.copy().sub(camPos).normalize());
} else if (key == 's') {
camPos = camPos.add(camDir.copy().sub(camPos).normalize().mult(-1));
camDir = camDir.add(camDir.copy().sub(camPos).normalize().mult(-1));
}
}
p.show();
}
void mouseDragged() {
float dx = mouseX - pmouseX;
float dy = mouseY - pmouseY;
aXZ += dy / 100;
aYZ += dx / 100;
}
there is also a Planet and Body3D class:
class Body3D{
PVector pos;
PVector vel = new PVector(0,0,0);
PVector acc = new PVector(0,0,0);
float m;
void applyAcc(PVector acc_){
acc = acc.add(acc_);
}
void update(){
vel = vel.add(acc);
pos = pos.add(vel);
acc = new PVector(0,0,0);
}
}
class Planet extends Body3D{
Planet(PVector pos_, float m_){
this.pos = pos_;
this.m = m_;
}
void show(){
lights();
noStroke();
fill(255);
translate(pos.x,pos.y,pos.z);
sphere(this.m * 1.3);
}
}
Thanks!