You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Update()移至Entity父类后失效?LibGDX对象位置更新异常

问题:父类Update移动逻辑失效,图片位置无法更新

我有三个仅图片不同的对象,它们共用相同的函数和变量,于是我把这些内容抽离到名为Entity的父类中。现在对象能正常渲染图片,但按键控制移动的Update()方法突然失效——按键检测功能正常,但图片位置完全没变化。我原本以为父类方法可以被子类直接调用,搞不懂问题出在哪。

父类Entity代码

package com.mygdx.game;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class Entity{
    public Vector2 position;
    public Sprite sprite;
    public float speed;
    public Entity(Texture img){
        sprite = new Sprite(img);
        position = new Vector2();
    }

    public void Update(float deltaTime){
        if(Gdx.input.isKeyPressed(Input.Keys.A)) position.x-=deltaTime*speed;
        if(Gdx.input.isKeyPressed(Input.Keys.D)) position.x+=deltaTime*speed;
        if(Gdx.input.isKeyPressed(Input.Keys.S)) position.y-=deltaTime*speed;
        if(Gdx.input.isKeyPressed(Input.Keys.W)) position.y+=deltaTime*speed;
    }
    public void Draw(SpriteBatch batch){
        Update(Gdx.graphics.getDeltaTime());
        sprite.setPosition(position.x, position.y);
        sprite.draw(batch);
    }
}

子类Object1代码

package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;

public class Object1 extends Entity{

    public Object1(Texture img){
        super(img);
        super.position = new Vector2(Gdx.graphics.getWidth()/10,0);
    }
}
问题原因与修复方案

核心问题

  1. 你在子类构造方法里重新创建了一个Vector2对象赋值给super.position,但父类Update方法修改的是父类构造时创建的旧Vector2实例的坐标。现在两个position是完全独立的对象:Update改的是旧对象,Draw方法给Sprite设置的是新对象的坐标,自然看不到位置变化。
  2. 成员变量speed没有赋值,默认值为0,就算修复了position的问题,移动逻辑也不会生效。

修复步骤

  1. 修改子类构造,复用父类已初始化的position对象:
    public Object1(Texture img){
        super(img);
        // 直接修改父类已创建的position的坐标,而非新建对象
        position.set(Gdx.graphics.getWidth()/10, 0);
    }
    
  2. 给speed赋值,可以选择在父类构造里设默认值,或在子类中单独赋值:
    • 父类构造加默认值:
      public Entity(Texture img){
          sprite = new Sprite(img);
          position = new Vector2();
          speed = 200; // 设置默认移动速度,单位为像素/秒
      }
      
    • 子类中赋值:
      public Object1(Texture img){
          super(img);
          position.set(Gdx.graphics.getWidth()/10, 0);
          speed = 200;
      }
      

额外优化建议

  • 把position、sprite、speed改为protected权限,遵循封装原则,避免外部直接修改成员变量。
  • 不要在Draw方法里调用Update,建议在游戏主循环(比如Screen的render方法)中统一调用所有实体的Update,再调用Draw,实现逻辑与渲染分离,代码结构更清晰。

内容的提问来源于stack exchange,提问作者Benjamin67

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:40:42