将对象保持在屏幕上

时间:2014-04-22 14:38:19

标签: object collision-detection processing

现在我确定你们都听说过这些愚蠢的台球游戏问题,这应该是我的最后一次,我已经将碰撞击倒,但是将它保持在屏幕上是一个问题。我该怎么做呢?

 class Ball {
  int xpos, ypos;
  int ballDiam;
  color myColor;
  Ball(int tempdiam, color tempColor) {
    ballDiam=tempdiam;
    myColor=tempColor;
  }

  void update() {
    fill(myColor);
    ellipse(xpos, ypos, ballDiam, ballDiam);
  }
}

Ball b1, b2;
int click;
String msg;
int steps = 30;
int difx,dify;
Boolean moving = false;
void setup() {
  msg="";
  click=0;
  size(600, 300);
  b2= new Ball(50, #000000);
  b1 = new Ball(50, #ffffff);
}
void draw() {
  background(#009900);
  b1.update();
  b2.update();

  if (click==0) {
    b1.xpos=mouseX;
    b1.ypos=mouseY;

    msg="click to place ball";
  }
  if (click==0) {
    b1.xpos=mouseX;
    b1.ypos=mouseY;
    b1.update();
  }
  else if (click==1) {
    b2.xpos=mouseX;
    b2.ypos=mouseY;
    b2.update();
    difx = b1.xpos-b2.xpos;
    dify = b1.ypos-b2.ypos;
    msg="click to place eightball and shoot";
  } else if(click==2){
    b1.xpos-=difx/steps;
    b1.ypos-=dify/steps;
    b1.update();
    //cdistance = dist(b1.xpos,b1.ypos,b2.xpos,b2.ypos);
    float distance = dist(b1.xpos,b1.ypos,b2.xpos,b2.ypos);
    if(distance>b2.ballDiam/2){
      moving = true;
      b1.xpos-=difx/steps;
      b1.ypos-=dify/steps;
    }
    else{
      moving = false;
      msg="new";
      click=3;

    }

  }

  else if(click==3){
    if (b1.xpos<b2.xpos && b1.ypos<b2.ypos){
        b2.xpos+=5;
        b2.ypos+=5;
      }
    if (b1.xpos>b2.xpos && b1.ypos>b2.ypos){
        b2.xpos-=5;
        b2.ypos-=5;
      }
    if (b1.xpos>b2.xpos && b1.ypos<b2.ypos){
        b2.xpos-=5;
        b2.ypos+=5;
      }
    if (b1.xpos<b2.xpos && b1.ypos>b2.ypos){
        b2.xpos+=5;
        b2.ypos-=5;
      }
    msg="click again to start over";
  }
 else if(click==4){
   setup();
 }


  textSize(20);
  text(msg, 0, height-5);
}


void mouseClicked() {
  if(!moving){
    click++;
  }
}

1 个答案:

答案 0 :(得分:0)

你可以这样做几乎与你在两个球之间进行碰撞检测的方式相同,期望你需要在球和屏幕边界之间进行测试...... 你还要确保利用Ball类的直径属性来确保你真正获得球的边缘,并且它不会反弹并重新进入......

if( b1.xpos + b1.ballDiam >= width ) { // middle of the ball plus its diameter is over the right screen bounds
  println("ball hit the right side");
  b1.xpos = width - b1.ballDiam; // clamping the position to the bounds of the screen
  b1.reverse(); // you probably want to do something about making it bounce back at this point
}

if( b1.xpos - b1.ballDiam <= 0 ) { // middle of the ball minus its parameter is over the left screen bounds
  println("ball hit the left side");
  // all the other stuff here
}

if( b1.ypos - b1.ballDiam <= 0 ) { // middle of the ball minus its parameter is over the top screen bounds
  println("ball hit the top side");
  // all the other stuff here
}

if( b1.ypos + b1.ballDiam >= height ) { // middle of the ball minus its parameter is over the bottom screen bounds
  println("ball hit the bottom side");
  // all the other stuff here
}

有意义吗?