使不同类的对象互动?

时间:2017-10-25 17:00:41

标签: processing

我在处理中创建了一个简单的程序,其中有一个球在屏幕周围弹跳,还有一个能够在屏幕上闪烁和移动的Kirby。我想要的是程序检测球何时接触Kirby以便Kirby可以作为响应闪烁,但是,Kirby和Ball有两个不同的类别。我如何使这项工作?

Kirby k;
Ball b;

void setup() {
  size(400, 400);
  k = new Kirby(width/2, height/2);
  b = new Ball(2);
}

void draw() {
  background(60, 190, 255);
  k.display();
  k.blink();
  b.display();
  b.move();
}

void keyPressed() {
  k.move();
}

class Ball{
  float x = width/4;
  float y = height/4;
  float rb = 30;
  float xspeed = (random(-5, 5));
  float yspeed = (random(-5, 5));

  Ball(int stemp){
    xspeed = xspeed + stemp;
    yspeed = yspeed + stemp;
  }

  void display(){
    fill(0);
    ellipse(x, y, rb, rb);
  }

  void move(){
    x = x + xspeed;
    y = y + yspeed;
    if (y > height || y < 0){
      yspeed *= -1;
    }
    if (x > width || x < 0){
      xspeed *= -1;
    }
  }
}

class Kirby {
  float xpos;
  float ypos;
  float rk = 100;
  float eye = 30;
  float mov = 5;

  Kirby(int xtemp, int ytemp) {
    xpos = xtemp;
    ypos = ytemp;
  }


  void display() {  
    noStroke();
    fill(225, 100, 190);
    ellipse(xpos, ypos, rk, rk);
    fill(0);
    ellipse(xpos - 20, ypos - 10, 10, eye);
    ellipse(xpos + 20, ypos - 10, 10, eye);
  }

  void blink() {
    if (mousePressed == true) {
      eye = 1;
    } else {
      eye = 30;
    }
  }

  void move() {
    if (keyPressed == true) {
      if (key == 'w') {
        ypos = ypos - mov;
      } else if (key == 'a') {
        xpos = xpos - mov;
      } else if (key == 's') {
        ypos = ypos + mov;
      } else if (key == 'd') {
        xpos = xpos + mov;
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

即使您的数据由两个类表示,您仍然可以从主草图中访问该数据。这是一个较小的例子:

SELECT a.BoughtTickets, b.event_capacity, b.event_id
FROM (SELECT event_id, COUNT(*)  AS BoughtTickets 
      FROM ticket
      GROUP BY event_id) a
JOIN (SELECT  event_capacity, event_id
      FROM requested_event 
      JOIN approved_event
        ON requested_event.reservation_id = approved_event.reservation_id ) b
 ON a.event_id = b.event_id  // here

此代码使用PVector circleOne; PVector circleTwo; float circleSize = 100; void setup() { size(500, 500); circleOne = new PVector(width/2, height/2); circleTwo = new PVector(0, 0); } void draw() { background(64); circleTwo.set(mouseX, mouseY); float distance = dist(circleOne.x, circleOne.y, circleTwo.x, circleTwo.y); if (distance < circleSize) { fill(255, 0, 0); } else { fill(0, 255, 0); } ellipse(circleOne.x, circleOne.y, circleSize, circleSize); ellipse(circleTwo.x, circleTwo.y, circleSize, circleSize); } 类的两个实例来表示两个圈子,并使用circle-circle collision detection检查他们的PVectorx以检查他们是否正在触摸

您可能希望做一些非常相似的事情,只需使用您的类而不是y类。

您还可以将距离检查移到其中一个类中,这实际上是PVector所做的:

PVector