Skip to content

Instantly share code, notes, and snippets.

@Nekodigi
Created July 19, 2020 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nekodigi/4e750c58979ac51974254363dc7b31f9 to your computer and use it in GitHub Desktop.
Save Nekodigi/4e750c58979ac51974254363dc7b31f9 to your computer and use it in GitHub Desktop.
Ball ball;
ArrayList<Block> blocks = new ArrayList<Block>();
int bs = 100;//block size
int ni, nj;
void setup(){
fullScreen();
//size(1000, 1000);
ball = new Ball(new PVector(width/2, height/2+bs+EPSILON), new PVector(20, 10), bs/2);
ni = width/bs;
nj = height/2/bs;
for(int i=0; i<ni; i++){
for(int j=0; j<nj; j++){
blocks.add(new Block(new PVector(i*bs+bs/2, j*bs+bs/2), bs/2, true));
}
}
}
void draw(){
background(255);
fill(0);
ball.update(blocks);
ball.show();
for(Block block : blocks){
block.show();
}
int second = millis()/1000;
fill(255);
textSize(200);
textAlign(LEFT, TOP);
text(second, 0, 0);
}
void mousePressed(){
blocks.add(new Block(new PVector(mouseX, mouseY), bs, true));
}
class Ball{
PVector pos, vel = new PVector();
float r;
Ball(PVector pos, PVector vel, float r){
this.pos = pos;
this.vel = vel;
this.r = r;
}
void update(ArrayList<Block> blocks){
if(pos.x < 0 || pos.x > width){vel.x = -vel.x;pos.add(vel);}
if(pos.y < 0 || pos.y > height){vel.y = -vel.y;pos.add(vel);}
for(Block block : blocks){
if(block.broken == false){
float dstx = abs(pos.x - block.pos.x);
float dsty = abs(pos.y - block.pos.y);
boolean inside = block.isInside(this);
if(inside)block.broken = true && block.breakable;
if(inside && dsty < dstx){vel.x = -vel.x;pos.add(vel);}
if(inside && dstx <= dsty){vel.y = -vel.y;pos.add(vel);}
}
}
pos.add(vel);
}
void show(){
rect(pos.x-r, pos.y-r, r*2, r*2);
}
}
class Block{
PVector pos;
float r;
boolean breakable;
boolean broken;
Block(PVector pos, float r, boolean breakable){
this.pos = pos;
this.r = r;
this.breakable = breakable;
}
boolean isInside(Ball ball){
float dstx = abs(pos.x - ball.pos.x);
float dsty = abs(pos.y - ball.pos.y);
float d = (ball.r+r);
return dstx < d && dsty < d;
}
void show(){
if(!broken)rect(pos.x-r, pos.y-r, r*2, r*2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment