Removing spheres - java

I have finnaly managed to make my program detect collision between two balls that I have created in Java-3D; the player ball and the enemy ball. Now the problem is that I don't know how to make the player ball be removed when it collides with the enemy ball. I have tried some simple stuffs like objTrans.removeChild(sphere); and objRoot.removeChild(objTrans); (objTrans is my TransformGroup and objRoot is my BranchGroup), in both cases I get this error message
Exception in thread "AWT-EventQueue-0" javax.media.j3d.RestrictedAccessException: Group: only a BranchGroup node may be removed
I also tried objRoot.detach(); but then I get the error message:
Exception in thread "AWT-EventQueue-0" javax.media.j3d.CapabilityNotSetException: BranchGroup: no capability to detach
I don't know any other ways to make the ball be removed. Please Help.

I came across the same problem when designing a game myself. The solution that I found worked best was to store the objects that could possibly be destroyed in a list which I could iterate over and delete elements whenever necessary.

A simple code example. Each time you call updateModel (), a BranchGroup is removed, it is then updated with the new shape, and then added again
private BranchGroup mapGroup = null;
public void updateModel (....)
{
Shape3D shape;
// Update 3D primitives
if (mapGroup != null) // remove previous 3D model
object.removeChild (mapGroup);
shape = facesTexturedShape (....);
if (shape != null) // add new 3D model if non-null
{
mapGroup = new BranchGroup ();
mapGroup.setCapability (BranchGroup.ALLOW_DETACH);
mapGroup.addChild (shape);
object.addChild (mapGroup);
}
}

Related

Libgdx - didpose over and over?

hey am a beginner in Libgdx. i am a bit confused about disposing the stuff.
Texture brickTexture;
Array<Brick> bricks;
public Game {
brickTexture = new Texture("brick.png");
bricks = new Array<Brick>();
for (int i = 0; i < 10; i++) {
Brick brick = new Brick(i, brickTexture);
bricks.add(brick);
}
}
void dispose () {
brickTexture.dispose(); // brick texture loaded in this class
for (Brick brick : bricks) brick.brickTexture.dispose(); // disposing the public texture which was earlier passed on to the brick class
}
Should both of the lines be in the dispose method or only the first one ?
You only have to do this once. It's the same Texture object so when you dispose it on any reference no other object can use it anymore. It's disposed.
Also you might want to check out AssetManager class, which handles disposing stuff for you.
You are using "bricktexture" for every "Brick" in the ArrayList, so you are basically pointing to the same object so you should only dispose "bricktexture" once.
If you also want to "free" the array, probably you should call
bricks.clear();
Which will become empty (as with no elements inside).

How do I remove Sprites when they go on a specific position?

My Sprite are spawned at a random time, after being spawned the the move upward until they get on a certain position then they should be removed. That's what I've been trying to do but I always get an error.
//this method is called at random time
public void newEnemy(){
Sprite enemy= Pools.obtain(Sprite.class);
enemy.set(enemySpr);
enemy.setPosition(200,150);
enemies.add(enemy);
}
//removing the enemy
while (enemyIterator.hasNext()){
Sprite nextEnemy=enemyIterator.next();//<--error here,this is line 66
if(enemySpr.getY()+enemySpr.getHeight()>=treeObj.treeSpr.getY()){
removeEnemy(nextEnemy);
}
}
//removeEnemy method
public void removeEnemy(Sprite sprite){
enemies.remove(sprite);
Pools.free(sprite);
}
//this is the error there I get:
Exception in thread "LWJGL Application" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at com.dreamroad.savethetree.EnemyClass.update(EnemyClass.java:66)
at com.dreamroad.savethetree.MyGdxGame.render(MyGdxGame.java:51)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Process finished with exit code 0
I think this is the reason why I get the error, but I'm not sure:
public void draw(SpriteBatch batch){
for(Sprite drawEnemy:enemies) { //enemies is the ArrayList
drawEnemy.draw(batch);
drawEnemy.translateY(deltaTime * movement);
}
}
As Subler says, the problem here is that you're trying to remove something from a list at the same time as iterating over it.
However, there's an easier solution. Simply call remove() on the iterator. This will remove the iterator's current element.
//removing the enemy
while (enemyIterator.hasNext()) {
Sprite nextEnemy = enemyIterator.next();
if(enemySpr.getY() + enemySpr.getHeight() >= treeObj.treeSpr.getY()) {
enemyIterator.remove();
Pools.free(nextEnemy);
}
}
The problem is that youre trying to remove something in a list you're currently iterating over, the thing i've always done in a situation like this is create an extra list which holds the Sprites that should be deleted, and then delete them after iterating over the list (or, at the end of your update method, or something like that)
A short code sample that illustrates my idea:
//removing the enemy
//Initialize a list to store the sprites to be removed
List<Sprite> toBeRemovedSprites = new ArrayList<Sprite>();
while (enemyIterator.hasNext()){
Sprite nextEnemy=enemyIterator.next(); //I get the error here..<--
if(enemySpr.getY()+enemySpr.getHeight()>=treeObj.treeSpr.getY()){
removeEnemy(nextEnemy);
toBeRemovedSprites.add(nextEnemy);
}
}
//Remove the sprites that should be deleted, after iterating over the list
for(Sprite s : toBeRemovedSprites){
enemies.remove(s);
}
//removeEnemy method
public void removeEnemy(Sprite sprite){
//Remove this line that removes the sprite from the list
//enemies.remove(sprite);
Pools.free(sprite);
}
Another thing you could do is just to use the remove function of the iterator,
imagine it could look something like this:
//removing the enemy
while (enemyIterator.hasNext()){
Sprite nextEnemy=enemyIterator.next(); //I get the error here..<--
if(enemySpr.getY()+enemySpr.getHeight()>=treeObj.treeSpr.getY()){
removeEnemy(nextEnemy, enemyIterator);
}
}
//removeEnemy method
public void removeEnemy(Sprite sprite, Iterator<Sprite> enemyIterator){
//Change the line to remove using the iterator
//enemies.remove(sprite);
enemyIterator.remove();
Pools.free(sprite);
}

