2014-02-18 81 views
2

我想爲Android設備製作一個小遊戲。 所有的作品...除了與玩家和對象的碰撞。我做錯什麼了嗎?我已經嘗試了很多檢查碰撞的方法。例如,相交,相交,包含和自我碰撞測試的功能。Android Rect碰撞

編輯:我的問題是,什麼也沒發生:)

所有的
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); 
    int width = metrics.widthPixels; 
    int height = metrics.heightPixels; 

    private Bitmap player, enemy; 
    private int speedrun=1, x= 0, y = height - height/5, i=1, yg=height - height/5 + 40, xe= 920, xp =width/2 - width/4; 
    private Rect p, e; 
    public static int speed=0; 

//other code 

@Override 
    protected void onDraw(Canvas c) 
    { 
     c.drawColor(Color.CYAN); 
     handelPlayer(); 
     p = new Rect(xp, y, 0, 0); 
     wayrect = new Rect(x, yg, 0, 0); 
     wayrect2 = new Rect(x + width, yg, 0, 0); 
     e = new Rect(xe, yg - 250, 0, 0); 
     c.drawBitmap(enemy, e.left, e.top, null); 
     c.drawBitmap(player, p.left, p.top, null); 
    } 

    public void handelPlayer() 
    { 
     x -= speed*speedrun; 
     xe -= speed*speedrun; 
     if (x + width < 0) 
      x = 0; 
     if (xe < -100) 
      xe = 920; 
     if (MainActivity.touch == 1) 
     { 
      y -= 100;//jump 
      MainActivity.touch = 0; 
      i = 1; 
     } 
     if (y <= height - height/5) 
      y += 3 * i/10; //gravity 
     i++; 

     if (p.intersect(e)) //collosision 
      speedrun = 0; 
    } 
+0

出了什麼問題? –

+0

嘗試將'p.intersect(e)'改爲'Rect.intersects(p,e)'。 'intersect'會改變矩形'p'到交叉點,而'Rect.intersects(Rect a,Rect b)'只是一個測試,我認爲你正在尋找。 –

+0

記得如果你覺得它有用,就可以對你接受的答案進行投票表決;) – Agostino

回答

1

首先,你的矩形從您的播放器位圖的頂部進入(0,0),您的設備的左上角。我想象你的意思是:p = new Rect(xp, y, xp + player.getWidth(), y + player.getHeight());e一樣,見下面的代碼。

二,p.intersect(e)如果它們相交,則將矩形p更改爲十字路口,因此應該使用Rect.intersects(p, e)來代替。

第三,您檢查舊位置值的碰撞,因爲您在更改位置後沒有更新矩形。

速戰速決可能是交集測試移動到handelPlayer的頂部(小注:handlePlayer將是正確的方式來拼寫),像這樣:

protected void onDraw(Canvas c) 
{ 
    c.drawColor(Color.CYAN); 
    handelPlayer(); 
    p = new Rect(xp, y, xp + player.getWidth(), y + player.getHeight());; 
    wayrect = new Rect(x, yg, 0, 0); // These rectangles also has their right bottom corner at (0,0), which might cause problems 
    wayrect2 = new Rect(x + width, yg, 0, 0); 
    e = new Rect(xe, yg - 250, xe + enemy.getWidth(), yg - 250 + enemy.getHeight()) ; 
    c.drawBitmap(enemy, e.left, e.top, null); 
    c.drawBitmap(player, p.left, p.top, null); 
} 


public void handelPlayer() 
{ 
    if (Rect.intersects(p, e)){ //collision 
     speedrun = 0; 
    } 

    x -= speed*speedrun; 
    xe -= speed*speedrun; 
    if (x + width < 0) 
     x = 0; 
    if (xe < -100) 
     xe = 920; 
    if (MainActivity.touch == 1) 
    { 
     y -= 100;//jump 
     MainActivity.touch = 0; 
     i = 1; 
    } 
    if (y <= height - height/5) 
     y += 3 * i/10; //gravity 
    i++; 


} 

有可能是另一個問題,但,因爲你還沒有描述到底發生了什麼。

+0

我試過固定版本,但是沒有修復它!我的問題是,沒有任何事情發生......所以碰撞測試總是回覆! – lolxdfly

+0

問題是什麼?發生了什麼/沒有發生? –

+0

nothig發生:)玩家不會停止,如果他碰撞其他紋理! – lolxdfly