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);
//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);
void draw() {
//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);;
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;
 void run() {
 void gravity() {
 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() {
void display() {
 ellipse(loc.x, loc.y, 30, 30);

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s