Basic Entity Game Logic in Java

Introduction: This article is for free, documented source for basic game logic in Java. This can be used for 2D or 3D games of whatever variant you would like - racing, shooter, etc - just re-arrange how the procedures are handled and the variables named. Health: For the health of a car/player/entity, we first create the variable as an integer - full number, to hold the current health...
  1. private int health;
We set it to private so that only the containing - entity - class can see/use it. We can then set it's default value to 100 (full health) on the constructor so that once a new entity is created, they have a default health of 100...
  1. public Main() {
  2.         this.health = 100;
  3. }
Another thing we can do is create a simple method to update the health of the player, and make it restore over time. The entities tick method would automatically invoke this new method so that it is ran every tick of the game...
  1. public void updateHealth() {
  2.         if (this.health < 101) {
  3.                 this.health += 1;
  4.         }
  5. }
This will ensure that the entities health restores by one each time the method is ran, unless it is already at the maximum of full health, 100. Username: A highly used feature within a game is a customisable username. We are going to use basic System.in, console, input for this example. So first we would create a variable to hold the entities username, just like the health except it needs to be a string...
  1. private String username;
We can create a method to select a new username...
  1. public void updateUsername() {
  2.         Scanner scanner = new Scanner(System.in);
  3.         System.out.println("Enter a new username...\n"); //'\n' for a new line.
  4.         this.username = scanner.next();
  5. }
First we create a scanner of System.in (java console user input), then we read the next full token (next work) and set it as the new username. Retreiving Methods: Finally we can write methods to retrieve the value of the variables. This is good because it means we are not directly accessing the variables - they're private anyway, from other classes such as the main game logic class, rendering class or others...
  1. public int getHealth() {
  2.         return this.health;
  3. }
  4.        
  5. public String getUsername() {
  6.         return this.username;
  7. }
Please note that we set the method return types appropriately so they are able to return the correct data, int/integer for health. And, string/varchar for username.

Add new comment