Created
January 3, 2012 12:22
-
-
Save carstenschwede/1554734 to your computer and use it in GitHub Desktop.
Simple testApp.cpp for a moving ball in openFrameworks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//BALL "TUTORIAL" FOR SUSANA RIBEIRO | |
#include "testApp.h" | |
//FIRST WE NEED TO DECLARE SOME THINGS ABOUT A "BALL" | |
struct BallStructure { | |
ofPoint position; //A BALL HAS A POSITION | |
int radius; //AND A RADIUS OF COURSE | |
ofColor color; //AND WE LIKE TO LET IT HAVE A COLOR | |
ofPoint direction; //A BALL HAS SPEED IN SOME DIRECTION | |
}; | |
//OK, NOW WE KNOW HOW A BALL LOOKS LIKE; SO WE CAN CREATE ONE: | |
BallStructure myFirstBall; | |
//-------------------------------------------------- | |
void testApp::setup() { | |
//HERE WE ARE SETTING THE RATE AT WHICH WE THE PROGRAM WILL RUN (AND HOW MANY TIMES PER SECOND THE UPDATE AND DRAW METHODS ARE CALLED IT IN FRAMES PER SECOND) | |
ofSetFrameRate(60); | |
//NOW WE TELL THE FIRST BALL HOW IT LOOKS LIKE: | |
//FIRST WE GIVE IT A RANDOM POSITION | |
myFirstBall.position.x = ofRandom(0,ofGetWidth()); | |
myFirstBall.position.y = ofRandom(0,ofGetHeight()); | |
//AND A RADIUS | |
myFirstBall.radius = ofRandom(10,30); | |
//AND THE COLOR | |
myFirstBall.color = ofColor::fromHsb(ofRandom(0,255),255,255); | |
//AND A RANDOM SPEED/DIRECTION | |
myFirstBall.direction.x = ofRandom(-15,15); | |
myFirstBall.direction.y = ofRandom(-15,15); | |
} | |
//-------------------------------------------------- | |
void testApp::update() { | |
//HERE WE UPDATE THE POSITION OF THE BALL BASED ON THE SPEED/DIRECTION | |
myFirstBall.position = myFirstBall.position + myFirstBall.direction; | |
//HERE WE CHECK IF WE REACHED THE BORDERS OF THE WINDOW AND BOUNCE IT BACK | |
if (myFirstBall.position.x < 0) { | |
myFirstBall.direction.x = abs(myFirstBall.direction.x); | |
} | |
if (myFirstBall.position.y < 0) { | |
myFirstBall.direction.y = abs(myFirstBall.direction.y); | |
} | |
if (myFirstBall.position.x > ofGetWidth()) { | |
myFirstBall.direction.x = -abs(myFirstBall.direction.x); | |
} | |
if (myFirstBall.position.y > ofGetHeight()) { | |
myFirstBall.direction.y = -abs(myFirstBall.direction.y); | |
} | |
} | |
//-------------------------------------------------- | |
void testApp::draw() { | |
//NOW WE CAN DRAW THE BALL | |
//FIRST WE SET THE COLOR | |
ofSetColor(myFirstBall.color); | |
//AND NOW WE CAN DRAW A CIRCLE AT THE POSITION OF THE BALL WITH ITS RADIUS | |
ofCircle(myFirstBall.position,myFirstBall.radius); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment