Moving objects smoothly, bad perfomance - java

I just finished developing my mini-game on Android and I got some questions about perfomance and generally "how to": If I have 25+ objects on the creeen (just a polygon with 7-8 angles) its starts to lag hard and CPU usage is very high (15-20% without colision detection, up to 50% with collision detection on samsung note 10.1 tablet).
So I have ~25 polygons (asteroids) and they are always "flying". So to move them I make a Timer, right? On TimerTask I got something like this
public void move() {
translate[1] += speed[1];
translate[0] += speed[0];
updateTranslateMatrix(); // updating translate matrix and then send it into vertex shader
updateAABBCoords(); // update coordinates of Axis-aligned bounding box
updateCoordsByTranslate(); // update coordinates of verticles (to be able to define exact collision (with bullets and starship))
}
Is there something unnecessary in this method?
Also I want to ask if it is OK to run this timer every 17 ms? Or 17 ms is too often? I feel smoothness of movement only at 17 ms, may be I am doing it wrong? And same Timer interval I got on starship/bullets movement and on Collision detection.
Help me, please. I feel like missing something huge and fundamental, because 50% CPU on note 10.1 in that simple Asteroids game is not normal.

One key issue, I believe, is that you are assigning an individual Timer to every object instead of employing a general purpose game loop. A vast majority of games use a game loop which runs continuously and can be split, typically, into two components: Update and Render.
An article on basic game loop design for Java/Android
An answer to a relevant question on game loop design on gamedev.stackexchange.com
When using a game loop you can not guarantee being able to update exactly every 17ms or some other arbitrary duration. Instead, the Update and Render methods receive a DeltaTime parameter which is the time since the last frame.
This is then used when, for example, getting new object positions by multiplying it with the object's velocity. Doing so allows for smooth interpolation of position and ensures that object speed is not affected by CPU speed.

Related

JavaFX: Heavy laggs after a specific time

We're working on a little game with JavaFX for the GUI. The game is turn-based and after each turn we update our borderPane (.setCenter()) with the new board (this is an array which representes the tiles in the game). The tiles are drawn as JavaFX-Canvas objects.
We have the problem that every time after 155-160 turns the whole application begins to lag. CPU usage is increasing to 80% on my computer by one turn (e.g. turn 154: 1 % und turn 155: 80%). We also got an outOfMemoryError but not every time.
Additionally, we implemented some sysos for debugging and all the methods on our board array with the game logics are correctly and fastly iterated. The lag must be something in the JavaFX-Thread.
Can you help me?
Thanks a lot :)
The gc maybe isnt cleaning old objects. Did you try to use the daneobjects but not creating a new one every time?
Greets

Using Delta Time to Improve Movement

I looked up many threads on how to use delta time and I can't figure it out.
I want my guy to move at a constant speed every time I run the game.
So I have:
timer = new Timer(9, this);
timer.start();
then the paint method.
I tried doing start time at the beginning of the paint method and then a current time at the end of it. How would I make it affect the timer's speed or how far the player moves. I've tried multiplying the time delta by the increment to the x. nHeroX = dx*deltaTIme;
I feel like it's very simple I just need someone to tell me straight what to do please.
Traditionally, game programming relies on a continuous loop.
Anyway, all I have realized.
In this loop, you should separate model update and graphic update.
In your snipset, you seem to try mixing the two things.
In this loop :
- In a first time, you let the model to update.For example : guy's move from x to x1.
- In a second time, you must refresh the graphics to allow the guy to have a new position in the screen.
The speed of your guy depends on the guy model (ex: constant in your guy class).
But the speed of another type of guy could be different.
The general speed of your game relies on the FPS set in your main loop.
You can see an example on this post :
Java Main Game Loop
Good luck
Get the system time from the System object.
Get it again during your animation. Delta time is nothing more than subtraction.
Get rid of the JavaScript tag. The languages are completely different.

Are my programming methods for java games sufficient [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
so I'm making a 2d Java game with the slick2d and MarteEngine libraries. This is the biggest project since I made checkers for my Java class. I am still pretty new to programming concepts and using optimal ways to get stuff done.
The basic structure of my game is you are a player/hero in a zombie apocalypse and you can gather survivors to help you. There are a many areas that I'm concerned about in my programming. I'm not sure if my methods are a good choice for what I want. This game also does not currently have a grid/tile system.
I've looked at some open source java games and they don't really answer my questions to my methods. So I'm going to make a list here of what I'm uncertain about and I hope you guys can confirm/deny if my methods are appropriate. Sorry if this list gets too long, I'm thinking of the questions as I type.
Targeting/Attacking - Survivors will automatically attack zombies once they get within the gun's target range. To do this, I have every survivor get the distance (using distance formula) to every zombie and find the closest one to attack. I check for this constantly so if a faster zombie gets closer, the survivor will change targets. For zombies, they acquire a target and stick to it (for now). The zombies constantly check if they are within the attack range (around 50 pixels) using the distance formula. If they are within range, stop and attack, otherwise, move towards the target.
2D Camera - So a camera in a 2D environment moves the world around instead of you. My current method is have my zombies/survivors/any entities on the map stored in array lists. First the background is adjusted, then all the lists are cycled through and every entity's x and y values are modified. This seems to work alright but some stuff you can really notice sliding around on the background. Not really sure how to avoid this.
User Interface - I really have no clue how to work with UI. What I've been doing so far is simply using a background and then generating button objects and manually lining them up. Then, I check if the mouse is over any of the button's areas and if there is a click while moused over the button. I have three different backgrounds and buttons that I switch out with booleans. I'm going to recode that area though, using objects with the background and buttons. Is this the correct way to do UI?
Path Finding - I have no path finding system yet. Do I have to stick to a grid system? I really rather my entities move freely along the terrain and not in a weird square to square motion.
Selecting - I have it so you can select survivors, upgrade them, and other random stuff. My current method for selecting is constantly check where the mouse X and Y is. I get the distance from the mouse to every survivor and check if it is within 30 pixels. Then, I check if there is a click, if so, select the survivor and unselect all others. I'm still trying to figure out how to unselect all survivors if I click on open space. Is there a better way to go about doing this?
Picking stuff up - Same way as said before. I check the distance from the player to every item that can be picked up. If the item is within 30 pixels of the player, it picks it up. It seems to work fine for the moment I suppose. Maybe there really is no other way to do this.
Animations - I understand the how to animate with sprites, but I just want to make sure. So if I have 7 different guns to be shot, do I need to manually make functions that have precise timing on each sprite. Say if I have a shotgun, it needs a recoil, pump forward, brief pause, pump back, and ready again. For a pistol I need just the recoil really. So I'd have to make unique functions for each of these animations?
Sorry to type this long list of questions. I try to gather information on this stuff as much as possible and I haven't been able to find many examples on this stuff. I greatly appreciated any answers, even just a yes or no answer. Thanks in advance!
2D Camera:
Not exactly sure what you are doing when you say you modify each entity's position, but the way I'd do it is have a Camera object that has its own x, y, width, height and methods to move the camera around also, and then in your Draw cycle:
for (every Object on the map)
{
if (Object is within Camera bounds)
{
// Draw the Object at the Object-xy minus the Camera-xy
// This will draw the Object at its position relative to the camera
// and won't waste time drawing things that are not within camera bounds
}
}
Targeting/Attacking
You have the right idea, but checking every zombie against every survivor will take a lot of computing and (depending on how many zombies and survivors) can cause the game to slow down a lot. It's the same deal with collision detection, checking every object against every other object to see if they collide takes a lot. There are ways to not have to check everything against everything, I suggest you read into 'Spacial Partitioning'. I have not used slick2d but perhaps it has such a thing already implemented for you.
Picking stuff up
Same deal as Targeting/Attacking, if there are too many items or things that can pick up items, it will end up slowing frame rate a lot.
Selecting
This isn't way you should be doing selecting, but I myself have not had to use selection much at all so I am not completely sure of the best way, you should probably try searching around for ways to do this. Either way your current way can be improved by only checking on a click, you don't need to check every single frame, only check when there has been a click.
This is all I can help with currently, I hope it has been of some use to you at least.

More Efficient Method of Drawing Thousands of Particles (Java/Android)

So I'm writing a sort of particle simulator, like a "falling sand game" if you know what that is, and I've kind of hit a roadblock now. The way I'm doing this is I have a particle object that basically as of now has an position (int x, int y) and that's it. The way I'm drawing/moving them, is with a thread and the onDraw event for an android panel. Each time onDraw is called I loop through all the particles, move them down one pixel unless they hit the bottom and then draw them, this is pretty smooth until I get to about 200 particles, then the fps drops significantly. I know this is computation heavy the way I'm doing it, there's no debate about it, but is there any way I could do this to allow a lot more particles to be drawn and with less lag?
Thanks in advance.
I take it you're using an individual-pixel drawing function for this? That would indeed be slow.
I see a couple ways to improve it. First is to put the pixels into an in-memory bitmap then draw the whole bitmap at the same time. Second, since particles are always just going down one pixel, you can scroll part of the bitmap instead of replotting everything. If Android doesn't have a scroll then just draw the bitmap one pixel down and start a new bitmap for the particles above the scroll. You'll have to fix up the particles on the bottom, but there are fewer of those.
I've never done things like this before, but I have done some complex cellular automata. Sorry if this is too vague.
The basic idea here is to mark all particles that should "keep falling" or "not move" and exclude them from complex processing (with a special short/fast processor for the "falling" list - all you need to do is drop each one by a pixel).
The acceleration for non-moving particles - static particles (I'll call them S particles), is that they don't move. Mark it for all non-moving regions (like a gravity-immune "wall" or "bowl" that a user might make. Mark particles above it S if they are stable, so for example for liquid, if it has S particles under, and to both sides of itself, it will not move. For something like sand that forms piles, if it has an S in each of the three spots under it, it makes a pile, you'll get nice 45-degree piles like this, I'm sure you can change it to make some things form steeper, or less-steep piles. Do S mapping bottom-up.
The acceleration for particles with no particle under them is falling - F particles. Particles with an F particle under them are also F particles. Mark these bottom-up as well.
Particles unmarked F or S are complex, they may start falling, stop falling, or roll, use the slow processor, which you already have, to deal with them, there shouldn't be many.
In the end what you will have is many many fast particles. Those in a pile/lake and those raining down. The leftover particles are those on the edge of slopes, on the top of lakes, or in other complex positions. There shouldn't be nearly as many as there will be fast particles.
Visually mark each kind of particle with some colour, complex particles being bright red. Find cases where it is still slow, and see what other kinds of fast processors you should make. For example you may find that making lots of piles of sand creates lots of red areas along slopes, you may want to invest in speeding up "rolling zones" along the slopes of piles.
Hope it makes sense. Don't forget to come back and edit once you've figured something out!
You may want to look into OpenGL ES hardware acceleration and renderscript. It doesn't give you a more efficient solution code wise (see the other answers for that). It does open up a lot more processing power for you to use however. You can even run the entire simulation on the GPU (possibly, don't know your implementation details).
Edit
Also, if you still decide to do the processing in java, you should look at Method Profiling in DDMS. This will help you visualize where your performance bottlenecks are.
If you blur your image a bit, then you could just move half particule at a time, maybe one fourth only and print them all.. that would cut computation and the user wouldn't see it, getting the feeling all particules move.
But what ever you choose, I think you should be put a strong limit, not all users have powerfull android devices.
Regards,
stéphane
I think if particles are close each other, you can create objects that represent 3 or more particles.
When displaying several particles on screen, sets of grains maybe gets unnoticed.

How to generate simple 2D graphics in real time?

For my internship on Brain-Computer Interfacing I need to generate some very fast flickering squares on a CRT monitor (flickering = alternating between two colors). The monitor's refresh rate is 85Hz and we would like this to be the bottleneck, which means that repainting all squares can take at most 1000/85 = 11ms.
My language of preference for GUI/graphics programming is Java, so I tried making a prototype with AWT, because it's synchronous (unlike Swing). I now seem to have two problems: the first is that time measurements show that the repainting of even 9 squares simply takes too long. My algorithm takes the desired frequency and calculates the times at which the system should repaint in advance and then uses a loop (with no sleep/wait delay) that checks everytime if the next 'time' was reached and if so, loops through all the squares to repaint them. The way I implemented it now is that the squares are Panels with background color A and are contained in another Panel with background color B and the flickering happens because the Panels' visibility is changed. I figured that this would be faster than one Panel that has to draw Rectangles all the time.
I don't have a decent profiling tool (can't get Eclipse TPTP or NetBeans profiler to work) so I can't be sure, but I have the feeling that the bottleneck is actually not in the repainting, but in the looping (with conditional checking etc.). Can you recommend anything about what I should do?
The second problem is that it seems like the squares are rendered top-to-bottom. It's like they unroll really fast, but still visibly. This is unacceptable. What I'm wondering though, is what causes this. Is it Java/AWT, or Windows, or just me writing a slow algorithm?
Can you recommend some things for me to try? I prefer to use Java, but I will use C (or something) if I must.
I would avoid any kind of high-level "components", like JPanels and the like. Try getting a Graphics2D representing the window's contents, and use its fillRect() method.
Failing that, you could probably do this easy enough in C and OpenGL. rasonly.c is a standard template program that sets up OpenGL to work as a "rasterizer" only, i.e. 2D mode. Using this as a starting point, you should be able to get something running that draws your desired "squares" without too much trouble.
You don't describe your desired scene very well, it sounds from that equation as if you want to draw 100 squares, each having a different color. For maximum performance in OpenGL, you should draw all squares of the same color together, to minimize the "state changes" between drawing calls. This is probably a purely theoretical point though, as drawing 100 2D squares at 85 Hz really shouldn't tax OpenGL.
UPDATE: Oh, so it's been a bunch of years, and nowadays you probably need to take the above with a grain of salt and read some modern tutorial. Things have changed. Look up the Vulkan API.
(I remember a demonstration of this using the BBC micro and palette switching, though that would be 50fps rather than 85, as it was a British domestic TV)
I'd switch to jogl and use display lists. They get very high fps rates in Java.

Categories