Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (527)
Games in Android Showcase (127)
games submitted by our members
Games in WIP (593)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2 3 4
1  Game Development / Newbie & Debugging Questions / Is using glScalef(...) frowned upon for 2D? on: 2014-10-23 16:29:52
Are there any tangible performance issues relating to using glScalef(...) to render a 2D tile-based scene?

As probably thousands of other people on here are doing, I'm creating a 2D tile-based game, and part of that requires me to draw my grainy, poorly-designed 16x16 pixel textures (read in from a texture atlas) at a much higher size than they're designed. The entire scene is 'zoomed in' by a factor of 3 or 4 (I'm thinking this will be user-definable). But I'm wondering whether I should really be using glScalef to do this, or just simply draw the quads bigger?

I'm only calling glScalef(...) once before the tiles are rendered. It doesn't get called again until the next render pass, so there's no continual use of the function for each tile.

Thoughts would be welcome on this - I'm keen to try and use this method to up-scale bitmap font rendering too!

Thanks!
2  Discussions / General Discussions / Re: Mobile Java game development, without using a full-size laptop on: 2014-10-09 11:40:51
Thanks again everyone for pitching in your thoughts on this, although I still remain surprised at the expectation that a decent laptop should be able to run games. As I mentioned in my original post - this machine's sole purpose was to be a mobile development platform, and I wasn't looking for stellar graphics performance.

I totally get that other (PC) laptops of a similar price are probably more powerful, or perhaps more diverse when it comes to their application across the productivity / gaming territories, but I must stress that this is a device I'm just going to be typing code into on a regular basic - not something I plan on loading up Windows onto and firing up my Steam library.

I won't wax lyrical about the pros and cons again, there are some pretty balanced arguments put forth above this post from various community members. I'm pretty pleased that a productive discussion was had here, since this seems (glazing over the posts) to be the right kind of kindling for a PC / Mac flame war. Not what I intended, naturally.

One thing I do feel like chipping in on, though, is one thing I think that Apple do very well. And that's making choices easy for the consumer. Sure, they do come in at a (much) higher price for their hardware, but I walked into a local PC World branch recently, and looking through their 'Laptops & Netbooks' aisles I just felt completely lost. So many brands, so many different specifications, screen types, bolt-on-extras, included software and all that fuss. Variable build quality was also a particular point of note, along with many laptops having a kind of materials identity-crisis. Some looked futuristic, some decidedly plastic, others a horrific mish-mash of weird multi-function buttons and control surfaces. I honestly wouldn't have wanted to spend any time trying to make a decision there.

At least with Apple, the product line is fairly simple. Macbook Airs for portability and productivity, Macbook Pros for the more serious usage scenarios, iMacs for desktop workstations and Mac Pros for industry-level applications. There's very little granularity in each line too, making the choices much more simple.

At the end of the day, everyone has their own preference, and no one laptop will be right for everybody!
3  Discussions / General Discussions / Re: Mobile Java game development, without using a full-size laptop on: 2014-10-08 19:47:54
Hi all, I thought I'd respond now that I've finally made a decision, and a purchase!

I know this will engage the ire of some people who've taken the time to respond to my original post (and I'm sorry if that's the outcome here), but I ended up picking up a Macbook Air (11" base model). All told it was $749 (or $899 to my U.S. friends).

Ultimately there were a few things that tipped the scales in favour of the Macbook. Primarily, weight and portability were satisfied nicely by my choice, but the screen and speed of the thing have been really surprising. The base 11" model doesn't have the stellar screen resolution of the Macbook Pros (which go up to 2560 x 1600 I believe), but it's ideal for the smaller screen dimension.

Furthermore, coding on it is a joy. Eclipse runs amazingly - it starts up almost instantly and project builds are really snappy. Much improved over my old 2009 Macbook Pro. As for all the other productivity stuff, well - it does that stuff just as well as other machines I'd imagine.

I appreciate everybody taking the time to share their thoughts on my issue, and am grateful for the advice received, so thanks!

Lastly, one thing I should add - the laptop looks stunning. Yes, I know that looks are probably the least of concerns here, but I'm yet to pick up another laptop in the same price bracket that has this amazing kind of build quality and polish to it. I'm always happy to be proven wrong, but it feels like a solid, quality piece of hardware - something I'm pretty chuffed to own. Not very pragmatic, I know, but hey - if I'm going to spend £700 on a piece of hardware to take out and about, I might as well get something that looks good too  Grin

Not everybody's cup of tea, but hey. It's a great mobile development platform!
4  Discussions / General Discussions / Re: Mobile Java game development, without using a full-size laptop on: 2014-10-05 19:32:44
Thanks everyone for the replies to this question, although I'm surprised at some of the (perhaps perceived) hostility in some responses.

I've had a look at some cheaper laptops (perhaps formerly classed in the 'netbook' bracket), but they all seem to be either too heavy for what they are in size, have awful, low-resolution displays with terrible brightness / contrast ratios, or are simply just lacking in the performance department.

I appreciate that I might be asking a lot for a machine that ticks all the right boxes but remains under the £700-ish price bracket, but I believe one helpful poster above pointed out that the Macbook air, although slightly above my budget, does actually tick the boxes I need whilst still being reasonably affordable.

I'm not looking for a hardcore out-and-about desktop replacement, just something small and light enough to not be a hassle to cart around and yet still be comfortable enough to code on.

That said, I appreciate everyone's' input. I'm still looking at the Macbook Air as the replacement machine. It's never about the badge, I couldn't give two hoots about it. But it's got good performance, great weight, and a nice high-resolution screen, so it seems perfect for me.
5  Discussions / General Discussions / Re: Mobile Java game development, without using a full-size laptop on: 2014-10-04 12:37:43
Thanks for the reply - I hadn't even considered the Macbook Air line, come to think of it. I guess the world of laptops have moved on a bit since 5/6 years ago!

The price range does sting, true, but the more I look into this, the more likely I'm finding that going with just a more modern laptop is the way forward.

That said, the lowest-spec Macbook Air (which suits my needs, hardware-wise) has an 11" (27cm) screen. I didn't even realise the range went that small. That does actually fit my requirements (at a push), since my main reason for being anti-laptop was that I'd expected at least a 13" screen on any laptop. Having one with a smaller display is a huge bonus for me.

Thanks for pointing this out, you've made my search a whole lot easier now!

6  Discussions / General Discussions / Mobile Java game development, without using a full-size laptop on: 2014-10-03 15:28:46
Hey all,

I've been struggling with this for a while now. I have a pretty old, but powerful enough 13" Macbook from the 2009-ish era which I've been using for mobile Java development for a while now (using Eclipse).

The problem is, the laptop is starting to wear down and exhibit graphics card problems, so I've no doubt it's on the way out. To be honest though, I'm glad. The thing is a beast. It's so heavy and cumbersome compared to newer laptops in its size range.

I've been looking for something compact to move onto for mobile development for the last few weeks, and I was really tempted by the Surface Pro 3 - a device that has the right kind of form factor (small enough to be extremely lightweight and portable, yet with a large enough screen / high enough resolution to make coding feasible). It's also pretty well rated in terms of power and capability, although perhaps not really necessary for my code project requirements.

However, the sheer price of the thing turns me right off. That almost insulting £100 price tag for a snap-on mechanical keyboard (and £169 for a dock... what?) feels like a real slap in the face. The lowest price version of that device with a serviceable hard drive size (128GB, not the tiny 64GB version) is already £849, something that seems wildly exorbitant.

I'd love to hear from fellow Java devs who might use mobile workstations for their projects - especially those that use devices perhaps smaller than the average laptop. I'm really hoping to pick up something capable but modest enough to have a reasonable price tag whilst being a bit more portable than my 4-and-a-half pound ageing Macbook!

Thanks all!
7  Game Development / Newbie & Debugging Questions / Re: Calculating 2D tiled lights (additive behaviour of multiple sources) on: 2014-09-16 15:12:39
That's brilliant! Just the kind of reply I was hoping for!

I'm really pleased that I was heading along the right lines.

Currently, I'm apply a blanket floating-point modifier to the RGB color value of each tile. Each quad's vertex colours are all multiplied by the  light intensity thusly:

1  
glColor3f(red * intensity, green * intensity, blue * intensity);


I'm guessing that supporting coloured lights, as you say, is no different than multipliying the individual color components by actual light color components. Intensity is the floating point light level for that tile (between 1 and zero).

I'll give it a try, thanks!
8  Game Development / Newbie & Debugging Questions / Calculating 2D tiled lights (additive behaviour of multiple sources) on: 2014-09-15 22:52:21
Hey all!

I'm trying to wrap my head around the additive nature of attenuated light sources in a tiled 2D scenario.

Pictures!

Here's the current method of calculating a light source (linked because they're too big for this post):
http://imgur.com/gjRPqhE

