Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add an example? #35

Open
GanWeaving opened this issue Jul 25, 2013 · 0 comments
Open

How to add an example? #35

GanWeaving opened this issue Jul 25, 2013 · 0 comments

Comments

@GanWeaving
Copy link

I'm sorry this is surely not the way to go but I'm not sure how to do it otherwise ...

Here's the code for example 1.3 from the book:

/* built with Studio Sketchpad:

// Nature of Code - EXERCISE 1.3 - 3D Bouncing Ball
// Extend the bouncing ball with vectors example into 3D.
// Can you get a sphere to bounce around a box?

// https://forum.processing.org/topic/
// the-nature-of-code-code-solutions-of-the-examples

// studio.processingtogether.com/sp/pad/export/ro.9o1T5z1ghf2s7/latest

final PVector location = new PVector();
final PVector velocity = new PVector(3, 2, 4);

final static int BALL_DIM = 30;
final static int CUBE_DIM = 450, CUBE_RAD = CUBE_DIM >> 1;

int cx, cy;

void setup() {
size(400, 400, P3D);
strokeWeight(2);

cx = width >> 1;
cy = height >> 1;
}

void draw() {
background(-1);

drawCube();
moveSphere();
drawSphere();
}

void drawCube() {
//move cube and ball to center:
translate(cx, cy, -CUBE_DIM);

//rotate cube and ball so it's 3D-ness can be appreciated:
rotateX(-QUARTER_PI);
rotateY(QUARTER_PI);
rotateZ(QUARTER_PI/2);

//draw cube:
noFill();
stroke(0);

box(CUBE_DIM);
}

void moveSphere() {
//move ball:
location.add(velocity);

//detect edges with center at 0,0 and edge minus width of ball:
if ( checkBounce(location.x) ) velocity.x *= -1;
if ( checkBounce(location.y) ) velocity.y *= -1;
if ( checkBounce(location.z) ) velocity.z *= -1;
}

void drawSphere() {
//draw ball, and lights for definition:
translate(location.x, location.y, location.z);

fill(0300);
noStroke();
lights();

sphere(BALL_DIM);
}

static final boolean checkBounce(float coord) {
return coord > CUBE_RAD - BALL_DIM | coord < BALL_DIM - CUBE_RAD;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant