2013-12-20 29 views
0

我正在使用libGDX創建一個像曲線發燒但適用於Android的遊戲。
其實我正在研究碰撞,但我嘗試的一切都不行;我使用Rectangle類的overlaps方法。
它總是返回false重疊方法不起作用

這裏是用來檢查是否有衝突的代碼:

public void collision() { 
    if(head.getAlive()) { 
     for (TailSnake tail : getTail()) { 
      if (tail.lifeTime > 2) 
       if (head.bounds.overlaps(tail.bounds)) 
        head.dead(); 
     } 
     for (Object wallObj : getWall()) { 
      Wall wall = (Wall) wallObj; 
      if (head.bounds.overlaps(wall.bounds)) 
       head.dead(); 
     } 
    } 
} 

的TailSnake代碼:

package com.me.mygdxgame; 

import com.badlogic.gdx.math.Rectangle; 
import com.badlogic.gdx.math.Vector2; 

public class TailSnake { 

    static final float SIZE = 0.1f; 

    Vector2 position = new Vector2(); 
    Rectangle bounds = new Rectangle(); 
    float lifeTime = 0; 

    public TailSnake(Vector2 position) { 
     this.position = position; 
     this.bounds.height = SIZE; 
     this.bounds.width = SIZE; 
    } 

    public Rectangle getBounds() { 
     return bounds; 
    } 

    public Vector2 getPosition() { 
     return position; 
    } 

    public void update(float delta) { 
     lifeTime += delta; 
    } 
} 

最後HeadSnake的代碼:

package com.me.mygdxgame; 

import com.badlogic.gdx.math.Rectangle; 
import com.badlogic.gdx.math.Vector2; 

public class HeadSnake extends TailSnake{ 

    static final float SPEED = 1f; 
    static final double ROTATE_SPEED = 200; 

    Rectangle bounds = new Rectangle(); 
    Vector2 velocity = new Vector2(); 
    boolean alive = true; 

    public HeadSnake(Vector2 position) { 
     super(position); 
     this.velocity.x = 0; 
     this.velocity.y = SPEED; 
    } 

    public Vector2 getVelocity() { 
     return velocity; 
    } 

    public boolean getAlive() { 
     return alive; 
    } 

    public void update(float delta) { 
     if (alive) 
      position.add(velocity.cpy().scl(delta));   
    } 

    public void dead() { 
     this.alive = false; 
    } 
} 

回答

0

你沒有更新邊界。在你的更新方法中,設置好位置後,也要更新邊界。類似的東西 -

bounds.x = position.x; 
bounds.y = position.y; 
bounds.x -= bounds.width/2f; 
bounds.y -= bounds.height/2f; 
+0

非常感謝。我不知道爲什麼我沒有想到這一點。 – Poroing

+0

@ user2984573我很樂意提供幫助。 :) –