The light at the source point is at maximum brightness. The light then bleeds off around 30% per tile's distance from the source, ending when the result is zero or below.

Assuming that I'm starting with a blank light map (zero light), how do I get to a situation where I'm accurately 'blending' other cell's light levels?

Consider the following example:
http://imgur.com/eax6b67

Here, multiple light sources intersect. This is a photoshop mockup using alphas that roughly represent the same light levels I'm actually using in-game. But the principle seems to work well - the alphas that overlap seem to add together to give a blended equivalent.

Is the principle as simple as adding the result of a light source calculation to the existing cell's light level? So assuming a blank 'zero' light starting point, I simply add each light source's attenuated light level to the cell's existing level?

I feel like I'm missing something, so hopefully some guidance will help steer me away from certain disaster!

Thanks!
9  Game Development / Newbie & Debugging Questions / Re: Data structures for large arrays on: 2014-08-31 09:04:38
Hello again! Thanks for all of your suggestions everybody, it's been great to get some perspective on this.

I should probably explain why I need to store certain variables - but I'd like to clarify off the bat that I probably don't need to store the X and Y grid reference - since the inferred position in the array is naturally enough there.

During the update cycle, tiles that have an animTexID (i.e. one that isn't -1, or 'none') will have their frame time incremented by the current engine millisecond delta time. There's a quick TextureManager call to see whether or not that frame time is longer than the nominated frame time for that particular texture ID, and if so its frame counter is incremented. It's then either capped (if its a non-looping animation that's hit its last frame) or looped if it's hit its last frame.

