与椭圆碰撞

时间:2014-04-20 00:19:42

标签: processing collision ellipse

我正在处理台球比赛,并试图让母球击球。我把球杆放在桌子底下,我不太明白碰撞。由于某种原因,我必须点击两次才能丢弃母球。

  class Ball{
  PVector postions;
  PVector velocity;
  float r,m;
  Ball(float x, float y, float r_) {
  postion = new PVector(x,y);
  velocity = PVector.random2D();
  velocity.mult(3);
  m = r*.1;
  int xpos,ypos,diam;
  Ball(
  int tempxpos, 
  int tempypos, 
  int tempdiam
  ){
  xpos=tempxpos;
  ypos=tempypos;
  diam=tempdiam;


  }
  void update(){
  postion.add(velocity);
  ellipse(xpos,ypos,diam,diam);
  }

  void checkBoundaryCollision(){
  if(postion.x > width-r) {
  positon.x = width-r;
  veloctiy.x *= -1;
  }
  else if (position.x <r) {
  position.x = r;
  velocity.x*=-1;
  }
  else if (position.y > height-r) {
  position.y = height-r;
  velocity.y*=-1;
   }
  }

  void checkCollision(Ball other) {
  PVector bVect = PVector.sub(other.position, position);
  float bVectMag = bVect.mag();

  if(bVectMag < r + other.r){
   float theta = bVect.heading();
   float sine = sin(theta);
   float cosine = cos(theta);

  PVector[] bTemp = {
    new PVector(), new PVector()
  };

  bTemp[1].x = cosine * bVect.x + sine * bVect.y;
  bTemp[1].y = cosine * bVect.y - sine * bVect.x;

  PVector[] vTemp = {
    new PVector(), new PVector() 
  };

  vTemp[0].x = cosine * velocity.x + sine * velocity.y;
  vTemp[0].y = cosine * velocity.y - sine * velocity.x;
  vTemp[1].x = cosine * other.velocity.x + sine * other.velocity.y;
  vTemp[2].y = cosine * other.velocity.y - sine * other.velocity.x;

  PVector[] vFinal = {
    new PVector(), new PVector()
  };

  vFinal[0].x = ((m - other.m) * vTemp[0].x + 2 * other.m * vTemp[1].x) / (m + other.m);
  vFinal[0].y = vTemp[0].y;

  vFinal[1].x = ((other.m - m) * vTemp[1].x + 2 * m * vTemp[0].x) / (m + other.m);
  vFinal[1].y = vTemp[1].y;

  void display() {
    noStroke();
  }



    Ball b1, b2;
    int mouseClick=0;
    String msg;
    int steps = 20;
    int difx, dify;

   void setup() {
   msg="";
   b1 = new Ball(mouseX, mouseY, 50);
   b2 = new Ball(mouseX, mouseY, 50);
   size(600, 400);
  }



void draw() {
  background(0, 153, 0);
  fill(255, 255, 255);
  b1.update();
  fill(0, 0, 0);
  b2.update();
  textSize(20);
  text(msg, 0, height-5);

  if (mouseClick==0) {
    b1.xpos=mouseX;
    b1.ypos=mouseY;
    msg="click twice to place the ball";
  } 
  else if (mouseClick==1) {
    b1.xpos=mouseX;
    b1.ypos=mouseY;
    fill(255, 255, 255);
    b1.update();
  } 
  else if (mouseClick==3) {
    msg="click to shoot";
    difx = b1.xpos-b2.xpos;
    dify = b2.ypos-b2.ypos;
    b1.xpos-=difx/steps;
    b1.ypos-=dify/steps;
    b1.xpos+=5;
  }

  if (mouseClick==2) {
    msg="click to place the eight ball";
    b2.xpos=mouseX;
    b2.ypos=mouseY;
    b2.update();
  }
}


void mousePressed() {
  mouseClick++;
}

0 个答案:

没有答案