Hi, basically i have a programmed an App that is essentially 2 balls, one is controlled by the mouse and is used to 'bounce' the other around the window.
Essentially i'm wondering if anybody can help me to implement vectors in my code as I've heard it's a better way to do this kind of thing, and it cleans up the code, but I've never used it and am having trouble understanding how to do it.
anyway here is the code;
float bx;
float by;
int ballSize = 20;
int ballSize2 = 40;
int m;
boolean bover = true;
boolean locked = false;
float xOffset = 0.0;
float yOffset = 0.0;
int numBalls = 2;
float spring = 0.05;
float friction = -0.4;
Ball[] balls = new Ball[numBalls];
void setup() {
size (640,600);
bx = height/2;
by = width/2;
stroke(0);
background(120);
noStroke();
smooth();
balls[0] = new Ball(300, 205, height/8, 0, balls);
balls[1] = new Ball(bx, by, height/7, 1, balls);
fill(0);
}
void draw()
{
background(0);
for (int i = 0; i < numBalls; i++) {
balls[i].collide();
balls[i].move();
balls[i].display();
}
balls[0].x = mouseX+5;
balls[0].y = mouseY+5;
if (mouseX > bx-ballSize && mouseX < bx+ballSize &&
mouseY > by-ballSize && mouseY < by+ballSize) {
bover = true;
if(!locked) {
}
}
else {
stroke(100);
bover = false;
}
}
class Ball {
float x, y;
float diameter;
float vx = 0;
float vy = 0;
int id;
float mass;
float spring = 0.2;
float rest_posx;
float rest_posy;
Ball[] others;
Ball(float xin, float yin, float din, int idin, Ball[] oin) {
x = xin;
y = yin;
diameter = din;
id = idin;
others = oin;
}
void collide() {
for (int i = id + 1; i < numBalls; i++) {
float dx = others[i].x - x;
float dy = others[i].y - y;
float distance = sqrt(dx*dx + dy*dy);
float minDist = others[i].diameter/2 + diameter/2;
if (distance < minDist) {
float angle = atan2 (dy, dx);
float targetX = x + cos(angle) * minDist;
float targetY = y + sin(angle) * minDist;
float ax = (targetX - others[i].x) * spring;
float ay = (targetY - others[i].y) * spring;
vx -= ax;
vy -= ay;
others[i].vx += ax;
others[i].vy += ay;
}
}
}
void move() {
x += vx;
y += vy;
if (x + diameter > width) {
x = width - diameter;
vx *= friction;
}
else if (x - diameter < 0) {
x = diameter;
vx *= friction;
}
if (y + diameter > height) {
y = height - diameter;
vy *= friction;
}
else if (y - diameter < 0) {
y = diameter;
vy *= friction;
}
}
void display() {
fill(255, 204);
ellipse(x, y, diameter, diameter);
}
}
void mousePressed() {
if(bover) {
locked = true;
}
else {
locked = false;
}
xOffset = mouseX-bx;
yOffset = mouseY-by;
}
void mouseDragged() {
if(locked) {
bx = mouseX-xOffset;
by = mouseY-yOffset;
}
}
void mouseReleased() {
locked = false;
}
Any help would be greatly appreciated!!
Thanks
cron12
1