# Defining Coordinates of a Sphere

Hello!
I’m interested in defining the coordinates of where a sphere lies in a 3D space. I know sphere uses just radius `sphere(r);`

Is there a way to define (x,y,z) values?

2 Likes

Here is a clue from processing reference:-

``````noStroke();
lights();
translate(58, 48, 0);
sphere(28);
``````
1 Like

If you want a data structure for 3D spheres of different size / locations, you can also make a simple class.

``````ArrayList<SphereLoc> spheres = new ArrayList<SphereLoc>();
void setup() {
size(400, 400, P3D);
for(int i=0;i<50;i++){
}
}

void draw(){
background(128);
for(int i=0; i<spheres.size(); i++){
spheres.get(i).render();
}
}

class SphereLoc {
float x, y, z, r;
SphereLoc(float x, float y, float z, float r){
this.x = x;
this.y = y;
this.z = z;
this.r = r;
}
void render() {
translate(x, y, z);
sphere(r);
translate(-x, -y, -z);
}
}
``````

You could also do the class render with pushMatrix / popMatrix, but translating back should be a bit faster.

1 Like

Some remarks:

• I recommend to use lights() in 3D and
• also to use noStroke(); with spheres, together with fill();
• There is a shorter form of a for loop, I use it in draw() below

here

``````
ArrayList<SphereLoc> spheres = new ArrayList<SphereLoc>();

void setup() {
size(900, 900, P3D);
for (int i=0; i<50; i++) {
spheres.add(new SphereLoc(random(0, 900), random(0, 900), random(70, -300),
random(40)));
}
noStroke();
}

void draw() {
background(128);
lights();
for (SphereLoc currentSphere : spheres) {
currentSphere.render();
}
}

// ============================================================

class SphereLoc {

float x, y, z, r;
color col=color(random(255), random(255), random(255));

// constr
SphereLoc(float x, float y, float z, float r) {
this.x = x;
this.y = y;
this.z = z;
this.r = r;
}// constr

void render() {
translate(x, y, z);
fill(col);
sphere(r);
translate(-x, -y, -z);
}
//
}//class
//
``````
3 Likes

@Chrisir @jeremydouglass
Thanks for the help! The information about class worked great for my project.

1 Like