我正在處理2D Processing 2.2.1遊戲中的碰撞檢測。基本上我所做的是編寫一個類,它通過定義其端點的座標來創建一個盒子,並且有一個方法來檢查這些盒子中的兩個是否重疊。我通過引入布爾值來實現這一點,只要這些框中的兩個重疊,該布爾值就設置爲true。然後基本上實現一個創建這些框的get方法,我遇到了返回類型錯誤的結果。它表示該方法未返回正確類型的Box1。我真的不明白,因爲我回來的盒子確實適合構造函數。我非常肯定,這是因爲碰撞對象在一個數組中,隨着時間的推移會產生越來越多的對象,但我很遺憾不知道如何改變我的對撞機(Box1)類。在方法中返回類型錯誤的結果
這裏是代碼即時得到的錯誤:
//returning collider info
public Box1 getBox1() {
for (int i =frameCount/600; i >0; i--) {
return new Box1(block[i].x - Blockpic.width/2, block[i].y-Blockpic.height/2, block[i].x+Blockpic.height/2, block[i].y+Blockpic.height/2);
}
}
這是我對撞機(BOX1)類:
public class Box1 {
float x1, x2;
float y1, y2;
Box1(float x1, float y1, float x2, float y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
boolean isOverlap(Box1 b) {
if (((x1 <= b.x1 && b.x1 <= x2) || (x1 <= b.x2 && b.x2 <= x2))
&& ((y1 <= b.y1 && b.y1 <= y2) || (y1 <= b.y2 && b.y2 <= y2))) {
return true;
}
return false;
}
}
只是完整信息我的產卵對象類(錯誤所在的位置):
public class Blockfield {
private int Blockcount;
private PImage Blockpic;
private Block block[];
//Constructor
public Blockfield (int Blockcount) {
this.Blockcount = Blockcount;
Blockpic = loadImage("block2.png");
//new array
block = new Block [Blockcount];
for (int i=0; i < Blockcount; i++) {
block[i] = new Block(width+Blockpic.width, random (height),7);
}
}
//Draw method for this class
public void draw() {
for (int i =frameCount/600; i >0; i--) {
pushMatrix();
translate (block[i].x,block[i].y);
image (Blockpic, block[i].x, block[i].y);
popMatrix();
}
}
public void update() {
for (int i =frameCount/600; i >0; i--) {
//moves blocks right to left
block[i].x -=(6 * (frameCount/200));
//spawns block when they leave the screen
if (block[i].x < 0 - Blockpic.width) {
block[i] = new Block(width+Blockpic.width, random (height),7);
}
}
}
//returning collider info
public Box1 getBox1() {
for (int i =frameCount/600; i >0; i--) {
return new Box1(block[i].x - Blockpic.width/2, block[i].y-Blockpic.height/2, block[i].x+Blockpic.height/2, block[i].y+Blockpic.height/2);
}
}
}
class Block {
float x, y;
int speed;
Block (float x, float y, int speed) {
this.x= x;
this.y= y;
this.speed = speed;
}
}
非常感謝!
嗨,我想這是有道理的,但它爲什麼會告訴我,返回類型是不正確的?那麼它會不會是一個Nullpointer異常?此外,遵循該邏輯,只需將framecount定義爲正數(i = 0 + frameCount/600)即可解決問題。另外我怎麼沒有遇到我以前的方法中的錯誤?非常感謝你的回答和你的時間,但可悲的是,這並沒有讓我更接近實際解決我的問題.... –
@MariusHumphrey我已經編輯我的帖子來回答你的新問題。如果您仍不清楚,請提供我們可以使用的[MCVE](http://stackoverflow.com/help/mcve)。 –
嗨,對不起,我正在旅行,所以我無法回到你身邊。感謝您的幫助,我現在明白了什麼是錯的。我剛剛結束了對碰撞使用更簡單的類。再一次感謝你的幫助! –