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

2013/4/13

Collecting objects won't work.

h123n h123n

2013/4/13

#
I am trying to make a game where you avoid lazer beams and collect gems, but once the player collects the second gem, the gem doesn't disappear. I don't know what does this so could someone please help me. Here is the code: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Gem here. * * @author (h123n) * @version (0.1 BETA) */ public class Gem extends Actor { private int gems = 0; /** * Act - do whatever the Gem wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { //See if our gem has been stolen ;( Actor penguinDave; penguinDave = getOneObjectAtOffset(0,0, PenguinDave.class); if (penguinDave != null) { World world; world = getWorld(); world.removeObject(this); gems++; if (gems == 1) { world.addObject(new Lazer(), 100,400); world.addObject(new Gem(), 50,200); } if (gems == 2) { world.addObject(new Lazer(), 350,400); } } } }
Gevater_Tod4711 Gevater_Tod4711

2013/4/13

#
I think the relevant code is not in the class Gem but in the player class. Could you post the code of this class too?
danpost danpost

2013/4/13

#
The value of the variable 'gems' will never be two. You are removing the Gem object that has the variable of 'gems' with a value of one and creating a new Gem object whose 'gems' field is initialized to zero. What you can do, instead of creating a new Gem object, is just move the one that is already there. Remove the statement: world.removeObject(this); Change the statement: world.addObject(new Gem(), 50, 200); to setLocation(50, 200);
h123n h123n

2013/4/13

#
Thank you Gevater_Tod4711 and danpost, I didn't know that deleting the object also reset the variables, thank you both for helping me do the coding and if I release my game, I'll put you both in special thanks. =-D
danpost danpost

2013/4/13

#
Deleting the object does not reset the variable. The variable stays with the object you delete. However, if there are no more references to the object, it will no longer be accessible to you and it will be flagged for garbage collection. Each object you create from that class will have a seperate variable with that name; this is why we call those variables 'instance object variables' (or 'instance object fields'; a.k.a. 'properties'); since each instance created from that class will have a set of its own.
You need to login to post a reply.