简体   繁体   中英

How do I delete objects in a Java game

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.

You should have a Rectangle class, or rather a Coin class, eg

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 , eg

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM