【问题标题】:Why is my Body returning null?为什么我的身体返回 null?
【发布时间】:2012-06-21 06:01:22
【问题描述】:

我正在使用 AndEngine 为 Android 平台制作游戏。我需要检测圆形物体是否与圆形精灵接触。为此,我正在计算两者的中心和半径,并使用 pythag 来确定它们是否确实接触。但是,当我尝试获取身体的 x 坐标时,我不断收到 nullpointerexception。每次触摸屏幕并创建精灵时, spriteNum 都会增加。任何想法为什么?我的代码:

public class grow implements Runnable{
    Sprite sp;
    Body body[] = new Body[100];
    public grow(Sprite sprite){
        sp = sprite;
    }
    @Override
    public void run() {
        float radf, rads; //fill radius/stationary radius
        float[] fill; //fillx/stationaryx
        float fx=0, fy=0, sx, sy;

        while(down){
            //Log.e("Tag","Running thread. Down = "+Boolean.toString(down));
             yourSprite[spriteNum].setScale(scale += 0.1);
             fill = yourSprite[spriteNum].getSceneCenterCoordinates();
             fill[0]=fx;
             fill[1]=fy;
             radf=yourSprite[spriteNum].getHeightScaled()/2;    

             Log.e("Fill X before for",Float.toString(fx));

            if(spriteNum>0)
                for(int x=0;x<spriteNum;x++){               
                    rads=yourSprite[x].getHeightScaled()/2;
                    sx = body[x].getWorldCenter().x; //Null pointer exception
                    sy = body[x].getWorldCenter().y;

                    if(Math.sqrt(Math.pow((fx-sx),2)+Math.pow((fy-sy),2))<(radf+rads))
                            down = false;
                    Log.e("Fill x",Float.toString(fx));
                    Log.e("Stat x",Float.toString(sy));
                }
             try {
                Thread.sleep(75);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        body[spriteNum] = PhysicsFactory.createCircleBody(mPhysicsWorld, yourSprite[spriteNum], BodyType.DynamicBody, FIXTURE_DEF);
        mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(yourSprite[spriteNum], body[spriteNum], true, true));
        if(body[0]!=null)
            Log.e("Body created","not null"); //This says it's not null, but when I did the same thing just inside of my for() loop and it did say it was null
    }

【问题讨论】:

    标签: android nullpointerexception andengine


    【解决方案1】:

    我猜这是因为你已经初始化了 body 数组 Body body[] = new Body[100] 但不是其中的单个 Body 元素。因此,当您访问 body[x] 时,它会返回 null。您还应该初始化数组中的正文元素。比如:

    for(int i=0; i<body.length; i++) {
       // probably some cod here..
       body[i] = new Body(..);
       // probably some cod here..
    }
    

    我想到你的问题的另一个原因是,你说:

    spriteNum 每次触摸屏幕时都会增加 创建的。

    所以有可能你在启动时初始化了一些 body 元素,然后当 sprite 计数增加时,你不会在 body 数组中创建新元素,所以当你尝试 body[0] 它不是 null 而是对于新的 sprite body 元素可能没有被初始化,你会得到 null,因此是 NPE。

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多