0

我目前正在使用名为 libgdx 的框架学习游戏编程。它允许用户制作可以在桌面上的 Java 虚拟机和 Android 手机上轻松运行的程序。我正在尝试制作一个基本程序,它将在屏幕上显示一个字符并允许我用键盘来回移动它。我创建了 3 个类 - 一个名为Assets,它将文件加载到内存中并将它们转换为纹理和动画,一个名为InputHandler,它通过更改动画、移动方向等来响应键输入,还有一个名为FightView,它本质上是所有渲染完成。使用典型的命令InputHandler从类中调用。for 的构造函数如下所示:FightViewinput = new InputHandler(anim, frame);InputHandler

public InputHandler(Animation animation, TextureRegion region){

    Assets.load();  //loads textures from files into memory and creates animations from them
    animation = Assets.playStance;  //set initial animation to be used
    region = animation.getKeyFrame(0, true);    //make TextureRegion equal to first frame in animation

}

现在,我想要发生的只是将传递给构造函数的 Animation 和 TextureRegion 设置为上面引用的值,这样,例如,如果我要在声明后regionFightView类中提到input,它将被设置为animation.getKeyFrame(0, true);. 根据我对 Java 的有限经验,我认为这是应该发生的,但在编译时我得到一个 NullPointerException,指向下面代码中的第二行:

    input = new InputHandler(anim, frame);
    x = centreX - (frame.getRegionWidth() / 2);

显然,frame即使在通过构造函数传递之后,它仍然是 null,它(可以在构造函数的第三行中看到)应该为它分配一个值。请注意,在传递给构造函数之前,它们实际上都是 null - 我正在尝试创建一个类,该类将提供字段数据,而无需在FightView类中这样做。

任何帮助表示赞赏。这可能是错误的方法——我想做的是创建一个对象,在初始化时,它将加载AnimationandTextureRegion数据。

4

1 回答 1

1

您遇到的问题是由于对基本 Java 概念的误解。Java 通过值而不是引用传递参数。你写的东西永远不会像你期望的那样工作。

首先,我建议您解决一个更简单的问题,或者顺便加强一些基本的 Java 概念和对象概念。

其次,这里有一个简短的答案来实现你想要的。

将成员添加到 InputHandler 类以保存 Animation 和 TextureRegion。在构造函数(不带参数)中,您将像您所做的那样分配值,除非您将它们分配给成员变量。

class InputHandler {

    public Animation animation;
    public TextureRegion region;

    public InputHandler() {

        Assets.load();  //loads textures from files into memory and creates animations from them
        animation = Assets.playStance;  //set initial animation to be used
        region = animation.getKeyFrame(0, true);    //make TextureRegion equal to first frame in animation

    }
}

After constructing the InputHandler you could reference it's members (frame in this case) and see your correct values.

input = new InputHandler();
x = centreX - (input.frame.getRegionWidth() / 2);
于 2011-07-27T23:38:14.937 回答