This site requires JavaScript, please enable it in your browser!
Greenfoot back
Sloppybobby3
Sloppybobby3 wrote ...

2024/2/15

Damage Enemy (Edit variables in enemy class from hero class)

Sloppybobby3 Sloppybobby3

2024/2/15

#
I'm trying to make my player do damage to an enemy, but I cannot seem to figure out how to edit variables across classes. It compiles with no syntax errors, but does not appear to make any changes to the variable. Here is the related code of both the enemy and player class. Any help would be appreciated. Enemy:
public int enemyHealth = 2;
  
    public void act()
    {
       if(enemyHealth == 0)
       {
           die();
       }
    }
   
    public void die()
    {
      getWorld().removeObject(this);
    } 
Player:
 public void enemyDamage()
    {
        if(isTouching(enemy.class) && (getImage() == atkRight || getImage() == atkLeft))
        {
            enemy Enemy = (enemy) getOneIntersectingObject(enemy.class);   
            Enemy.enemyHealth -= 1;
        }
    }
I have a small animation, just by changing the image, which is why there is that && in the if statement for the player, to make sure it is in the attack.
danpost danpost

2024/2/16

#
Sloppybobby3 wrote...
I'm trying to make my player do damage to an enemy, but I cannot seem to figure out how to edit variables across classes. It compiles with no syntax errors, but does not appear to make any changes to the variable. << Codes Omitted >>
Try something like this in the Player class:
public void enemyDamage() {
    if ( ! getImage().toString().contains("atk")) return;
    enemy Enemy = (enemy) getOneIntersectingObject(enemy.class);
    if (Enemy != null) Enemy.enemyHealth--;
}
You need to login to post a reply.