This may not be entirely correct in the way someone with more experience than I would do it, but I got it to work.
Here’s what I did in my Player class:
public void update() {
int xa = 0, ya = 0;
if (anim < 7500) {
anim++;
} else {
anim = 0;
}
if (input.up) ya--;
if (input.down) ya++;
if (input.left) xa--;
if (input.right) xa++;
if (input.run && input.right) {
if (hasStamina()) {
xa = xa + 1;
changeStamina(1);
}
}
if (input.run && input.left) {
if (hasStamina()) {
xa = xa - 1;
changeStamina(1);
}
}
if (input.run && input.up) {
if (hasStamina()) {
ya = ya - 1;
changeStamina(1);
}
}
if (input.run && input.down) {
if (hasStamina()) {
ya = ya + 1;
changeStamina(1);
}
}
if (xa != 0 || ya != 0) {
move(xa, ya);
walking = true;
} else {
walking = false;
}
}
public int getStamina() {
return stamina;
}
private boolean hasStamina() {
if (stamina > 0) {
return true;
} else {
return false;
}
}
public void changeStamina(int changeAmt) {
stamina -= changeAmt;
System.out.println(stamina);
}
and in my main Game class I added a few lines to my run() method: To get it to update once every frame was rendered I figured it would need to be called from here so I initialized a new regenTimer and had it add to the stamina every half second in increments of 2. I bolded the lines that got the program working correctly for me.
public void run() {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
long regenTimer = System.currentTimeMillis(); //The new regenTimer I initialized
final double ns = 1000000000.0 / 60.0;
double delta = 0;
int frames = 0;
int updates = 0;
requestFocus();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
update();
updates++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
frame.setTitle(title + " | " + updates + " ups, " + frames + " fps");
frames = 0;
updates = 0;
}
//Added this part for the regeneration of Stamina
if (System.currentTimeMillis() - regenTimer > 500) {
regenTimer += 500;
if (player.getStamina() < 100) {
player.changeStamina(-2);
}
}
}
stop();
}
This might not be the best way for this, but I got it working, so I’m glad for that. What would be a better method to do this?