Reputation: 98
Basically I'm making a game where I need to add health to characters. When the player hits the spider's hit box, I want the health to change and my frame to repaint. I feel like I'm doing it right. Here is my code:
Frame.java
:
public static int redHealth;
public static int blueHealth;
public static void getBlueHealth(int health) {
health = redHealth;
}
public static void getRedHealth(int health) {
health = blueHealth;
}
// Create health labels
public static JLabel redHealthLabel = new JLabel("Health: " + redHealth);
public static JLabel blueHealthLabel = new JLabel("Health: " + blueHealth);
Key.java
:
if (Frame.spiderObj.intersects(Frame.blueCharacterObj)) {
System.out.println("hit spider");
Frame.getBlueHealth(97);
Frame.frame.repaint();
System.out.println(Frame.redHealth + "" + Frame.blueHealth);
}
As you can see, I'm passing 97
as a parameter into the getRedHealth()
and getBlueHealth()
methods, which is then set to equal redHealth
and blueHealth
. However when I run my game and hit the spider, it prints out hit spider
but does not update the health.
Any help???
Upvotes: 0
Views: 77
Reputation: 29266
Your big problem is that you are trying to "pass by reference" to populate health
rather than actually returning it.
Should be:
public static int getBlueHealth() {
return blueHealth;
}
Also: you probably don't need a getter since bluehealth is already public static
.
Even if you could pass by reference, calling it with a constant would fail. Not clear from your calling code whether you want getters or setters.
Upvotes: 1