0
\$\begingroup\$

I've had formal education in Java for around half a year now, and as a hobby I would like to attempt game development. I've downloaded the Slick2d library to help with this.

I've run into a problem as of right now. When I create my game objects, like player, etc. I presume I have to do this in the pre-build init() method, but I probably could do it in the main() as well (What one would you suggest?). Now, my question is, when I create a Player instance in init() or main(), how do I pass it to the update() method? I could of course make the player object public/global, but I've been taught that this is very poor programming, so I'm reluctant to do this.

I would greatly appreciate an answer, since I would like to learn to do things the "correct" way, and as of right now I have no single clue what that is. Thanks for your consideration.

\$\endgroup\$
1
\$\begingroup\$

As long as all of your mentioned methods are in the same class, you do not need to pass your objects to the methods - if you just declare your objects in that class. That is the normal way to do it.

This is not the same as declaring the variables "public". You can do that, if you want. But without declaring this explicitely, variables are set to "private" in java, thus restricted to the scope of their class. So just go ahead an declare your player object at the start of your class.

Where you initialize the objects is a different question. Usually, the init() method in frameworks is called ONCE before the game goes into its loop. As you probably would want to initialize your objects once, you can do that in this method. You can also create your own initialization method that only initializes some of your game's objects.

public static void main(String args[]){} is the method that is the starting point for any java-program IIRC. You can only initialize static or local variables here, though. But you cann call your init()-method from here and start the game loop.

public class Game{

 private Player p1;

 public static void main(String args[]) {
   init();
   //alternative: initializePlayer();
   //gameloop
 }

 public void init(){
     p1 = new Player();
 }

 /*private void initializePlayer(){
     p1 = new Player();
 }*/

 public void update(){
    p1.update();
 }

}

\$\endgroup\$
0
\$\begingroup\$

Simply - you shouldn't!

The good way is to make some class to keep objects to be updated, or simply keep them in public array or list and then do something with it in your update method.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.