Home > Back-end >  Changing the position of a sphere in P5.js
Changing the position of a sphere in P5.js

Time:10-23

By default, it seems like a sphere object in P5 is located at (0,0). I want to create an object that is visually represented by a sphere with the ability to define the x and y coordinates of the sphere object.

Because I want to deal with multiple of these objects and draw connections between them, I don't want to use the translate function for a sphere to position it every time. Is there a way to position the sphere to the coordinates I want without the translate function?

CodePudding user response:

You can still use translate() without affecting the global coordinate system by isolating local coordinate systems within push()/pop() calls. You can read more in the 2D Transformation tutorial. Even through it's for Processing, the only difference is swapping pushMatrix() for push() and popMatrix() for pop() and the concept translates to 3D as well, not just 2D.

function drawSphere(x, y, z, radius){
  push(); // enter local coordinate system
  translate(x, y, z);
  sphere(radius);
  pop(); // exit local coordinate system (back to global coordinates)
}

Here's a basic example drawing multiple spheres and lines between them:

const NUM_POINTS = 12;
let points = new Array(NUM_POINTS).fill();;

function setup(){
  createCanvas(600, 600, WEBGL);
  noFill();
  // shorthand for initialising 12 random points at a set distance
  points.forEach((p,i) => points[i] = p5.Vector.random3D().mult(150));
}

function draw(){
  background(255);
  rotateY(frameCount * 0.01);
  // draw spheres (and lines from centre)
  for(let i = 0 ; i < NUM_POINTS; i  ){
    // get each point
    const point = points[i];
    // draw sphere
    drawSphere(point.x, point.y, point.z, 30);
    // draw lines (optional)
    const nextPoint = points[(i   1) % NUM_POINTS];
    line(nextPoint.x, nextPoint.y, nextPoint.z, point.x, point.y, point.z);
  }
}

function drawSphere(x, y, z, radius){
  push(); // enter local coordinate system
  translate(x, y, z);
  sphere(radius, 6);
  pop(); // exit local coordinate system (back to global coordinates)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script>

(If you're familiar with 3D packages such as Blender, C4D, Maya, etc. most of these allow you to nest an object inside another object (inheriting the parent's transformation, but allowing indepedent transformations which don't affect the parent. This is roughtly what you can achieve with push()/pop() calls).

CodePudding user response:

function createSphere(x, y, z, r) {
  translate(x, y, z)
  sphere(r)
}

usage

createSphere(1, 2, 3, 10)
  • Related