Home > Software design >  How do you get a value of a variable of an other object of the same class?
How do you get a value of a variable of an other object of the same class?

Time:10-29

I'm working on a little game to learn java. Currently I created a Sphere, a Player and a Game class ( Main class to run). I want the shpere to know, whether it collides with the player or not.

First thing I tried was the Get and Set thing, but the problem is, that I have to create a Player-Object in the Sphere-class to acces the Get-Method of the Players Position.

As it's a new object, it's not the same as the Object in my Game-Class, so it doesn't change when moving.

CodePudding user response:

Think who is the responsibility to check for collision. It can be confusing but logically you need a Game class where you will have access to both Player and a Sphere objects. There you can have update method (which is executed in some time frame in a loop) and there you can check the positions of the two objects if they collide. So this mean that the positions must be kept inside in Player for player object and in Sphere for Sphere object.

CodePudding user response:

add a reference to the player object to the sphere object

class Main {
  public static void main(String[] args) {
    Player player = new Player();
    Sphere sphere = new Sphere();
    sphere.setPlayer(player);

    Game game = new Game(player, sphere);
    game.start();
  }
} 

Inside the sphere object you can now access the players position using the reference

  • Related