libgdx overlap stop draw

I have written the following code. I would like to stop drawings once object one the collision has occurred. Unfortunately, it only stops drawing the object only when the collision is occurring and then starts drawing the object again.
To give an example of what I am trying to learn is: player collects coin, coin disappears. if the player misses coin, the coin still appears on screen.
The idea is to learn the basic concepts before I start putting things together. Copying code without understanding is no fun. Thanks in advance.
batcher.begin();
if (egg.collected) {
batcher.draw(AssetLoader.textureEgg, eggRect.x, eggRect.y, eggRect.width, eggRect.height);
}
batcher.end();
My egg class:
public class Egg {
private Rectangle egg;
private Vector2 location;
public Egg(float x, float y){
location = new Vector2(x, y);
egg = new Rectangle(location.x, location.y, 10, 15);
}
public void update(float delta) {
egg.x--;
if (egg.x < -20) {
egg.x = 137;
};
}
public boolean collected = false;
public Rectangle getEgg() {
return egg;
}
public boolean isCollected() {
return collected;
}
}
The result of the above code is: The game crashes with following errors.
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.mygdx.gameworld.GameRenderer.render(GameRenderer.java:60)
at com.mygdx.screens.GameScreen.render(GameScreen.java:32)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:214)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Tenfour04 is right. Since collides is true when the two objects overlaps, it will stop drawing while they overlap and start to draw again. Save the return value to member variable.
Create a member variable in your Egg class to keep track of whether the egg has been collected:
public boolean collected = false;
If you want to practice good encapsulation, you could make this variable private and give it a getter and setter, but I'll keep it simple like this.
Then in what appears to be your game or screen class, you need to tell the egg when it's collected:
if (eggRect.overlaps(boundingRect))
egg.collected = true;
Now, you should only draw the egg if it is not collected:
batcher.begin();
if (!egg.collected){
batcher.draw(AssetLoader.textureEgg, eggRect.x, eggRect.y, eggRect.width, eggRect.height);
}
batcher.end();
By the way, it's kind of weird that your Egg class extends Rectangle, but you aren't using it as a Rectangle but rather as a container for some other Rectangle. You might as well remove "extends Rectangle".

The Android draw order for bitmaps, drawables and text?

