【问题标题】:libgdx remove bullet from bullet arraylibgdx 从项目符号数组中删除项目符号
【发布时间】:2016-01-28 14:18:32
【问题描述】:

我正在创建一个 2d 游戏。我有一个子弹类数组,我用它来创建我的子弹。我还有另一个数组,它包含在屏幕上移动的精灵,每 3 到 4 秒渲染一次。

问题:

当子弹和其他精灵在同一位置相遇时,子弹应该被移除或删除并且永远不会回来。

请帮帮我...

渲染子弹的代码:

bullet.java:

import com.badlogic.gdx.math.Vector2;

public class Bullet{

public Vector2 bulletLocation = new Vector2(0, 0);
public Vector2 bulletVelocity = new Vector2(0, 0);

public Bullet(Vector2 sentLocation, Vector2 sentVelocity) {
    bulletLocation = new Vector2(sentLocation.x, sentLocation.y);
    bulletVelocity = new Vector2(sentVelocity.x, sentVelocity.y);
}

public void Update() {
    bulletLocation.x += bulletVelocity.x;
    bulletLocation.y += bulletVelocity.y;
}
}  

主类:

ArrayList<Bullet> bulletManager = new ArrayList<Bullet>();
Array<Other> OthersManager = new Array<Other>();
Bullet currentbullet;
Other currentOthers;

渲染();

int other = 0;
while (other < OthersManager.size) {
currentOthers = OthersManager.get(other);
        if (currentOthers.OtherLocation.x > guy.getX()) {
            currentOthers.OtherVelocity.x = -2f;
        }
        if (currentOthers.OtherLocation.x < guy.getX()) {
            currentOthers.OtherVelocity.x = 2f;
        }
        currentOthers.Update();
        others.setPosition(currentOthers.OtherLocation.x,currentOthers.OtherLocation.y);
        others.draw(batch);
        other++;
    }

    int counter = 0;
    while (counter < bulletManager.size()) {
        currentbullet = bulletManager.get(counter);
        currentbullet.Update();
        shoot.setPosition(currentbullet.bulletLocation.x,currentbullet.bulletLocation.y);
        if(currentOthers.OtherLocation.x == currentbullet.bulletLocation.x){
            bulletManager.remove(currentbullet);
        }
        shoot.draw(batch);
        counter++;
    }

【问题讨论】:

  • 你写过碰撞代码吗?
  • 是的。抱歉,我没有展示它。再次检查我的代码我已经添加了它

标签: java arrays libgdx sprite


【解决方案1】:

看来问题出在这段代码中:

    if(currentOthers.OtherLocation.x == currentbullet.bulletLocation.x){
        bulletManager.remove(currentbullet);
    }

我建议您使用 Vector2 类中的 epsilonEquals 方法来检查您的 currentOthers.OtherLocation 是否与 currentbullet.bulletLocation 匹配:

    if(currentOthers.OtherLocation.epsilonEquals(currentbullet.bulletLocation)){
        bulletManager.remove(currentbullet);
    }

此外,您可以将 epsilonEquals 与 float epsilon 一起使用: documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-06
    • 2023-03-12
    • 2018-12-11
    • 2014-07-02
    • 2014-10-29
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多