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

2018/2/21

How to make one object be affected by another object's variable

Farfnir Farfnir

2018/2/21

#
So, I have a game where there are many different cards. Each one uses the same class, and I want the attack value of one card to affect the health of the one it is touching, how do I go about this?
danpost danpost

2018/2/21

#
If you had a 'takeDamage' method in the class that uses an int parameter for the amount of damage to take, you could just call that method on the other card. You might also need a boolean, maybe called 'dealtDamage' to track whether the card has given damage yet on any particular turn (set to 'false' at beginning of turn, or when the ability for the card to deal damage becomes possible, and set to 'true' when damage is dealt out; only deal damage when 'false'.
jimboweb jimboweb

2018/2/24

#
If you want cards touching to affect each other, you can use getOneIntersectingObject or getIntersectingObjects. Using getOneIntersectingObject you can do something like this: The card would have a changeHealth method like:
    public void changeHealth(int amount){
        health += amount;
    }
Then you could do something like this:
Card intersectingCard = (Card)getOneIntersectingObject();
if(intersectingCard != null){
     int changeHealthAmount;
    //changeHealthAmount = whatever code figures out how to change the health
    intersectingCard.changeHealth(changeHealthAmount);
}
If you might be intersecting more than one card you could change it to:
      for(Actor cardActor:getIntersectingObjects(Card.class)){
          Card card = (Card)cardActor;
          int changeHealthAmount;
          //code to set changeHealthAmount to what it should be
          card.changeHealth(changeHealthAmount);
      }
Yehuda Yehuda

2018/2/25

#
You cannot leave the parentheses in the getOneIntersectingObject method blank, you have to specify a class (Card.class).
You need to login to post a reply.