Reputation: 11
I have a object in my java game which is going to be a coin, currently its just a rect made with
g.setColor(Color.yellow);
g.fillRect(x, y, 16, 16);
I have collisions set up to give the player points when they touch it, and that works fine, but how do I make it delete itself after its touched? as it is the points just keep going up.
The only thing I could think of was to recolor it to make it look like it wasn't there, but thats far from the same thing.
Upvotes: 0
Views: 2046
Reputation: 3729
You should have a Rectangle
class, or rather a Coin
class, e.g.
public class Coin {
int xPos;
int yPos;
int width;
int height;
// For giving player points
int points;
// Constructors, etc
// e.g. public int getXPos(), public int getYPos()..
}
At the start, you will have something like an ArrayList
of Coin
, e.g.
ArrayList<Coin> coins = new ArrayList<Coin>();
In your drawing method,
for (Coin c : coins) {
g.fillOval(c.getXPos(), c.getYPos(), c.getWidth(), c.getHeight());
}
When the player collides with the Coin
, you'll just need to remove it from the ArrayList
.
To make it more extensible, you can even define an interface Collectible
, and make all your collectible in-game objects such as Coin
in this case implement the Collectible
interface.
Upvotes: 2
Reputation: 304
You really should have an ArrayList
of objects in some kind of level or handler class
to deal with having multiple objects. That way you can easily add
or remove
them as you need to using the ArrayList
functions add()
and remove()
. For more specific information on actually removing objects see this post. And for information on handling objects in a game see this post.
Upvotes: 1
Reputation: 147
If you made an object you could make it equal to null.
rectObj = null;
If you simply did a fillRect() method without making an actual object you could move it off the panel or simply color it white. However, I hope that you did use an object as it would be a lot simpler and effective.
Upvotes: 0