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).
Related
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).
Please forgive me for what is likely an incredibly cringeworthy question (I am quite new to both Java and Android Studio). I come from a C background and am currently developing a mobile app for Google Play using Android Studio. The application will require a number of enemy objects to be created for the game.
Consider the following method of creating a Bitmap for an enemy object;
Within the GamePanel class (parent is SurfaceView, implements SurfaceHolder.Callback);
enemy = new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.enemy_pic));
Within the Enemy class, our image is declared as an instance variable;
private Bitmap image;
And then we initialise it in the constructor (picResource is the first argument into the constructor);
image = picResource;
My question is the following - if I create a list of enemy objects (there are lots of enemies!), will this result in the duplication of the Bitmap data? I am not sure from the docs whether it's lower level implementation will emulate pointer behaviour in C, and as such result in only minimal overhead from structuring it this way, or whether I am chewing up memory because I am essentially duplicating all the data in the picture file.
I create a list of enemy objects (there are lots of enemies!), will this result in the duplication of the Bitmap data?
Every call to decodeResource() will result in result in a new in-memory bitmap. If you create all your enemies as in your question:
enemy = new Enemy(
BitmapFactory.decodeResource(getResources(), R.drawable.enemy_pic)
);
every Enemy object will have its own unique bitmap.
That is, if you put this in a loop
List<Enemy> enemies = new ArrayList<>();
for (int i = 0; i < nEnemies; ++i) {
enemy = new Enemy(
BitmapFactory.decodeResource(getResources(), R.drawable.enemy_pic)
);
enemies.add(enemy);
}
You will get nEmemies bitmaps, i.e. each Enemy object has its own (in-memory) bitmap.
If you decode your enemy bitmap only once and pass the resulting reference to the Enemy constructor, you just create new reference to the single existing bitmap. That is, rewriting the above as (for example)
List<Enemy> enemies = new ArrayList<>();
Bitmap enemyBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.enemy_pic);
for (int i = 0; i < nEnemies; ++i) {
enemy = new Enemy(enemyBitmap);
enemies.add(enemy);
}
results in only a single bitmap to be shared by all enemies (unless Enemy does something to the bitmap to create a copy).
To refer back to your answer. In Java, assignments of the form
image = picResource;
do not create copies, but only create additional references (to be precise, this is only true for reference types, i.e. objects).
Side note: if you use Context.getDrawable(), you can make use of use of Android's drawable cache and get the same drawable even for repeated calls.
I have a JList that is displaying a custom object (Frog) using a custom cell renderer.
frogList = new JList<Frog>();
frogModel = new DefaultListModel<Frog>();
frogList.setModel(frogModel);
frogList.setCellRenderer(new FrogBrowserCellRenderer());
//add frogs...
The frog objects contains a list of images, and I have my list pick the latest one to display. It's in a thumbnail file, so I can read it into memory and display it. However I know that the JList re-renders every time the window moves or the window needs redrawn which is really bad for performance and just not good design. The issue I have is that this list is dynamic so I cannot simply load all images at startup because users can add them at runtime and it'll auto update the list.
Some people mentioned loading the image into memory in the constructor and setting it in the getListCellRendererComponent() method but that doesn't appear to be possible because it only creates one cell renderer and uses it for everything in the list. I also verified this by printing out the constructor method. Since I will have a list of frogs with all different images this doesn't really make sense.
Here is the code I am using to create the thumbnail right now.
public Image createListThumbnail() {
try {
Image returnImg = null;
//get latest frog image
SiteImage img = frog.getLatestImage();
BufferedImage src = ImageIO.read(new File(XMLFrogDatabase.getImagesFolder()+img.getImageFileName()));
BufferedImage thumbnail = Scalr.resize(src, Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH, 200, 150, Scalr.OP_ANTIALIAS);
if (!frog.isFullySearchable()){
ImageFilter filter = new GrayFilter(true, 30);
ImageProducer producer = new FilteredImageSource(thumbnail.getSource(), filter);
returnImg = Toolkit.getDefaultToolkit().createImage(producer);
}
return returnImg;
} catch (IOException e) {
IdentiFrog.LOGGER.writeExceptionWithMessage("Unable to generate thumbnail for image (in memory).", e);
}
return null;
}
I call this method in my getListCellRendererComponent() which I know causes terrible performance but I don't understand how to cache it in memory for multiple frogs and also use only one object. Perhaps an image map? I can't seem to find any solid evidence of a proper way to do this.
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".
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);
}
}