重叠方法不起作用

时间:2013-12-20 14:03:15

标签: java android libgdx

我正在使用libGDX创建一个类似曲线发烧的游戏,但对于Android 实际上我正在研究碰撞,但我尝试的一切都行不通;我使用overlaps类中的Rectangle方法 它总是返回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;
    }
}

1 个答案:

答案 0 :(得分:0)

您没有更新边界。在更新方法中,设置位置后,也要更新边界。像 -

这样的东西
bounds.x = position.x;
bounds.y = position.y;
bounds.x -= bounds.width / 2f;
bounds.y -= bounds.height / 2f;