I'm creating a small game in android. Anything that needs to be drawn on screen extends my VisibleObject class, I then have a Manager class that i can add all my visible game objects to and each frame i tell the manager to call the draw function of everything within it.
Here's were objects are initialised and added to the manager:
#Override
public void surfaceCreated(SurfaceHolder holder) {
fps = new TextDrawable(Color.BLACK, 14, 100, 40, 40);
player = new Player();
map = new Map();
leftTouch = new TouchCircle(Color.GRAY);
manager.add("fpsText", fps);
manager.add("leftTouch", leftTouch);
manager.add("player", player);
manager.add("map", map);
gameloop = new GameLoop(getHolder(), this, fps);
gameloop.setRunning(true);
gameloop.start();
}
Now the problem i'm having is with the draw order, if you look at the order the objects are added to the manager for reference..
I can tell you for certain that the player is being drawn on top of
the map! These are both drawn by drawing there respective bitmaps with drawBitmap(..).
However the fpsText and leftTouch are being drawn underneath the map! These are drawn using drawText(..) and drawOval(..) respectively.
Even though they implement different Canvas.draw.. functions, I would expect them all to be drawn in order as I just pass the canvas object i have to my manager class and then let the manager cycle through each object passing it that canvas to draw with.
Can anyone clear up for me why bitmaps seem to be drawn on top and what the solution should be to get my fps and touch area drawn above the player and map bitmaps? I'd Appreciate it.
EDIT: I am using private ConcurrentSkipListMap<String, VisibleObject> objectMap; within my manager to store the objects and drawing like so..
public void draw(Canvas c){
for (Map.Entry<String, VisibleObject> object : objectMap.entrySet()){
synchronized(object){
object.getValue().draw(c);
}
}
}
Bitmaps are not drawn on top of the text unless you draw Bitmap after you drawn text (and position overlaps).
You haven't disclose onDraw method so I can't be sure, but I suspect that you are not calling drawing methods in right order.
How does you manager stores the values added to it? Maybe you use Map implementation that doesn't maintain order of elements added (most implementations don't, LinkedHashmap does).

Java Greenfoot, cannot link method between files

Working on a project in school, I'm a beginner to programming and I have big problems with the making of Bubble Shooter, I need to get all of the balls of the map before it changes to map2..
Trying to make it with listing all of the balls but the program crashes at the end of the first map and gives us the error-report that it can't load a negative value. I figured it was when it was trying to load the gun and wanted to put an if-statement that says that if "allowedBallTypes != null" or zero, as it might be, than it should load the gun.
cannot find symbol - getAllowedBallTypes();
greenfoot java method class
The bubbleworld class:
public BubbleWorld()
{
super(Map.MAX_WIDTH*Map.COLUMN_WIDTH, Map.MAX_HEIGHT*Map.ROW_HEIGHT, 1,false);
// Max speed. We use time-based animation so this is purely for smoothness,
// because Greenfoot is plain stupid. I can't find a way to get 60 Hz so this is
// what we have to do. Note: Exporting the game seems to cap this to some value < 100. :(
Greenfoot.setSpeed(100);
// Load the map.
map = new Map(this, testMap1);
// Update the allowed ball types. (i.e. we don't want to spawn a
// certain color of balls if the map doesn't contain them!)
map.updateAllowedBallTypes();
// Create the cannon.
Cannon cannon = new Cannon();
addObject(cannon, getWidth()/2, getHeight());
The map class:
public int[] getAllowedBallTypes()
{
return allowedBallTypes;
}
public void updateAllowedBallTypes()
{
int allowedCount = 0;
boolean[] allowed = new boolean[Ball.typeCount];
// Only ball types that exist in the map RIGHT NOW as attached balls will be allowed.
for(Cell c : cells)
{
if(c != null && c.getBall() != null && c.isAttached())
{
int type = c.getBall().getType();
if(!allowed[type])
allowedCount++;
allowed[type] = true;
}
}
allowedBallTypes = new int[allowedCount];
int writeIndex = 0;
for(int type = 0; type < Ball.typeCount; ++type)
{
if(allowed[type])
{
allowedBallTypes[writeIndex++] = type;
}
}
}
The Cannon class:
private void prepareBall()
{
// Get a random ball type from the list of allowed ones. Only balls currently in the map
// will be in the list.
int[] allowedBallTypes = ((BubbleWorld)getWorld()).getMap().getAllowedBallTypes();
int type = allowedBallTypes[Greenfoot.getRandomNumber(allowedBallTypes.length)];
// Create it and add it to the world.
ball = new Ball(type);
getWorld().addObject(ball, getX(), getY());
}
Assuming you are getting that error in the pasted snippet of the Cannon class, the error suggests that there is a problem with the getMap() method of BubbleWorld -- can you paste that in so we can see it? It might not be returning the correct type. In general, you need to paste in more code, including complete classes, and say exactly where the error occurs. An easier way might be to upload your scenario with source code to the greenfoot website (www.greenfoot.org -- use the share function in Greenfoot, and make sure to tick the source code box) and give a link to that.
Based on your code, your map class doesn't seem to have a class-level variable declaration of int[] allowedBallTypes;

Categories