gpt4 book ai didi

java - 射出不止一颗子弹

转载 作者:行者123 更新时间:2023-11-30 03:31:26 24 4
gpt4 key购买 nike

我的角色拍摄遇到问题。当按下空格按钮时,角色会发射一颗子弹。但是,当我按空格两次时,我的角色应该会射出两颗子弹。不幸的是,我当时只有一颗子弹,当我的子弹与某物(例如墙壁)碰撞时,才会射出第二颗子弹!据我所知,ArrayList 当时只更新一个项目符号,当该项目符号被删除时,然后更新另一个项目符号。我需要如何获得双倍(甚至更多)子弹效果?

这是我的 Player 类

public class CoolGuy extends GameObject{
private ArrayList<PlayerBullet> bullets;
/*Tones of code here */
public void shoot(float delta){
if(PlayerBullet.shoot){
if(index != 0){
index++;
}
bullets.add(new PlayerBullet(full.x, full.y + sprite.getHeight()/2 - 30));
}
}
public void update(float delta) {
if(bullets.size() > 0){
if(bullets.get(index) != null){
bullets.get(index).update(delta);
}
for(GameObject t : list){
if(t instanceof Brick){
if(bullets.size() > 0 && bullets.get(index) != null && bullets.get(index).hits(t.getHitBox()) == 1){
bullets.remove(index);
}
}
}
}
}
}

这是我的 Bullet 类(class)

public class PlayerBullet extends ItemObject{
private Sprite sprite;
private Rectangle full;
public static boolean shoot;

public PlayerBullet(int x, int y){
......
......
}
public int hits(Rectangle r) {
if(full.overlaps(r)){
return 1;
}
return -1;
}
public void update(float delta) {
full.x += (delta * 500);
setPosition(full.x,full.y);
}
}

在我的主课上

player1.update(Gdx.graphics.getDeltaTime());

if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
player1.shoot(Gdx.graphics.getDeltaTime());
}

最佳答案

我不知道你的 index 参数应该是什么(你用它做的事情对我来说没有任何意义),但它确实似乎是问题。

首先,在 shoot 方法中,只有当它非零时才递增它,因此如果它为零,它将永远为零。

然后在 render 中,您仅更新单个项目符号,而不是数组中的所有项目符号。

对我来说最清晰的解决方案(尽管我再次不知道您试图使用 index 参数跟踪什么)是完全删除 index 参数。然后将 ArrayList 替换为 libgdx 的 Array 类,这样可以在循环期间快速修改和删除,并像这样更改渲染方法。

public void update(float delta) {
for (int i=bullets.size-1; i>=0; i--) { //count backward for safe removals
PlayerBullet bullet = bullets.get(i);
for(GameObject t : list){
if(t instanceof Brick){
if(bullet.hits(t.getHitBox()) == 1){
bullets.removeIndex(i);
}
}
}
}
}

关于java - 射出不止一颗子弹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com