In answer to the data size question, realistically, I very much doubt my game will go over a potential map size of 800 x 2400 tiles. And even then, I think having all 800 tiles of width is a bit excessive for my needs. But eh, I think it's worth extending the capability of the engine, just in case....

So, taking some of the options offered, splitting that map size into chunks of 16 x 16 tiles gives me a size of 50 x 150 chunks. If I were to dump each chunk into a file, that's a grand total of 7,500 files.

I could be clever and use chunk 'strips' instead - where I define an entire row of chunks in a file - which would leave me with only 150 files, but the obvious additional overhead of how long it takes to read a chunk row into memory, but swings and roundabouts I guess.

So, when I create a new map, I prototype the creation of all the chunk files:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
public static String newChunkString()
   {
      String builder = "";
     
      for (int x = 0; x < CHUNKSIZE; x++)
      {
         for (int y = 0; y < CHUNKSIZE; y++)
         {
            builder += "[";
            builder += "T=0;";      // refers to the enumerated index of the type
            builder += "R=0;";      // how much 'resource' this tile has remaining
            builder += "]\n";
         }
      }
     
      return builder;
   }


The great thing is that I don't really need to store that much information about a particular tile in the chunk file - its texture IDs I can get from the tile type, the frame timers will be reset on launch (and probably set to a random frame in their maximum frame count to restore the visual 'randomness'), and the power requirement and current level will be calculated on launch also.

A quick test of a 10 x 20 chunk level gave me a total of 550Kb of files (200).

Running it with the full compliment of 50 x 150 chunks gave me a total of 20Mb of files (7,500). The map took around 10 seconds to generate these resources.

I might opt for the chunk rows simply because I'm concerned about the awful file fragmentation you'd probably end up with on disk with the one-file-per-chunk method. But perhaps I'm over-thinking it? It is a kind of one-shot deal... once the chunks are made on disk, it'll just be a case of loading and saving a handful of them every now and then.

Finally, in response to the comment suggesting I move to a single dimensional array - I understand the performance improvements gained (I had a look at the thread you mentioned, and did some other digging too) - but I also can't ignore how much easier it is to get my head around a two dimensional array. Being able to provide simple X and Y coordinates into the arrays just seems, I don't know, easier to wrap my head around I guess!
10  Game Development / Newbie & Debugging Questions / Re: Data structures for large arrays on: 2014-08-30 11:00:14
Thanks, it helps to see how other devs approach the same tehnique!

Much appreciated!
11  Game Development / Newbie & Debugging Questions / Re: Data structures for large arrays on: 2014-08-30 10:06:12
That does seem like a sensible suggestion.

So what you're suggesting is that I split the world map into a kind of chunk format (say 16x16 tiles apiece), and have a maximum 'range' of chunks that are stored in memory.

Then, if a chunk goes out of range, I store it to disk and flush it from the active list of chunks, and conversely when I attempt to create a 'new' chunk (when in range) I first check to see if it exists on disk and load it from there first?

