#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# How to make a cube face a 3D coordinate (x,y,z) ?

edited January 2017

Hi,

I have a problem with a sketch in witch I need to make some cubes face a certain coordinate in P3D it works for the Z axis just like 2D with atan2() but when it comes to the X and Y axis it doesn't work :/

here is the code I have for now:

``````import peasy.*;

PeasyCam cam;

float x;
float y;
float z;

void setup() {
size(500,500,P3D);
cam = new PeasyCam(this, 100);
}

void draw() {
background(50);

//the angles
float angleZ = atan2(-x,y); //-x,y
float angleX = atan2(0,z);
float angleY = atan2(-z,x);

//Cube that need to face the target
pushMatrix();
rotateZ(angleZ);
rotateX(angleX);
//rotateY(angleY);
translate(0,0,0);
box(100);
line(0,0,0,0,1000,0);
popMatrix();

//Cube that need to face the target
pushMatrix();
translate(1000,1000,1000);
rotateZ(atan2(-x+1000,y-1000));
//rotateX(atan2(y+100,-z-100));
box(100);
line(0,0,0,0,1000,0);
popMatrix();

//to control the little cube (target)
if(keyPressed) {
if(keyCode==UP) {
y+=4;
}
if(keyCode==DOWN) {
y-=4;
}
if(keyCode==LEFT) {
x+=4;
}
if(keyCode==RIGHT) {
x-=4;
}
if(key==' ') {
z+=4;
}
if(keyCode==SHIFT) {
z-=4;
}
}

//little cube (taget)
pushMatrix();
translate(x,y,z);
box(50);
popMatrix();
}
``````

I used the peasyCam so its easier to see and control

float x,y,z are the targets to face, you can control them with Arrows Space and Shift

thanks !

Tagged: