Posted by : Unknown
Senin, 04 April 2016
Sketch 1
ball[] balls = new ball[10];
void setup() {
size(700,700);
for(int i = 0; i < balls.length; i++) {
balls[i] = new ball(int(random (50,400)), int (random (50,400)), int(random (5)),int (random(5)),int (random (10,100)));
}
}
void draw() {
background(155);
for(int i = 0; i < balls.length; i++) {
balls[i].display();
balls[i].update();
}
}
void mousePressed() {
for(int i = 0; i < balls.length; i++) {
if(balls[i].pointInEllipse(mouseX,mouseY)) {
balls[i].changeColor();
}
}
}
Sketch 2
class ball {
private int y, x, dy, dx, size;
private color ballColor = color(255,0,0);
public ball(int y, int x, int dy, int dx, int size) {
this.y = y;
this.x = x;
this.dy = dy;
this.dx = dx;
this.size = size;
}
public void update() {
move();
checkCollisionsWithWalls();
}
public void move() {
y += dy;
x += dx;
}
public void checkCollisionsWithWalls() {
if(isCollidingWithHorizontalWalls()) {
setdy(getdy() * -1);
}
if(isCollidingWithVerticalWalls()) {
setdy(getdx() * -1);
}
}
public boolean isCollidingWithVerticalWalls() {
if(getX()+(getSize()/2) > width || getX()-(getSize()/2) < 0) {
return true;
}
return false;
}
public boolean isCollidingWithHorizontalWalls() {
if(getY()+(getSize()/2) > width || getY()-(getSize()/2) < 0) {
return true;
}
return false;
}
public void display() {
fill(this.ballColor);
ellipse (x,y,size,size);
}
public int getY() {
return this.y;
}
public int getX() {
return this.x;
}
public int getSize() {
return this.size;
}
public void setdy(int dy) {
this.dy=dy;
}
public void setdx(int dx) {
this.dx=dx;
}
public int getdy() {
return this.dy;
}
public int getdx() {
return this.dx;
}
public boolean pointInEllipse(int x, int y) {
double distance = Math.sqrt(Math.pow((x-getX()),2) + Math.pow((y - getY()), 2));
if(distance < getSize()/2){
return true;
}
return false;
}
public void changeColor() {
if (red(this.ballColor) == 255) {
this.ballColor = color (0,255,0);
} else {
this.ballColor = color (255,0,0);
}
}
}