问题描述
所以我在Processing上做游戏,我似乎无法找到如何使if语句成为条件。当我的圈子碰到一个障碍时,这种情况应该会减少生命。我有这个主意,但我只是不能将其放入代码中,请帮助我。条件为“ if”,其后为完整游戏代码。
void difficulty()
{
if(/*what do i write here*/){
lives--;
}
else{
fill(0,255,0);
}
}
////////主要游戏代码从此处开始////////
int score;
int score1;
int miss;
int lives=10;
int ballx,bally;
class Rect
{
float x;
float y;
float speed;
float leng;
color c;
boolean valid;
final int MAX_COLOR = 255;
final int MIN_X = 50,MAX_X = 750;
final int MIN_Y = -800,MAX_Y = -100;
int MIN_SPEED = 1,MAX_SPEED = 2;
final int MIN_Leng = 50,MAX_Leng =100 ;
Rect()
{
initAll();
}
void initAll() {
valid = true;
c = color(random(255),random(255),random(255));
x = random(MIN_X,MAX_X);
y = random(MIN_Y,MAX_Y);
speed = random(MIN_SPEED,MAX_SPEED);
leng = random(MIN_Leng,MAX_Leng);
}
void update() {
if (!valid) {
initAll();
return;
}
move();
draw_rect();
}
void draw_rect()
{
fill(c);
rect (x,y,leng,leng);
}
void move()
{
if (y-leng <= height)
{
y += speed;
} else if (y-leng > height )
{
valid = false;
miss++;
}
}
void difficulty()
{
if(){
lives--;
}
else{
fill(0,0);
}
}
void GameOver()
{
if (lives==0)
{
for (int i = 0; i < Obj.length; i++)
{
Obj[i] = new Rect();
}
background(0);
textSize(50 );
fill(255);
text( "You Lose ",15,150);
text( "score: " + score,100);
}
}
boolean isOver(int mx,int my) {
float disX = x - mx;
float disY = y - my;
if (sqrt(sq(disX) + sq(disY)) < leng/2 ) {
return true;
} else {
return false;
}
}
}
Rect [] Obj = new Rect [10];
void setup() {
size (400,600);
ballx=200;
bally=300;
for (int i = 0; i < Obj.length; i++)
{
Obj[i] = new Rect();
}
}
void draw() {
background(0);
textSize(50);
text( "score: " + score,100);
text("Lives: " + lives,50);
ellipse(ballx,bally,20,20);
for (int i = 0; i < Obj.length; i++) {
Obj[i].update();
Obj[i].difficulty();
Obj[i].GameOver();
}
surface.setTitle(nf(frameRate,3,2));
}
void keypressed(){
for(Rect s : Obj){
if ( key =='q' ){
ballx=ballx-2;
score++;
score1++;
s.valid = false;
break;
}
if ( key =='e'){
ballx=ballx+2;
score++;
score1++;
s.valid = false;
break;
}
}
}
解决方法
您要做的是检查播放器是否与任何矩形发生碰撞。
考虑一下,玩家与矩形碰撞意味着什么?
这意味着播放器的x位置必须大于左侧的x位置,但小于矩形右侧的x位置。 y位置也是如此。
由于需要检查所有所有矩形的位置,因此应使用for或foreach循环。
您现在可以按照我之前说的做,它可以正常工作,但是您还应该考虑播放器本身的大小。如果玩家的矩形的左侧/右侧(而不是矩形)与矩形发生碰撞,则玩家仍应与矩形发生碰撞。 从技术上讲,播放器是一个圆形,但为简化起见,我们将其近似为矩形。
boolean isColliding = false;
for(Rect r : Obj)
{
if (ballx + 10 > r.x && //is the right side of the ball further right than the left side of the rectangle?
ballx - 10 < r.x + r.leng && //is the left side of the ball further left than the right side of the rectangle?
//if both of the above are true,the balls x-position is between the left and right side of the ball
bally + 10 > r.y && //is the bottom of the ball further down than the top of the rectangle?
bally - 10 < r.y + r.leng) { //is the top of the ball further up than the bottom of the rectangle?
isColliding = true; //if all of the above are true,the ball is colliding with the rectangle
}
}
if (isColliding) {
lives--;
} else {
fill(0,255,0);
}