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

2019/6/21

Need to know how to carry data between classes

troubleturtle troubleturtle

2019/6/21

#
I am creating a game in which differently colored sheep shoot lasers that correspond to their color. I wish to have a trigger when a sheep touches a laser that is a color other than its own, but because I have condensed the sheep script into one class and the laser script into one class, this is very difficult. I was able to carry the image of the laser to compare it to the laser corresponding to the id of the sheep in the following code, but the statement ended up never being false because of the weird specifics of how the image is stored, destroying the sheep that created the laser. I don't know what other data I could ferry over from the laser class to the sheep class to make this distinction. I have a way to identify each sheep (id) and I have a similar way to identify each laser, but I don't know how to carry the id variable from laser class to the sheep class or an alternative. Help would be much appreciated. Here's my code: if(isTouching(laser.class) && (dead == 0)) { if(getOneIntersectingObject(laser.class).getImage() != new GreenfootImage("laser" + id + ".png")) { setImage("empty.png"); dead = 1; lost++; } }
Super_Hippo Super_Hippo

2019/6/22

#
To "carry over" the sheep's ID to its laser, you can pass it to the constructor when creating the laser.
//sheep creates laser
addObject(new Laser(id), getX(), getY());
public Laser(int id)
{
    this.id = id;
}
You will also need a way to get that ID.
public int getID()
{
    return id;
}
Then, to make sure a sheep isn't killed by its own laser:
Laser laser = (Laser) getOneIntersectingObject(Laser.class);
if (laser != null && laser.getID() != id)
{
    //…
}
troubleturtle troubleturtle

2019/6/24

#
Thank you! This reply got me to where I needed to be!
You need to login to post a reply.