So, working through this in my head, I could do the following:
  • Start off with a blank 'active chunks' array
  • Determine 'range' of chunks around the player, thus giving me a minimum and maximum chunk X & Y grid reference.
  • Check if these chunks are in the active chunks list, add if not insert prototype (empty) chunks flagged as 'not loaded'
  • Check through the active chunks list, and for those that aren't loaded, check for a file on disk and load its stage from there, else create the chunk from scratch using the required generation rules
  • Cycling through the active chunks array, determine which chunks are 'on screen' and add them to a 'visible chunks' list, which will be used to render them

I'd store the current chunk coordinate the player is in, so that if they change chunks I can kick off the next bit of code:

  • Determine the minimum and maximum chunk coordinates in range
  • Cycle through the active chunks list and if a chunk is out of range now, save it out to disk and remove it from the active list
  • Once done, repeat the 'add new chunk' code to add chunks that are now in range (that weren't before), flagging them for loading
  • Flush the visibility list and rebuild it based on the new active chunks list

This seems to work in my head, but maybe I've missed something. Thoughts would be welcome here!

Thanks for the pointer! Smiley
12  Game Development / Newbie & Debugging Questions / Data structures for large arrays on: 2014-08-30 09:38:53
I have a large 2D area which is to be represented by graphical tiles.

Each tile needs a few bits of information stored against it - enough that I ended up creating an actual object for each tile - but it doesn't seem that efficient to me for the actual level size required.

Here's the sort of information I need to keep an eye on for each tile:

- X & Y position (current a short, since its a grid reference and will never go over 5000 in either direction)
- Power level (a byte, as its minimum is 0 and maximum is 16)
- Requires power (a byte, with a minimum of 0 and maximum of 16)
- Static texture ID (a short, because there will never more than 32,767 textures!)
- Animated texture ID (again, a short, used like the above but either/or)
- Animation frame (a byte, used the control its texture animation)
- Frame time in milliseconds (a short, used the control its texture animation)

So my class looks a bit like this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
package com.ak.game;

public class Tile
{
   private short x, y;
   private byte power;
   private byte needsPower;
   private short texID, animTexID;
   private byte frame;
   private short frameTime;
   
   public Tile(byte x, byte y)
   {
      this.x = x;
      this.y = y;
   }
}


My question really is how to best approach the definition of thousands of these tiles.

If I were to want to have a level comprising of, say, a 320 x 3000 tiles, surely an array of Tile[][] objects is really inefficient?

I only ever plan on rendering whatever is on the screen, which is fine (I can reference the leftX / rightX and TopY / BottomY tiles to create a small 'viewport' tile loop for this). But updating tiles that are offscreen that need to be tracked? Seems like a hugely inefficient route to have to cycle through all 320 x 3000 (960k) tiles to accomplish this!

I'd be really grateful to get some pointers on how other people may have solved similar situations before. Would I have to look into some kind of aggregating update over multiple frames? Perhaps updating only X number of tiles each frame, thus splitting up the wholesale update leg-work over the course of multiple frames?

I should add that I want to avoid using multi-threading where possible, since I want to try and keep the base code as optimised as possible without giving up and 'cheating' on another thread! (something I'm not confident with yet).

Thoughts would be welcome!
Thanks!
13  Game Development / Newbie & Debugging Questions / Re: *SOLVED* Stuck in recursion hell! on: 2014-08-30 08:51:22
Thanks for your reply!

I'm guessing you were referring to this line of code:
Quote
// don't process this wire if it's already on
      if (wireMap
  • [y].on) return;
This was in to handle cases where the wire-trace loops back over itself (if someone essentially draws a wire in a 'box' shape). However, with the new code that prevents a wire from being re-traced when its generator ID matches the current process ID this is now redundant - I didn't spot it, so thanks for pointing that out!
14  Game Development / Newbie & Debugging Questions / Re: *SOLVED* Stuck in recursion hell! on: 2014-08-29 08:01:54
Of course, and thank you!

For those that are interested, this is the code that solved the issue:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
   private void calcNextWireNode(int x, int y, int depth)
   {
      // if we've hit our maximum recursion (distance) depth, finish here
      if (depth >= MAX_GENERATOR_TRAVEL) return;
     
      // if we're not in bounds, finish here
      if (!tileInBounds(x, y)) return;
     
      // if this tile isn't a valid wire type, finish here
      if (wireMap[x][y].type == WireType.NONE) return;
     
      // don't process this wire if it's already on
      if (wireMap[x][y].on) return;
     
      // don't process this if we're on the same generator ID
      if (wireMap[x][y].generatorID == CURRENT_GENERATOR) return;
     
      wireMap[x][y].generatorID = CURRENT_GENERATOR;
     
      // turn 'on' this wire if it's in range of the generator
      wireMap[x][y].type = onlineWireForType(wireMap[x][y].type);
     
      // increase the depth
      depth++;
     
      CURRENT_GENERATOR_OPS++;
     
      // test the four spaces around this tile
      calcNextWireNode(x-1, y, depth);
      calcNextWireNode(x+1, y, depth);
      calcNextWireNode(x, y-1, depth);
      calcNextWireNode(x, y+1, depth);
   }


Now that the wire map is made up of wire objects - I can start doing some cool things now, like having each wire store a power value which can be 'boosted' with other generators nearby, thereby allowing me to calculate a power 'fall off' value, rather than a simple cut off.

Thanks for everyone's input! I'm glad this is no longer a sticking point!
15  Game Development / Newbie & Debugging Questions / Re: *SOLVED* Stuck in recursion hell! on: 2014-08-28 16:25:40
Hah, thanks! I was almost tempted to click on that link!

I solved this by taking the concept first suggested to me. I added a 'current source' counter, which increments with every power source that's generated. Then, inside each Wire object I have a reference ID that's initially set to -1 when the map calculation begins.

Every time the recursion 'looks' at a wire - if its reference ID doesn't match the current source counter then it processes immediately. It then has its ID set to that very same source counter value.

If, however, a recursion looks at a wire whose reference ID is the same as the current source counter, it ignores it (since it's already been looked-at, or 'traced', to use the nomenclature of the offered solution).

This has the benefit of being compatible with the original code (with some modifications) but also solves the problem about each power source not travelling the correct distance.

Thanks a bunch for your help, guys, it's been invaluable!

16  Game Development / Newbie & Debugging Questions / *SOLVED* Stuck in recursion hell! on: 2014-08-27 20:33:02
Hi All!

This one has been foxing me for a while now - I'm convinced I'm missing something obvious.

I've written a little 'electric wiring' game (not realistic, I should point out!) where you can drop down a 'power generation' node, and connect wires to it on a grid.

This is a good example of how it's laid out:

Click to Play


The power generation node in the top-left corner of the grid can supply power for up to 6 cells distance. You can see that the green lines represent wires that are 'on', and the pink ones represent wires that are 'off' (sorry, you need mega-vision to see these at the moment).

To calculate the wires that get affected by this, I use the following code, seeding the function with the location of the power source first (0,0 - in my example image):

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
   // ~ ----- The bit that sets up the wire map and prepares it for being 'solved' ----- ~

   // global props
   private final int MAX_POWER_TRAVEL = 6;
   private int CURRENT_RECURSION_OPS = 0;

   // turn 'off' all wiring prior to solving the current power distribution
   turnOffAllWires();

   // solve the wiring map
   for (PowerSource p : powerSources)
   {
       CURRENT_RECURSION_OPS = 0;
       calcNextWireNode(p.x, p.y, 0);
       System.out.println("Calculated power source in " + CURRENT_RECURSION_OPS + " operations");
   }


   // ~ ----- Elsewhere in the class, this method provides the recursive means to solve the wiring map ----- ~

   private void calcNextWireNode(int x, int y, int depth)
   {
      // if we've hit our maximum recursion (distance) depth, finish here
      if (depth >= MAX_POWER_TRAVEL) return;
     
      // if we're not in bounds, finish here
      if (!tileInBounds(x, y)) return;
     
      // if this tile isn't a valid wire type, finish here
      if (wireMap[x][y] == WireType.NONE) return;
     
      // don't process this wire if it's already on
      if (isWireOn(wireMap[x][y])) return;
     
      // turn 'on' this wire
      wireMap[x][y] = onlineWireForType(wireMap[x][y]);
     
      // increase the depth
      depth++;
     
      CURRENT_RECURSION_OPS++;    // how many (global) recursion calls we've made to solve the wiring map
     
      // test the four spaces around this tile
      calcNextWireNode(x-1, y, depth);
      calcNextWireNode(x+1, y, depth);
      calcNextWireNode(x, y-1, depth);
      calcNextWireNode(x, y+1, depth);
   }


This code works nicely enough. Especially so since it doesn't break or endlessly loop when the wiring is set up like this:

Click to Play


In the image above, there are loops - but in the recursion, a node checks to see if itself is 'on', and skips it.

However, when adding another power source to the network, it doesn't distribute properly - it should exhibit the same spread amount as the original power source. This is what it looks like in its 'broken' state:

Click to Play


You can see that the second power source doesn't spread for all 6 cells. It SHOULD look like this:

Click to Play


I know what's happening here - the second lot of recursion to happen (the second power source) looks at the cells around it which are already 'on', thus killing the recursion.

How do I get around this pickle of an issue? I need something robust enough to work with (potentially) tens, if not hundreds of power sources. I know that recursion, done right, can be very powerful - but this 'flood fill' method I've adapted seems troublesome!

Any advice would be greatly appreciated.

Thanks guys n' gals!
17  Game Development / Newbie & Debugging Questions / Re: Suggestions for a sound library to use for sound effects? on: 2014-06-13 22:12:22
Thanks! I'll give that a try!
My game lacks the necessary visceral 'pew pew' sounds to add the required fun-factor!
18  Game Development / Newbie & Debugging Questions / Suggestions for a sound library to use for sound effects? on: 2014-06-13 20:28:44
Hi all,

I've heard some musings that the default sound capabilities offered by Java aren't great. I'm currently using LWJGL and the Slick libs, and have pretty much completed my game now, but it doesn't have any sound!

What's everyone else using to deliver sound effects and music in their games? I'm capable enough to engineer the various blips and bloops I need, but just need some advice on what libraries best suit Java game developers!

Thanks all!
19  Game Development / Newbie & Debugging Questions / Re: Calculating probabilities - is this the right way? on: 2014-05-16 19:13:28
Okay, so this method is probably a bit ugly, but it works great:

I start by defining the probability of each cell type. For simplicity's sake, everything is a percentage, with the sum of all values adding up to 100:

1  
2  
3  
4  
int chanceForEmpty = 70;     // type 0
int chanceForBig = 10;       // type 1
int chanceForMedium = 15;    // type 2
int chanceForSmall = 5;      // type 3


Then I run a loop for each chance variable, adding it into a values array as many times as it's needed. This array will contain all of the chance values:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
// get the sum of all values
int valueSum = chanceForEmpty + chanceForBig + chanceForMedium + chanceForSmall;

// set a values look-up array with the same dimension
int[] values = new int[valueSum];

// add each chance value
int iteration = 0;
for (int i = 0; i < chanceForEmpty; i++) { values[iteration] = 0; iteration++; }    // 0 = EMPTY
for (int i = 0; i < chanceForBig; i++) { values[iteration] = 1; iteration++; }      // 1 = BIG
for (int i = 0; i < chanceForMedium; i++) { values[iteration] = 2; iteration++; }   // 2 = MEDIUM
for (int i = 0; i < chanceForSmall; i++) { values[iteration] = 3; iteration++; }    // 3 = SMALL


Now, when I want to get a random, weighted type for a particular cell, I can call up a random value in the look-up array, which provides the weighting / probabilities I need:

1  
2  
3  
Random rnd = new Random();
int index = rnd.nextInt(values.length);
int randomType = values[index];    // 0 = Empty, 1 = Big, 2 = Medium, 3 = Small


I know the more talented guys and gals out there think this is probably ugly. I accept that this is only really useful in situations where the resulting pre-computed look-up array is fairly small. Mine is only 100 elements in size, but much larger sets could have memory footprint issues. But go gentle, this is my first attempt at handling weighted random selection Smiley

There's also the fact that this is precomputed, so obviously there would be additional issues on massive sets whilst everything is being preloaded into the look-up array. But again, my array size is small enough to be fairly inconsequential.

Here's my summary of what I've learned from this experiment:

PROS:
- Probably the easiest-to-understand method of accomplishing this that I've reviewed thus far.
- Quick and easy to code from the ground-up
- Since everything is precomputed, on-the-fly random selection requires no more work that fetching a value from memory.

CONS:
- Probably an ugly way to solve this!
- Adding a new weighted value to the set requires a little bit of coding (new for loop)
- Requires some re-calculation of how it affects the probabilities of other items in the set
- Not suitable for massive datasets (potentially memory-hungry, requires pre-computation).

I hope someone else finds this useful.

Thanks everybody for your help on this today!
20  Game Development / Newbie & Debugging Questions / Re: Calculating probabilities - is this the right way? on: 2014-05-16 12:43:55
All of these methods are actually very good - I can already see, based on the examples, how they would solve my problem.

This would also remove the need for me to do any initial probability testing on the empty vs. something check, since that's accounted for in the probability weighting itself (where the largest probability is nothing and all subsequent probabilities represent discrete entities).

Thanks! This was really helpful!
21  Game Development / Newbie & Debugging Questions / Calculating probabilities - is this the right way? on: 2014-05-16 11:14:42
Hi All,

I'm trying to fill up a grid of cells with random objects, but certain objects need to have a higher chance of generating than others.

So, imagining you have a 5x5 grid of cells, I could say that I want 50% of the cells to be empty, and the other 50% to contain something (potentially).

I made a little diagram showing kind of how the distribution of values works:



Here's where I get confused.

When I write the code to determine whether or not a cell is empty or not, I can do something like this:

1  
2  
3  
4  
5  
6  
7  
int chanceForSomething = 50;

Random rnd = new Random();
if (rnd.nextInt(100) < chanceForSomething)
{
    // cell isn't empty, generate something here!
}


But what confuses me is how I then further determine what to generate, based on their individual chances of generating? Looking at the percentage graph above, I can see how the lower 50% could be broken up into their own percentages (20% becomes a 40% chance, 5% becomes 10% etc.). However, if I were to do a calculation like this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
int chanceForHuge = 40;
int chanceForLarge = 30;
int chanceForMedium = 10;
int chanceForSmall = 10;
int chanceForTiny = 10;

Random rnd = new Random();

int rndVal = rnd.nextInt(100);  // how does this distribute against the chance probabilities?


How do I work out what chance probability 'rndVal' matches? Am I thinking about this all wrong?

I want larger objects to spawn more frequently than smaller ones, so they should have a higher chance of being created. But I also need potential room to add more objects to this list of probabilities in future, without having to resort to 'baking' the percentage chance check with code like 'if (chance >= 5 && chance < 10) ...'. That seems like an unnecessarily 'dirty' way of handling this.

Any helpful insight into this would be greatly appreciated. Thanks!
22  Game Development / Newbie & Debugging Questions / Re: Upgrading movement to use acceleration / deceleration, rather than static values on: 2014-03-29 21:32:04
Thanks to you both for your helpful replies, I'll get onto trying these out!

Many thanks again Smiley
23  Game Development / Newbie & Debugging Questions / Upgrading movement to use acceleration / deceleration, rather than static values on: 2014-03-28 12:16:41
Hi all!

I'm pretty comfortable with camera movement so far:

1  
2  
3  
4  
5  
6  
7  
8  
9  
private void moveForward()
{
    float dist = (maxMoveSpeedInUnitsPerSecond / 1000) * Engine.DELTA;
    float addX = dist * Math.sin(Math.toRadians(camera.yaw));
    float addZ = dist * Math.cos(Math.toRadians(camera.yaw));

    camera.position.x += addX;
    camera.position.z += addZ;
}


However, this is a pretty linear way of moving around (a key press makes you instant move at your 'maximum speed').

I'd like to modify this set up to use some degree of acceleration (and deceleration). I'm not sure how to approach this concept, as I'm somewhat confused as to how acceleration / deceleration on both movement axes are combined (forward / reverse combined with strafing).

Any insights here would be most appreciated, thanks!
24  Game Development / Newbie & Debugging Questions / Gravity works great - steps, that's another issue! on: 2014-01-30 13:41:48
I'm having resolving an aesthetic issue with my 3D gravity calculations for player movement.

I have no problem calculating the effect of gravity on the player:

- Add a gravity coefficient to a vertical inertia value
- Test the new 'feet' position of the player against the current floor height
- If the player's feet go through the floor in the next update, 'snap' them to the floor's height and zero-out the vertical inertia

So far, so good. However, I want the player to be able to walk up onto floor heights that are higher than the current one. Stepping down already works (gravity takes care of that), but at the moment the player will simply 'snap' to the higher step height without any form of 'smoothing'.

I've seen many 3D games perform this 'step' smoothly - interpolating the player's vertical position between the lower and higher step point, without the interference of the gravity-vs-floor snapping code.

Does anybody have any suggestions of theory on how to overcome this? Currently the player will snap to the floor-heights without issue - it's the graduation between the two that is causing me consternation!

Thanks!
25  Game Development / Newbie & Debugging Questions / Re: Using a texture atlas with a display list? [SOLVED!] on: 2014-01-18 22:12:19
Whoops! Not any more Smiley
26  Game Development / Newbie & Debugging Questions / Re: Using a texture atlas with a display list? on: 2014-01-18 21:59:43
The solution:

I broke up the segment's geometry into two main components - the horizontal quads (floor / ceiling) and the wall quads (for both inner and upper / lower step walls).

Since the display list for each bit of geometry can only accommodate one set of texture coordinates, I decided to make a Geometry Atlas, which is just a fancy-pants way of saying that I mapped a texture atlas to a display list array.

So I know that my texture atlas contains 8 x 8 texture tiles:


Therefore, I know that I'll need an 8 x 8 array of display list handles (for a total of 64) - one for each uniquely textured quad.

All I do therefore, is run a loop that creates a new display list for each XY tile coordinate in the texture atlas - which contains the glBegin... glEnd instructions for creating a uniquely textured quad based on its respective XY texture tile.

At runtime, when I create the segments, I simply tell the Geometry Atlas to return me the right display list handle for whatever XY texture I need. The work done earlier on creating the lists make this a one-line call.

The result is a much faster scene render. The great thing is that this is still not fully optimised - I'm not running my line-of-sight code here, which will vastly speed up performance beyond what is shown here.

A video showing it running with this new code can be seen here:
http://www.youtube.com/watch?v=q4S664yizGo
27  Game Development / Newbie & Debugging Questions / Re: Using a texture atlas with a display list? on: 2014-01-18 21:52:07
I've finished implementing the changes - I'm really chuffed with the results.

I'm just uploading a video showing the performance improvement, and I'll write up a brief explanation of how I solved this in a moment.
28  Game Development / Newbie & Debugging Questions / Re: Using a texture atlas with a display list? on: 2014-01-18 21:07:33
zFollette, I've come up with a solution that was inspired by a comment you'd made on one of your threads.

I'm writing a GeometryAtlas that can take a texture atlas, and initialises itself into an array of display list handles, where each handle represents a quad UV mapped to specific sub-texture from the atlas.

The first part - creating an atlas to use for the single patch (one quad) wasn't too difficult. I'll have to extend this to the other parts of the Segment's geometry, but it shouldn't be too difficult.

I'll report my progress back here so that other people can learn from this as well.

Thanks for your help!
29  Game Development / Newbie & Debugging Questions / Re: Using a texture atlas with a display list? on: 2014-01-18 20:23:03
Would chunks be relevant for what I'm making? Obviously I'm not saying doing A is more correct than doing B, but I'd like to think that what I'm doing is much more lightweight than the typical 'voxel builder' type of game.

Consider this: the typical level in this game will look a little something like this layout:


That's a 50x50 region of space, subdivided into 1x1 individual XZ tiles. Each tile, or Segment, can have a variable floor / ceiling space (I guess a little bit like Doom's line-defs).

Breaking up this level into chunks seems like overkill.

Even textured, this region of geometry gives over 155 FPS - but obviously I want to improve this since I'm running this on a fairly modern iMac (last 3 years), and I want better legacy support.

As a final point, this is a worst case scenario - I have a line-of-sight algorithm (which is perfect for the corridor-style nature of this type of level design) which effectively culls 80-90% or more of the geometry on show. This will ease the load, but I will still have that nagging thought in the back of my head that I'm doing all of this in a really dirty way at the moment!
30  Game Development / Newbie & Debugging Questions / Re: Using a texture atlas with a display list? on: 2014-01-18 19:56:52
Thanks, zFollette.

This would mean, by extension, that I can't use just 4 display lists to generate the entire map's geometry - since you should be allowed to apply different textures to the walls / floors etc. Doing so would change textures for all geometry parts generated by that display list.

What a pickle Sad
Pages: [1] 2 3 4
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

PocketCrafter7 (12 views)
2014-11-28 16:25:35

PocketCrafter7 (7 views)
2014-11-28 16:25:09

PocketCrafter7 (8 views)
2014-11-28 16:24:29

toopeicgaming1999 (74 views)
2014-11-26 15:22:04

toopeicgaming1999 (63 views)
2014-11-26 15:20:36

toopeicgaming1999 (15 views)
2014-11-26 15:20:08

SHC (29 views)
2014-11-25 12:00:59

SHC (27 views)
2014-11-25 11:53:45

Norakomi (32 views)
2014-11-25 11:26:43

Gibbo3771 (27 views)
2014-11-24 19:59:16
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!