Vector class

From here I learnt how to import a library called ‘toxiclibs’ which is basically a more advanced complex class code for 3d vectors, however I will just be using it in the 2D sense.

I had to go back to my previous ball bouncing code and change parts so it was working with vectors. It involved changing all my x and y integers to vectors, defining these at the beginning of the code as vec3D so I could then include them in my code, calling them vec3D.loc instead of x and y and vec.3D.speed instead of x.speed and y.speed. I also replaced all the floats with just one vector. It doesn’t make it look much differently at the moment, just changed the way of writing it.

import toxi.geom.*;
//Declares the class then class instance 
ArrayList ballCollection;
void setup() {
 size(600, 600);
 smooth();
//Initializes the class. New is saying create a new instance of the class 'Ball'
 ballCollection = new ArrayList();
for (int i = 0; i<100; i++) {
 Vec3D origin = new Vec3D(random(width), random(200), 0);
 Ball myBall = new Ball(origin);
 ballCollection.add(myBall);
 }
}
void draw() {
background(0);
//Calls the function of the class. The '.' opens up the class.
for (int i = 0; i<ballCollection.size(); i++) {
 Ball mb = (Ball) ballCollection.get(i);
 mb.run();
 }
}
class Ball {
//global variables. location, speed...
Vec3D loc = new Vec3D (0, 0, 0);
 Vec3D speed = new Vec3D(1, 0, 0);
 Vec3D grav = new Vec3D(0,0.2,0);
 //constructor. how to build the class, calling variables, happens just once.
 Ball(Vec3D _loc) {
loc = _loc;
 }
 //functions.
 void run() {
 display();
 move();
 bounce();
 gravity();
 }
 
 void gravity() {
 speed.addSelf(grav);
 }
 
 
 void bounce() {
 
 if (loc.x > width) {
 speed.x = speed.x * -1;
 }
 if (loc.x < 0) {
 speed.x = speed.x * -1;
 }
 if (loc.y > height) {
 speed.y = speed.y * -1;
 }
 if (loc.y < 0) {
 speed.y = speed.y * -1;
 }
 }
 
 
 void move() {
loc.addSelf(speed);
 }
void display() {
 noStroke();
 fill(255);
 ellipse(loc.x, loc.y, 30, 30);
 }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s