LibGDX实现敌人延迟射击及解决子弹不显示问题求助
问题描述
在LibGDX开发中,实现敌人向玩家发射直线飞行子弹的功能,但子弹未在PlayState中显示。以下是Ghost类代码:
public class Ghost { private Texture topGhost, bottomGhost; private Vector2 postopGhost; private Vector2 posBotGhost; private Random rand; private static final int fluct = 130; private int GhostGap; public int lowopening; public static int width; private Texture bullet; private Vector2 bulletpos; private Vector2 botbulletpos; public Ghost(float x) { GhostGap = 120; // the gap between the top and bottom ghost lowopening = 90; // bullet = new Texture("Bird.png"); topGhost = new Texture("Bird.png"); // middletude = new Texture("sipkemiddle.png"); //spelling mistake bottomGhost = new Texture("Bird.png"); rand = new Random(); width = topGhost.getWidth(); posBotGhost = new Vector2(x + 120, rand.nextInt(fluct)); postopGhost = new Vector2(x + 113, posBotGhost.y + bottomGhost.getHeight() + GhostGap - 50); bulletpos = new Vector2(postopGhost); botbulletpos = new Vector2(posBotGhost); } public void repostition(float x) { postopGhost.set(x + 75, rand.nextInt(fluct) + 200); posBotGhost.set(x + 75, postopGhost.y + GhostGap - bottomGhost.getHeight() - 247); } public void timer(float dt) { int ticker = 0; ticker += dt; if(ticker > 5) { ticker = 0; shoot(); } } public void shoot(){ setBulletpos(postopGhost); bulletpos.x = (bulletpos.x + 40); bulletpos. y = bulletpos.y; } }
目前无法生成可见的沿X轴移动的子弹,寻求解决建议。
解决建议
修正计时器变量作用域:
timer方法内的ticker是局部变量,每次调用都会重置为0,永远触发不了射击逻辑。将ticker改为Ghost类的成员变量,且用float类型存储时间累计:private float ticker = 0; public void timer(float dt) { ticker += dt; if(ticker > 5) { ticker = 0; shoot(); } }重构子弹管理逻辑:当前
shoot方法每次都会把同一颗子弹拉回幽灵位置再移动,无法生成多颗子弹。改为维护一个子弹列表,每次射击创建新的子弹实例:private List<Vector2> bullets = new ArrayList<>(); public void shoot(){ // 从幽灵位置生成新子弹 bullets.add(new Vector2(postopGhost.x, postopGhost.y)); }同时新增更新方法处理子弹移动与回收:
public void update(float dt){ Iterator<Vector2> iterator = bullets.iterator(); while(iterator.hasNext()){ Vector2 bullet = iterator.next(); // 按时间比例移动,保证帧率无关 bullet.x -= 40 * dt; // 移除超出屏幕的子弹,避免内存泄漏 if(bullet.x < -bullet.getWidth()){ iterator.remove(); } } }确保子弹在PlayState中被渲染:在PlayState的
render方法里,遍历Ghost的子弹列表绘制每一颗子弹:// 假设已有ghost实例和SpriteBatch batch for(Vector2 bulletPos : ghost.getBullets()){ batch.draw(ghost.getBulletTexture(), bulletPos.x, bulletPos.y); }给Ghost类添加对应获取方法:
public List<Vector2> getBullets(){ return bullets; } public Texture getBulletTexture(){ return bullet; }检查子弹移动方向:如果玩家在幽灵左侧,当前代码
bulletpos.x +=40是向右移动,会导致子弹飞离玩家方向,应改为bullet.x -= 速度值。验证纹理加载:确认
Bird.png路径正确,可在Ghost构造方法中打印System.out.println(bullet != null)验证纹理是否成功加载。
内容的提问来源于stack exchange,提问作者banabrain
相关产品推荐
相关产品推荐

