简体   繁体   中英

Java nullpointerexception for a 2D scrolling game

I'm making a game, its 2D side scrolling, kinda like terraria. In my game, i have offsets, XOff and YOff , and those move the terrain. I also have a method for my character, move() , and all that does is this:

public void move() {
        if (!ableToMove) //makes sure you can move
            return;
        // x += moveX; these 2 methods work, but x and y are just my player coords.
        // y += moveY;
        core.setYOff(1); //core is my main class, where the global variables are stored
    }

the comments label and describe each variable. so, setYOff(1) sets the YOff like so:

private void setYOff(int i){
     YOff += i;
}

Now, there is only one way that i am accessing the move method. in a thread, called PlayerThread , i have a constant call to the move() and another method called applyGravity() , which doesnt really have a relevance to this question. That is in the PlayerThread .

Now here is the problem i'm having... When I call the setYOff() , I'm getting the following error:

Exception in thread "player Thread" java.lang.NullPointerException
    at main.Player.move(Player.java:33)
    at main.PlayerThread.run(PlayerThread.java:24)
    at java.lang.Thread.run(Unknown Source)

which is telling me that when i'm calling the setYOff() method in my move() method, it doesnt work. I've tried just testing and moving the call to set the Y offset into the thread itself, and it gives the same error... I then tried to move it to the RefreshThread , and interestingly it did work... it moved the entire map down 1 pixel every 20 milliseconds... and i have no clue why! what is wrong with my move method that makes this not work, or better yet, my PlayerThread , that isnt making this work in the long run? What is different about my RefreshThread ? If you guys need the entire code for everything involving the calls, creation, and such of each thread, i can provide that, but i'm not sure you would need that... What do i need to do differently? Thanks in advance!

EDIT: I tried, in my PlayerThread just commenting out the move() call, and just having it adjust the y offset, and it worked! so it has to do with the move method, but again, why?

CORRECTION TO PREVIOUS EDIT: so testing more, i put the move() call back into the thread, and kept the setYOff(1) in it, and it still worked, but again not from within the move method itself...

The NullPointerException indicates that the object on which the method is being called is Null , in this case, the core object. Fix that and the problem should go away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM