# Question
Title: How to check if a variable is an integer?
I'm going through my C++ book and have currently made a working Guess The Number game.

The game generates a random number based on current time, has the user input their guess, and then tells them whether it was too high, too low, or the correct number.

The game functions fine if you enter a number, but returns 'Too High' if you enter something that is not a number (such as a letter or punctuation). Not only does it return 'too high', but it also continually returns it.

I was wondering what I could do to check if the guess, as input by the user, is an integer and if it is not, to return 'Not a number. Guess again.'

Here is the code.

```
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0)); // seed the random number generator
    int theNumber = rand() % 100 + 1; // random number between 1 and 100
    int tries = 0, guess;

    cout << "\tWelcome to Guess My Number!\n\n";

    do
    {
        cout << "Enter a guess: ";
        cin >> guess;
        ++tries;

        if (guess > theNumber)
                cout << "Too high!\n\n";

        if (guess < theNumber)
                cout << "Too low!\n\n";

    } while (guess != theNumber);

    cout << "\nThat's it! You got it in " << tries << " guesses!\n";
    cout << "\nPress Enter to exit.\n";

    cin.ignore(cin.rdbuf()->in_avail() + 1);
    return 0;
}

```

# Answer
Easiest is to use stringstream and check if conversion to int succeeded (reached eof)

```
#include "sstream"

//your code

cout << "Enter a guess: ";

std::string str;
cin >> str;
std::istringstream iss(str);
iss >> guess ;
if (iss.eof() == false)
    std::cout << "its not int";

//cin >> guess;

```
> 2 votes

# Answer
You're using an int variable, and the input is going directly into that, so if the input is not an integer, C++ tries to convert it to one. The user, on the other hand, can enter any string (or char array, technically?), whether it's an integer, a decimal number, or not a number at all.

For each of those three options:

* If the input is an integer, things work as expected.
* If the input is a decimal number, everything after the decimal is just dropped and you're left with the whole number before it. For example, typing in 2.34 will place the number 2 in the variable.
* If the input is not a number, it looks like no change will be made to the variable. (I just had to run an experiment to test that.)

I recommend placing the input into a string variable, and then test if it's a number before converting it to an int for comparisons. As for how to check whether it's a number, I believe this has some good examples: How to determine if a string is a number with C++?

As an aside, since you did not initialize a value in the guess variable, if the user enters something other than a number, you will still have a junk value when the comparisons begin. See this quick example:
> 1 votes

# Answer
This StackOverflow question covers it already. One of the suggestions there is this:

> Use `strtol`, wrapping it inside a simple function to hide its complexity :
>
> ```
> inline bool isInteger(const std::string & s)
> {
>    if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false ;
>
>    char * p ;
>    strtol(s.c_str(), &p, 10) ;
>
>    return (*p == 0) ;
> }
>
> ```

(Source)

I recommend asking pure programming questions like this at that site instead of this one.
> -1 votes

# Answer
Use `sstringstream`.

Try this:

```
using namespace std

string String;
cin >> String;
istringstream iss(String);

```
> -1 votes

---
Tags: c++
---


# Question
Title: Object generation from an existing object in a game engine
To simplify, let's say in en engine I'm coding for a game, I have the Main class an Object class. In the Main class' update method, I loop through the array of all Objects in the game. I also have a pool in the Main class from where I can get and return Objects.

Main.update () { for (all Objects) { Object\[i\].update() } }

My question is what's a good way of creating new Objects from an existing object's update method?

Do I have to pass the Main class to the Objects? or make the Main a static class?

Also another question is how to handle object destruction where I return them to the unused pool.

Thanks in advanced.

# Answer
> 1 votes
The easiest way to plumb the connections is to create an intermediary class that all game objects know about, much like every program knows about the OS it's running in. This class is responsible for taking requests to create or destroy a game object and passing it onto your Main class.

This intermediate communications class can be one of several things: a singleton, static methods in the Main class, or a class that's created and whenever a game Object is created it gets a pointer. That last one is cleaner, but will add storage required for each game Object and if you have tens of thousands every little bit adds up.

For your case, a small engine, I prefer the static methods version because you don't have to store pointers and while the communications API is a singleton the class it's talking to is not. And there's a clear concept of lifetime.

The reason to separate a little class to handle communicating like this is to keep it simple for all your game Objects, and to keep your Main class from getting littered with a bunch of message logic.

Your Main class is running through all the game Objects, then when the loop is done the Main class then asks the intermediary class what it needs create and destroy and then it does.

The reason to gather up all the Object requests is that it's pretty bad to add and delete list elements while you're looping through that same list.

---
Tags: architecture, objects, haxe, object-pools
---


# Question
Title: Implement Displacement Mapping: Gaps along seams
I am implementing Displacement mapping using DirectX 11 with its new tessellation stages.
Diffuse map and displacement map are generated by xNormal.
The result after I applied displacement mapping is cracked so badly.

Then I realized the values in the texture along seams are not the same/continuous, so I just use diffuse texture as displacement map, and the diffuse color is all-red.

The result is better but still 1-pixel gap along the seams.
I was confused by the little gap, so I enlarged the colored-part in the texture using MS painter, then the gap disappeared!

Now I just don't understand where the problem is. Even if the value along seams from different part of the texture is the same (red in this case), there are still gaps on the result model.

Here are the result screenshots. (reputation too low to post multiple links!)
https://i.stack.imgur.com/AdSew.jpg

I tried all sample filter here(MSDN) but nothing helps.

What causes the gap? It will be better if the problem can be solved by just modifying texture instead of changing my code.

# Answer
> 0 votes
Try hard-coding a constant displacement value, such as 1.0. If you still get cracks when using a constant displacement then look at your displacement vectors. How are you calculating them? They need to be exactly, bit-for-bit, equal across the seams; any discrepancy in how they're calculated could lead to cracking. If you're using the vertex normal as a displacement vector, ensure that the normals in the mesh are exactly equal cross the seams.

Once you've gotten things working for a constant displacement value you can put back in the texture-based displacement, but you'll see cracks again. With irregularly shaped UV seams it's impossible in general to make the textures match up precisely across the seam (it can be done if the seam is perfectly horizontal or vertical in UV space and both sides of the seam are precisely the same length).

There are ways to fix the problem, but it requires building some extra vertex data and adding some code to the shader. The basic idea is to sample the displacement map on both sides of the seam, and interpolate the resulting displacement values smoothly across the seam so that there's no sharp discontinuity. A bit more detail can be found in the "My Tessellation Has Cracks" talk by Bryan Dudash, listed on this page.

---
Tags: graphics, textures, directx11
---


# Question
Title: Game does not exit when playAgain (char) is set to 'n'
I have a level system in place for my Guess the Numbers game. I give the user the option to play again after guessing correctly. If only one level is active (with the other 3 being commented out) then the game will exit if the user enters `n`.

However, with all of the levels in play, the user entering `n` when prompted just prompts the user to enter their next guess.

I have achieved this using four `do while` loops with `do /*stuff*/ while (playAgain == 'y' && level == x /*1 - 4*/)`

The full code is over here on Pastebin.

Here is a single `do while` loop, but they are the same throughout all of the loops

```
do
{

srand(time(0)); // seed the random number generator

int theNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0, guess;

    do
    {

        cout << "Enter a guess: ";

        string str;
        cin >> str;
        istringstream iss(str);
        iss >> guess ;
        if (iss.eof() == false)
            cout << "\n\nPlease enter only numbers.\n\n";
        else
        {

            ++tries;

            if (guess > theNumber)
            cout << "Too high!\n\n";

            if (guess < theNumber)
            cout << "Too low!\n\n";
        }

    } while (guess != theNumber);

cout << "\nThat's it! You got it in " << tries << " guesses!\n";

cout << "Play again? (y/n)\n";
cin >> playAgain;

} while (playAgain == 'y' && level == 1);

```

# Answer
> 0 votes
Your levels' do-while structures are placed sequentially.

This means that when a player chooses level 1, beats it, and decides that he/she is done, the game will automatically proceed to level 2.

Try placing:

```
cout << "Level X" << endl; // Where X is the level number

```

before the `srand(time(0));` in your levels' code and you'll see this in action.

If you want the player to view the level selection again instead, you must put that into a loop as well.

Hope this helps - good documentation by the way.

**Edit 1:**

First, what if your boss told you that this game should 100 different levels? How would you implement that?

You could copy and paste a bunch of times, or you could rework your solution. (Hint: Most of the time, copying and pasting your code is a sign that you could be using loops or functions)

The only thing that changes between your levels is the range that the number is chosen from. So, let's put those values into an array.

```
const int NUM_LEVELS = 4;
int levelRanges[NUM_LEVELS] = {100, 1000, 5000, 25000};

```

Now, instead of:

```
int theNumber = rand() % 100 + 1;

```

we have:

```
int theNumber = rand() % levelRanges[level-1] + 1;

```

When `level` changes, so will the range! Note that if the player inputs a level number that doesn't exist, bad things will happen. To solve this, make the user pick the level again or close the game when that happens.

```
if(level < 1 || level > NUM_LEVELS){
    // Make the user repick or close the game...
}

```

Here is the new program in full: http://pastebin.com/mNuS1sXA

---
Tags: c++
---


title: Handling Block Collisions

text:
# Question
Title: Handling Block Collisions
The title isn't great, but let me try and explain my problem. I'm working on a little game at the moment the gist of which is that you're an entity in this 2-D world and you have to dodge obstacles. These obstacles approach form all 4 directions and you're stuck in the middle and simply have to survive as long as you can without dying (from hitting the walls, obstacles, etc.) Right now, my problem is this:

The obstacles are randomly generated, so they often collide with obstacles coming from the other directions. I feel like something should happens when they collide, but I don't really know what to do with them. Ideally, I would have the blocks generate such that they never collide, however this as proven to be both mathematically and computationally difficult. I'd still like to get this to happen if possible (if you have any clever tricks let me know) but I'm willing to consider other ideas as well. One thing that sounded cool to me was that upon collision, and explosion happens that abruptly shoves your entity away from the collision and deals a little damage. Conversely, a "black hole" could form and suck you towards the collision possibly dragging you into oncoming obstacles, etc. The problem I have with both of these ideas is that they're random. So there's no guarantee that it'll be consistent between play throughs. Seeing as they could potentially deal damage to the entity, it seems unfair. One person could have a significantly easier time than another because there were no collisions. Am I right to have these concerns? Or does the randomness add to the fun of things? Any ideas on how I could fairly handle such collisions?

Thanks!

# Answer
> 2 votes
If you approximate the obstacles with bounding spheres, then testing a new obstacle to see if it might collide with any existing obstacle is not too hard. http://twobitcoder.blogspot.co.uk/2010/04/circle-collision-detection.html explains the process well.

All you need to add on to that is some tests to make sure the position at the collision time (if there is one) is inside the play area.

As for determining which option is most fun, I'd suggest implementing each option and trying them, although in general I'd say that giving random numbers too much influence on how well the player does is usually a bad idea - you want the player to feel they have control over how well they do.

# Answer
> 2 votes
Totaly agree with Adam.

Randomness make experience much brighter, but it must me balanced with skill-challenge very nicely, across tons of testing and recalculating.

Naturaly, even skilled player should think like "Yeah, i can handle this" in first few minutes (or longer, depends on your planned gamesession time). But after this, he get in some random event he didn't expect, and both endings (win or lose) are good, like "wow, that was tough, but i realy rule in this game" or "omg, i've seen that, but it was so hard to win here. i think, i should try to do this again", but not too often too. And yeah, if this randomness will happen to often, this will lead to something like "okay, it's all challenge this game can give. boooring!" or "c'mon! i can't handle anything, this game just kick me in *** all the time! i will look for something else now".

Also, not so close to question, but it realy matters how your game behave itself with player. If it's not the main plan of your design, then better your game to be "kind" - don't punish player everytime he does mistakes. So - black holes? Ok, but don't punish your player too much with them. Give him a chance once a session (or a random chance, lol) to fix his mistakes, to try to play harder without "death", without need to restart. Maybe health regen (hello, CoD:MW), or maybe chance to gather enough points for new "heart/life" in health bar in this one session

It looks like a great idea - different results for same "collision" event. It should add some "various gameplay" experience on only one event, which is good - simplier the gameplay - better.

---
Tags: game-design, random, collision-avoidance
---


title: Collision avoidance (AI)

text:
# Question
Title: Collision avoidance (AI)
Now my 3D model has complete AI behaviours, but my model has no collision avoidance while he is moving towards the player! Because of this, he gets stuck in front of 3D blocks sometimes.

I think the solution includes the usage of rays. I've included a picture of what I want to do.

NOTE: The world is a 3D world, not a 2D one. (Even though they are almost the same)

I want my model to not collide with the boxes while he is moving towards me, i.e make some collision avoidance. :)

# Answer
A couple people have mentioned pathfinding, but that's only necessary for complex paths, like navigating a maze. Your situation just calls for basic obstacle avoidance so full fledged pathfinding is overkill (plus you often need obstacle avoidance in addition when doing pathfinding anyway). Look on this page for some great examples of steering behavior: http://www.red3d.com/cwr/steer/

In the list of demos you'll notice "Obstacle Avoidance". All you need to do is that, plus make your AI tend to turn toward the player when no obstacle is in the way. The site may have sample code to look at, but simply reading the description is probably gonna help you the most http://www.red3d.com/cwr/steer/Obstacle.html

In essence all it's doing is a box intersection check ahead of the moving entity (a raycast with a wide radius would do too) and if another object is intersected then the entity turns.
> 3 votes

---
Tags: xna-4.0, ai, geometry
---


# Question
Title: How to change something inside an switch statement?
So my question is how would you draw a list of strings, and then if a case of the enum is a certain way, then draw them a different way? Here is an example of what I mean:

```
enum CurrentState
{
    Menu1,
    SubMenu1,
    SubMenu2
}
private CurrentState _currentState = CurrentState.Menu1;
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
    //Draw list here so it is always displayed in all cases
    switch (_currentState)
    {
        case CurrentState.Menu1:
        {
            //How would you erase the previous list and draw it in a different way here?
        } break;
        case CurrentState.SubMenu1:
        {
            //How would you erase the previous list and draw it in a different way here?
        } break;
        case CurrentState.SubMenu2:
        {
            //How would you erase the previous list and draw it in a different way here?
        } break;
    }
}

```

# Answer
> 4 votes
**Don't draw the default list first**. If you want an "in all cases" use `default` as part of the `switch` functionality. The `default` case is triggered whenever none of the cases match.

```
switch (_currentState)
{
    case CurrentState.Menu1:
    {
        //Draw menu1
    } break;

    case CurrentState.SubMenu1:
    {
        //Draw submenu1
    } break;

    case CurrentState.SubMenu2:
    {
        //Draw submenu2
    } break;

    default:
    {
       //Draw list here so it is always displayed in all cases
    }
}

```

---
Tags: xna, c#, menu
---


title: Has Java 3D changed much since 2005?

text:
# Question
Title: Has Java 3D changed much since 2005?
I'm thinking of picking up the book called *"Killer Game Programming"* by *Andrew Davidson*, but its pretty old, now. I know Java, and I've been messing with jMonkeyEngine for a few days, but I'm curious to see if I would benefit from the 3D chapters of this book.

The book was published was in 2005. Has Java changed to the point where this book would now be obsolete, assuming it was up to date at time of publication?

# Answer
> 4 votes
A better question might be: why are there no new books on Java game programming? Java got pushed out of the in-browser experience by Flash and was never able to steal away C++ game developers in a big way. Nevertheless, Minecraft is completely fun. Both those books convey design principles that are applicable to any language or environment and the hand holding is not overbearing. Reading them will not instill any bad habits in you, so I say go for it.

# Answer
> 4 votes
You can actually find a number of the chapters for free at the book's website.

Java 3D was a neat API, but has since been "put on hold" in January 2008. It's not looking good, 3 years later and with no apparent progress towards starting up again. I would probably recommend looking into JMonkeyEngine or LWJGL instead (the former being closer to Java 3D, with a scene graph, while LWJGL is OpenGL in Java so it'd be more low-level).

Also it's extremely unfortunate that Java 3D is/was hosted at java.sun.com because the Oracle acquisition messed up some of the webpages. For example, many of the links at the Wikipedia article for Java 3D are now broken thanks to Oracle. So hopefully you will be able to get to all the downloads and documentation you need; but you might want to check now, before you buy the book!

Personally, I found Java 3D to be rather neat. I didn't do much with it, but I did buy this book and another about Java 3D in an attempt to learn it. It seems to be a well-made API with similar goals to Java (cross-platform - working on all machine, screen, etc. configurations).

One last note: there was one Java 3D game I knew of, called Magicosm (later renamed to Cosm). I was excited about it! But, well, you can read the story on that page. Still, archive.org has a copy of the old website which explained all the game ideas and progress of the game. So it appears that it is definitely possible to make a game in Java 3D.

# Answer
> 3 votes
It might be a good foundation and it discusses concepts that are not often discussed in context of Java. If you follow the author's work you'll be impressed with what he has gone on to do with Java and Computer Vision (CV).

You can get some older and unpublished chapters to Killer games here. Also the code from the book is there too.

He has also gone on to do some interactive gaming with Kinect and has written a lot about it.

# Answer
> 2 votes
> Has Java changed to the point where this book is now obsolete?

Never, apart from few changes in the JDK, it is nowhere near the word "obsolete".

IMHO, its always better if you know about the old technology and how it evolved well in hand before you start learning the new technology.

# Answer
> -1 votes
You may want to learn javascript and webgl instead. Combined with HTML5 that will allow you to develop platform-independent games for mobile and computer.

It doesn't really answer your question, but it might be better for you.

---
Tags: java
---


# Question
Title: Why should I choose to design a health bar rather than heart containers?
When designing any hero-based game, be it adventure, RPG, brawler, or similar, you eventually need to decide on your health system. Barring any regenerative systems with zero UI (like Call of Duty), should you use a discrete set of heart containers, Zelda-style, or a continuous health bar, like Street Fighter?

Here are some points of contention that I've been thinking about:

* Hearts are easier to understand (very clear how many hits you can take)
* Hearts give a better sense of accomplishment when expanding (A whole extra heart! Rather than just a slightly longer bar (or worse, no change))
* Hearts grow to take up a lot of screen real-estate, while health bars can stay compact
* Health bars allow for really fine control over health/damage balancing (using `float` rather than `int`)

Since I haven't been able to find any relevant game design articles on the subject, I'd really appreciate if everyone with some knowledge on the matter, or even just some insightful links would contribute, thanks!

# Answer
> 23 votes
Most answers have addressed the feasibility of using heart container systems, I'd like to present a reason why you would want to use them over a health bar.

Here's a word for you: Subitizing. People can make near-immediate judgments about the number of items in a group if you keep that number round about 4. Once you go above that point confidence and speed declines drastically.

Consider this example of having 5 HP and taking a 1 HP hit:

With the heart containers I am immediately sure I can take exactly 3 more hits and the 4th will kill me. With the health bar, it is 4 or 5? I'm not as certain.

This is a useful concept to take advantage of if the number of hits your character can take maxes out at a fairly low number (10 -12) and it is important for the player to be able to quickly and confidently know how many more hits they can take.

# Answer
> 18 votes
If the health can grow significantly over the course of the game, I think that health bars are more appropriate.

For example, in my current mmo game, the characters starts with 300 health, but that health can grow to over 3000 as the player levels. If this were implemented as hearts, it means you might start with one heart but have 10 or more hearts later on. This would either take up a lot of room that could be used otherwise, or the hearts would be so small that the health would be hard to read.

Also, if the player starts with one heart of health, it will be very hard differentiate between 10%, 25%, 50%, etc levels of health. Having a bar of health gives a consistent measure of health as a percent throughout the whole game, i.e. 50% health is always halfway down on the bar.

# Answer
> 17 votes
Why not do both? You can have a health bar divided on discrete intervals. That has a lot of the advantages of both systems:

* You can make health increases be always an extra block.
* After you get hit, you know how much of a block an attack takes and it's easier to measure how many hits you can take.
* You can choose whether to make the bar longer or the blocks smaller when health increases, depending on how much of the screen you are willing to use on showing the player's health.
* You have the same fine control of health as you get with health bars.

League of Legends does this, and that's a game where current health is really important.

You should however consider the aesthethic difference between heart containers and a health bar. In my opinion, the bar puts the player a lot closer to the mechanics of the game, while the hearts emphasize the fact that this is the life of the character you are showing. Hearts have a lot of meaning attached to them, and you can use this on your favor for some kinds of games.

# Answer
> 4 votes
pauld's answer already points out that a simple heart container system may not scale if the maximum health in the end-game differs by orders of magnitude compared to what you originally start with. But there are two ways to fix this:

* Just like with money where you have e.g. gold, silver and bronze coins with a 1:10 or 1:100 scale, introduce a multi-digit system. You could e.g. use three rows of ten hearts, where the topmost row represents the hundreds, the second the tens and the bottom one the ones. Or use a different icon that represents a tenth of a heart, e.g. a drop of blood
* Scale armor instead of insanely vast amounts of heart containers. When you progress, enemies that used to attack you for half of your hearts only cost one heart or later on only tickle. (That's probably preferable if you want to have a more credible experience)

# Answer
> 2 votes
I've always preferred the heart system. I feel like it ties into health better, whereas a health bar abstracts damage and doesn't give you any believable relation to damage. All damage results in critical failure at the 0 point.

To give you an idea of what I mean, I really liked the Assassin's Creed health style (from the 2 line). You could regenerate the last partial health block. Health blocks had a discrete 4 hit damage. And damage was reduced by armor.

Not only that, but armor was health, and any "damage" to armor resulted in a max-health penalty. Any "potions" you take was limited by armor damage that had to be repaired.

The new system in Assassin's Creed 3 takes all that away and replaces it with a health bar, and while that gives more control over the health, it replaces the believable system of damage with a critical failure.

In 2, you could get damaged down to 1 health and keep regenerating it and keep fighting through a lot of pain, the extra health that didn't regen was more like a failure buffer than a real health.

I liked this. I felt that it let me survive a lot more than health alone, but gave me an even more suspenseful feeling at one health block left than in 3 where it regens out of combat and I start at full health instantly.

It also limits you from being a infinitely growing system (like most MMOs) because you can keep "improving". This turns out to be a lie, because monsters simply scale in damage to where in reality actual health number is irrelevant. I personally think this needs to die. **I feel this is an intellectually lazy, and gameplay cheap system. That cheats the player out of a better experience.** One of my favorite MMOs is the Guild Wars line, because improvement isn't a measurement of levels, but skill-based (both player skills and actual activated skills). They cleverly made end-game improvement a hunt for skills. To apply this to WoW would be similar to having an ever expanding list of dropped skills, glyphs, and talent options. To apply this to Diablo 3, would be to have the standard list of runes be level-based, but then have dropped "elite" runes like Diablo 2.

So a recap:

In the 2 line:

* Armor equated resistance to damage and max health. If damaged it reduced max health, and had to be repaired.
* You were allowed to easily regenerate partial blocks.
* Higher suspense at 1 block left, becuase even though with careful planning you could live through infinite damage, you couldn't take a lot in one blow.
* More believable roleplay because of a need system (repair, potions, etc.)
* Limiting max health requires more focus on gameplay mechanics instead of just "moar damage, moar health", and requires a more fun endgame play than just rerun raid X for 1

None of this could be adequately represented with a health bar. And I think the health bar has lowered creativity and believable in lieu of easier maintenance.

**A big thing to remember is that if healing mechanics are health-percentage based and not health amount, then a floating-point health is really no different than a fixed health with more damage resistance.**

# Answer
> 2 votes
1. Hearts are cute. Binding of Isaac also used hearts.
2. Hearts go in wholes, or halves. If I remember correctly, the only thing that did less than half a heart of damage in Zelda was the Peahat. 1/4 heart damage didn't show up though.
3. Don't forget that games like Doom just used **raw numbers** (100% etc)
4. Diablo and Ultima Underworld used "potions", which are like themed health-bars.

In games like streetfighter, there were so many different attacks, the discretization imposed by hearts was probably not useful. Punch, kick, uppercut.. all *slightly different* amounts of damage. A more *continuous looking* thing like a health bar seems more appropriate there. Plus, hearts would probably be too cutesy.

# Answer
> 1 votes
It depends of the actual value you are abstracting. A value that starts in 3 and go up to 20 is easy to represent as hearth containers, but if the value represented can vary a lot over time or from one character to another (where applicable), then a percentage based health bar will be easier to represent and read.

Trying to represent a value like 112/435 in hearth containers would be hard to read or innacurate.

# Answer
> 1 votes
The only time you would need to subtract tiny amounts of health would be continuously-damaging terrain such as walking on hot coals or running through toxic fumes, in which case you could just a timer to subtract a quarter of a heart per second.

It shouldn't take too much screen space. If the player is expected to take 100 hearts-worth of hits between chances to recover, there's a problem with your game design. Also, you can use tricks like Zelda's heart-doubler to reduce the quantity of hearts.

Generally, the heart system seems to work better for third-person adventure games while small healthbars are better for third-person games like shooters (In these types of games, you could even hide the healthbar completely except when taking damage)

If you do need a really long healthbar, you could combine two ideas and do what Metroid Prime did: have each upgrade earn you a new healthbar, and display the current healthbar and the number of remaining healthbars on-screen.

# Answer
> 1 votes
It all depends on what kind of game are you making and what is the target audience. Games like World of Warcraft would never work with heart system, because it is all about numbers. People dedicate their free time to discover health formulas etc. Console RPGs work best with hearts. Console games usually hide as much of the game mechanics from players as possible. So it's realy upto you:

1. **You want a game that will be simple**, you mostly rely on the story. Hide most of mechanics from the player. Don't show hits as numbers, but simply one hit = one heart. You will probably not show the player any other stats neither. No strength/dexterity/intelligence. Just inventory. Items have no stats, maybe just special attacks etc. Your audience will be casual players, console players, younger children. **Use hearts.**
2. **You want a game for people who like D&D.** You show them stats, you let them design the character by rolling dice/assigning points. Every item will have many stats, and no good player will be able to live without excel spreadsheet. **Health bars or pure numbers.**

---

> Hearts are easier to understand (very clear how many hits you can take)

Only if one hit = one heart every time. For me understanding health bar is no issue - of course I don't know how much exactly I have, but I'd say to myself: *Oh noes! It looks like I am under quarter health, better to drink that potion!*

> Hearts give a better sense of accomplishment when expanding (A whole extra heart! Rather than just a slightly longer bar (or worse, no change))

No, a proper level up gives me a sense of accomplishment.

> Hearts grow to take up a lot of screen real-estate, while health bars can stay compact

See above

> Health bars allow for really fine control over health/damage balancing (using float rather than int)

Well, half hearts, quarter hearts... Again, it depends on how do you calculate damage. One hit = one heart, then no need for health bar.

---
Tags: game-design, gui, ui-design
---


# Question
Title: Best practice to use Sprites in a game using AndEngine GLES2
Currently I am having static reference to all my sprites and loading and initializing them in my OnCreateResource mthod of SimpleBaseGameActivity, But now I have to override onAreaTouched listener on spirtes and the way I can override it while Initializing the Sprite. But I have a static method creating Atlas and Texture Region for every sprite. And I am using these sprites in my scene class and I want to override onAreaTouched there. I can registerTouchArea for that specific sprite in my scene so that can be done But I want to Override OnAreaTouched in a way so that Code reusability can be done. Here is how I am currently creating and loading sprites.

```
defualtCageSprite = createAndLoadSimpleSprite("bg.png", this, 450, 444);

```

And this is my Method createAndLoadSimpleSprite.

```
public static Sprite createAndLoadSimpleSprite(String name,
    SimpleBaseGameActivity activity, int width, int height) {

BitmapTextureAtlas atlasForBGSprite = new BitmapTextureAtlas(
        activity.getTextureManager(), width, height);
TextureRegion backgroundSpriteTextureRegion = BitmapTextureAtlasTextureRegionFactory
        .createFromAsset(atlasForBGSprite, activity, name, 0, 0);
Sprite sprite = new Sprite(0, 0, backgroundSpriteTextureRegion,
        activity.getVertexBufferObjectManager());
activity.getTextureManager().loadTexture(atlasForBGSprite);

return sprite;

```

}
Now How Can I override onAreaTouched for some sprites while not losing the code reusability.

# Answer
> 1 votes
You should definitely detach creation of `Sprite` and `Texture`. Unless you are working with strictly 1:1 ratio - each sprite you create has different texture - and you create all your sprites and the beginning. The operation to load the texture from file to memory is resource intensive. The operation to assign texture to a sprite is almost free.

Therefore you should create textures only once at the start, before any sprites are created in some "loading" phase. Then create the sprites. You can have specialized sprites, like "BulletSprite" that will always show the same texture, so you don't have to pass it in constructor.

Instead of using createAndLoadSimpleSprite, consider implementing a sprite factory using this pattern: http://en.wikipedia.org/wiki/Factory\_method\_pattern

The best practice is always to load all textures first, then create sprites. Usually you will have more sprites sharing a texture. Drawing a Sprite is just an instruction - draw this texture there. In fact, textures are stored in completely separate memory, they are not stored on Java heap.

---
Tags: java, android, sprites, andengine, opengl-es2
---


# Question
Title: How does the Goomba know it has been jumped on?
I'm developing a 2D tile game engine in LibGDX and I'm asking myself how to structure the whole thing. One of the key questions right now is how to implement Player-Tile interaction similar to this particular example:

https://www.youtube.com/watch?v=Yyv5Tt5iUFc (only first seconds relevant)

We see a Player instance, a switch on a tile and something that reacts to the switch being pressed (the Door).

Basically my question is: What is this switch in "solution space"/Java OOP Terms? How to implement it? How to let it interact with the player?

I thought a lot and used Google for several hours but still didn't find any sufficient answer. Maybe I was searching with wrong words or fiddling through bad sources but I found a working solution to the problem myself which I am not very proud of since it seems stupid to me:

The map is made up of tiles where each cell has it's own properties (you can do that easily in Tiled). One of these properties is called "material". Each cell has a position in tile units and since one cell is 16x16 pixels it's position in pixels is tile units\*16.

If the cell's property material value is eg. "SWITCH" then there has to exist another property which other cell this switch will manipulate if stepped on. If the cell's property material value is "DOOR" there exists another property where this door will lead to. These tiles are called *EventTiles*.

An EventTile is an Object that holds attributes like position, alive (for animation purposes), steppedOn, animation sprites etc. and methods like update() which basically does something with this EventTile like checking whether it's alive should be set to false and a method called init() which initializes particular attributes of a EvenTile instance. Given this information a maploader creates a **HashMap** of **Pools** of **Eventtiles** (since as you can see in the video switches do have different textures, animation durations than doors etc.). The keys in the HashMap are the different materials. The value for a material key is the Pool of material objects or more precise the Pool of EventTile instances. They can be created or deleted (aka alive set to false) on the fly by my Pool object. In the maploading process particular EventTile instances for e.g. SWITCH will be put in the pool with it's according positions measured in pixel units. So right now for a given map we have a given amount of SWITCH EventTiles in the pool, each living on it's own in the pool.

Why am I using a pool? Because there are other materials like SAND which basically aren't events itself but have to use animations since when the player steps on sand and moves away player has to leave footprints on the sand and by time these footprints have to fade away themselves. I thought the only way to make these work is by creating new footstep EventTiles with own animations etc. and returning them to the pool once they are faded away and since I don't want GC to work all the time I'd rather have something like 12 footstep EventTiles ready for init.

The player position is measured in pixel units. Each time player.move() is called the last thing itself does is to get the property "material" of the cell the player is currently standing at and saving it to a attribute/variable player.onMaterial. So only the player knows which material it stands on. In my opinion this is a **flawed** principle but I will explain this later on.

Next, the level/world class, where the tiled map and the player are living instances of each particular class, is basically doing a call on the player to hand out the information about which material player stands on and handing out player position. With these informations the code in level goes through a torrent of if-statements how to handle this particular situation.

So, if player is standing on material "SWITCH" the HashMap get's the key "SWITCH" and returns the pool of switches. Then the position of each switch in the pool is compared to the player position. If they are equal the react() method of the particular switch EventTile instance is called and action performed (like opening a Door). This again is bad style in my opinion.

Why? Because not the switch itself reacts to player input but rather level polling every update() call whether or not the player is standing on the switch. Of course, player doesn't have to know that he stands on the switch or rather "SWITCH" material and I could have let each switch instance in the pool perform regulary *switch*.update() and ask the level (or the player) for player position and then if player.pos == switch.pos switch would itself
perform the action but then again using the pool is useless. Take the SAND material: Currently my map has about 120 sand tiles, given the other proposed approach there would be 2 times 120 SAND EventTile instances (my player is walking like a human being, so left foot follows right foot follows left foot..., each instance is for a different foot) which ask EVERY LEVEL.UPDATE() whether or not they have been stepped on. It's like letting a JButton poll if it has been pressed all the time instead having it being add as an EventListener.

Why not using EventListeners? Since using Threads here is not an option. The SNES didn't have threads either and they could still handle the switches correctly.

I think in complexity terms this is the same problem like in Super Mario Bros whether the Goomba knows it has been jumped on or the world is just comparing Marios Rectangle to each Goomba Rectangle, hence the title.

# Answer
> 2 votes
When checking if a goomba is stepped on, instead search the area around the player for a goomba rather than poll all goombas (so get each goombas x and y co-ords and compare to player co-ords). Then check these nearby goombas with a normal collision check.

Also you should set up a spawn routine that de-spawn goombas that are out of the view space and put them back in when the player moves into view range for even better efficiency.

---
Tags: java, libgdx
---


# Question
Title: Fuzzy State Logic or Finite State Machine for AI
My question is regarding the use of fuzzy state logic and finite state machine with AI. What I would like to know is what the key benefits are for both and also some examples of situations where you might want to use a particular state machine. My main areas of interest are the questions the follow.

Which is better for group AI? Which is better for individual AI? Which is more efficient?

Also some links to any demos of each that exist would be really cool!

Thank you all who answer/comment!

# Answer
I don't have an answer to your specific question, mostly because I don't believe there is an answer. The simplest application of fuzzy logic in an FSM would be allowing multiple states, rather than a single state, and using probability to determine behavior.

In this light, it's a question of whether or not an extra level of AI sophistication is appropriate. Simpler applications can suffice at times, while more sophistication in architectures provide enhanced perceived intelligence at the cost of complexity (in coding, debugging, design).

Allowing multiple states of an FSM which are executed randomly would allow for more seemingly random, yet still reasonable and "intelligent", behavior. This would have the result of seeming more human, as humans often seem random and "unpredictable".

For an individual agent, the agent might seem to do something less obvious, making it seem "foolish" or "unpredicable" or even "unexpectedly clever" depending on the situation. For groups of agents, fuzzy states might lend players to perceive the groups as "disorganized", or "unable to agree", etc.

Again, though, it's less "Which is better for individuals/groups?" and more "What level of sophistication of AI is appropriate for my game?"
> 7 votes

---
Tags: ai, state, fsm, game-theory, fuzzy-logic
---


# Question
Title: Android Action_Move when moving between specific screen areas
OK so I know how to iterate through the different pointers that are currently touching the screen so I know what the coordinates are of these pointers using the following:

**Code snippet**

```
case MotionEvent.ACTION_MOVE:{

    //Count through all the pointers currently touching the screen
    for(int index=0; index<event.getPointerCount(); index++) {

     //Is finger on the left button? If so, then go (or continue going) left
    if (event.getY(index) > renderer.leftButton("top") && event.getX(index)<renderer.leftButton("right")){
                renderer.setSpritewState('l', true);
                renderer.setSpriteState('r', false);}

 //Or is finger on the right button? If so, then go (or continue going) right
            else if (event.getY(index)>renderer.rightButton("top") && event.getX(index)>renderer.rightButton("left") && event.getX(index)<renderer.rightButton("right")){
                renderer.setSpriteState('l', false);
                renderer.setSpriteState('r', true);}
            }
            break;

}

```

However, this is constantly triggering one of the two conditions I guess as it's picking up minute movement of the finger/s. And, more importantly, if there is a finger on each 'button' - the sprite goes a bit crazy as each condition fights with the other and constantly flags the sprite to move left and then right etc.

What I'm really after is this something like this:

So, if a finger moves *within* a specified area, nothing happens as it's counter-productive. But if a finger moves from one area to another, then the action is triggered.

I'm guessing the code for this would need to save the old position of each of the fingers to compare to the new positions, but I'm not really sure how to go about this. Help would be appreciated. Thanks.

# Answer
You can specify the areas by a simple integer (for now). Area A would have index 1, and area B index 2.

You will store the last 'tapped' area in a variable. When the finger is released, and the 'released' - where the pointer up event triggered - area is different than the 'tapped' one, you trigger the action.

If you want to know when the touch left a specific area, then you'll need to have a list of Rectangles with the respective areas. Just do a simple `Contains` check to see if the moved point is inside the same area where it 'tapped' the first time.

Something like this (pseudocode):

```
// somewhere globally/locally
var initialArea = -1

...

var list = new list({0,0,20,30}, {20, 0, 20, 30}) // the rectangles list
if (event(tap) && initialArea == -1)
    initialArea = findArea(list, new point(tap.x, tap.y))

if (event(release_pointer))
    initialArea = -1; // no area at the moment

if (event(pointer_move) && initialArea != -1)
    currentArea = findArea(list, new point(tap.x, tap.y))
    if (currentArea != initialArea)
        // trigger action!
        initialArea = currentArea // prevent multiple firings.

```
> 1 votes

---
Tags: android, movement, touch, controllers, multitouch
---


# Question
Title: Dynamically editing a movieclip at runtime
I am trying to make a flash game(actionScript-3 if it matters) to test what I learned so far. And, in the game, I want to make the character(a robot?) customizable. The first solution I found was to edit the character movieclip directy. Is it possible to edit a movieclip at runtime? If yes, how?

# Answer
> 2 votes
Try using multiple movieclips (for the head, body, legs etc). That way you can switch them out easily. Put them together in a Sprite container.

---
Tags: 2d, flash, actionscript-3, game-mechanics
---


# Question
Title: 3ds Max error dialog: "Instancing not supported for this action"
"Instancing not supported for this action” is the dialog I get. My favorite part is that, according to google and yahoo, apparently i am the only person in the history of mankind to experience these words together in this order, let along get this message from Max. Thanks, autodesk, for putting this dialog in special for me!

So I’ve created my model (nws) and was setting up a Skin Wrap. Selected "Face Deformation", added the base-skin for weight, checked “weight all points”. . . clicked “convert to skin” and got that dialog.

My model doesn’t have a whole lot of elements to it, I had a left and right appendage that came from a base model (skyrim). so, i did a clone\>copy of all 3 of my elements, just to be sure nothing was instanced… and VOILA! Same error message. the only other elements are an imported NIF mesh and skeleton.

Any idea where this is coming from or how I can make it go away so that I can export my mesh?

# Answer
You probably solved this already, but for anyone who encounters this problem. It is because you applied the skin wrap to more than one object at a time. Convert to skin does not support this, so you'd need to do it for every object individually.
> 1 votes

---
Tags: 3dsmax
---


# Question
Title: How can I access bitmaps created in another activity?
I am currently loading my game bitmaps when the user presses 'start' in my animated splash screen activity (the first / launch activity) and the app progresses from my this activity to the main game activity,

This is causing choppy animation in the splashscreen while it loads/creates the bitmaps for the new activity.

I've been told that I should load all my bitmaps in one go at the very beginning.

However, I can't work out how to do this - could anyone please point me in the right direction?

I have 2 activities, a splash screen and the main game. Each consist of a class that extends activity and a class that extends `SurfaceView` (with an inner class for the rendering / logic updating).

So, for example at the moment I am creating my bitmaps in the constructor of my `SurfaceView` class like so:

```
public class OptionsScreen extends SurfaceView implements
  SurfaceHolder.Callback {

      //Create variables here

 public OptionsScreen(Context context) {

Create bitmaps here
}

public void intialise(){                         //This method is called from onCreate() of corresponding application context

// Create scaled bitmaps here (from bitmaps previously created)

}

```

# Answer
Never do massive loading of resources all at once on the GUI thread - that's a certain approach to getting choppiness.

Making sure that your app can access your bitmaps from any activity is not difficult; simply set up a Singleton class that handles your bitmaps. You can use the Application class as Jay suggests, but personally I'd build an own singleton class for such activities as I don't feel that the Application class is the right place for such data.

I have open-sourced my own implementation of an ImageHandler for Android bitmaps in https://github.com/micabyte/android\_game

See com.micabyte.android.graphics.ImageHandler

I've not implemented background loading in the ImageHandler (never needed it for the small bitmaps that I load via the ImageHandler, but you can check the SurfaceView implementation also in that project for how I handle loading a very large bitmap of 4096x4096 for game maps).
> 1 votes

# Answer
As RobCurr has mentioned, it's probably best to only load the necessary resources during the splash screen. Then load the absolute critical when you go to run the game. There are a couple different approaches to persisting your graphical resources across different activities. Basically your problem is "*How to maintain global variables/state across different activities?*"
Based on how you described your App, I think your best bet is to extend the Application class and load all the initial resources there. The Application class can then be accessed "globally" sorta of speak from any Activity. The Application class maintains it's existence during the life of your App. Note, if it's possible to load your resources statically, then creating static references is a better alternative to extending the Application class.

Some helpful links:
Extending Application Class
StackOverFlow post on Extending Application Class
Loading, Processing, Caching, Managing, Displaying Bitmaps Efficiently
Interesting group discussion about different options to maintaing global state
> 0 votes

---
Tags: android, graphics, performance, loading, png
---


# Question
Title: 2D map/plane with nodes overlayed that supports panning, scaling and clicking on nodes
I'm trying my hand at Android development and seem to be running into an invisible ceiling in trying to get what I want accomplished. Basically I'm trying to create an app that renders a 2D surface map that I can (pinch) zoom and pan. I'll have to place nodes on the surface of the map that will scale/zoom and pan in relation to the surface.

I started out with a 2D ImageView approach and got as far as pinch zoom, pan and laying nodes as relative ImageViews, but all the methods I tried to get X,Y,W,H for the 2D surface were always off for some reason. Additionally, I was never able to scale the node ImageViews correctly, and as a result never got far enough to try and work out their X,Y scaled offset.

So I decided to get back to 3D rendering. Conceptually pan/zoom is camera manipulation, so I don't have to mess with how to scale the 2D map or the nodes. But I need a starting point or sample to get me going that's close to what I'm trying to achieve. A sample on a translucent spinning cube isn't helping as much as I need it to.

Any tips? Links, insults and sympathy are all welcome!

# Answer
Why are you using ImageViews for 2D? I hope you mean a SurfaceView - ImageViews are not designed for any kind of speedy rendering.

I recently open-sourced the source code for my game library which pretty much does what you seem to want done; see the BitmapSurfaceRenderer in https://github.com/micabyte/android\_game

Unfortunately I haven't had time to do a proper example/tutorial for this yet, but the framework is pretty much designed to do exactly what you want (it's the way I implement game maps in my own games - big scrolling bitmap and then overlays with map details such as locations, units, etc).
> 1 votes

---
Tags: 2d, android, 3d, opengl-es
---


# Question
Title: Drawing models and their bounding boxes using two different shaders?
I have a bunch of 3d models I want to draw and also for some of them I want to draw bounding boxes. Calculating the boundnig boxes is no problem, but I'm not sure as to what is the best approach to rendering them.

I have a vertex and fragment shader for my 3d models and they contain a ton of information not needed to draw simple bounding boxes (textures, normals, etc) linked up in a program. Now I also want draw bounding boxes for each of the models meshes and I can think of two ways using two shader programs (one for 3d models and one for bounding boxes):

* after drawing each mesh change program to boundingbox and draw its boundingbox
* after drawing all meshes, change program to boundingbox and draw all boundingboxes for all meshes

I am inclined to believe the 2nd option is better, but is the overhead of glUseProgram significant enough to notice?

# Answer
> 1 votes
Well, I will assume you will need to draw the bounding boxes for debugging only, if I were you I will go with the easier solution; the solution that won't let me change a lot of code Since this is only for debugging I will not be concerned a lot about performance (even though your 2nd solution might be better for performance), you can introduce a preprocessor tag (assuming you are using C/C++) that will disable the box rendering piece of code in release mode, or you can do it in real time by using a flag to render or not.

---
Tags: c++, opengl
---


# Question
Title: Should I use three stars rating in my mobile game or create my own?
In a simple platformer game I want to rate the player's performance in a level based on score. Very common in a lot of mobile games is "three star rating", probably the most notorious example being Angry Birds. My question is:

Should I use the same type of rating or use something else? Is it better to be original or use something the players are used to?

If three stars, should I avoid 0 star rating? (i.e. give player at least a star for finishing the level).

---

From http://angrybirds.wikia.com/wiki/Star

Many other physics-based iOS games, such as Cut the Rope and Save Toshi use the same, or simliar 3-star system. However, the former allows the player to end the level with a zero-star ranking, and the latter allows players to get a three-star-plus ranking.

Reseachers found that before the release of the original Angry Birds, only 20% of all games were rated with the 3-star score system. After the release of it, nearly 80% of all games were rated with the same or similar scoring system. (Similars are the likes of Asphalt 6, which placing was rated with 3, and achivements were 2, meaning that this is a 5-star score system.)

# Answer
> 1 votes
The more levels of achievement, the more chance the player is to see a reward for playing again.

For example, in games where the feedback is expressed as a percentage, they might just improve from 90% to 91% where as they won't get that feedback from a star system where the improvement isn't enough to get an extra star. Worth noting that Angry Birds starwars uses percentages for the Millennium Falcon scores.

However, the fewer levels of achievement, the simpler the scoring system comes across. A younger audience can appreciate 3 stars than 100 percentage points, and they are nice and visual (even Angry Birds Star Wars represents percentages visually), while an older audience (in Angry Birds say) can still see the full score so no detail is lost through adopting a short system.

I would suggest working with percentages internally, then you can experiment with how they are represented externally, e.g.:

```
//3 star system, no 0 star
int stars = percentage / 50 + 1;

//3 star system, 0 star
int stars = percentage / (100/3f);

```

# Answer
> 1 votes
You could use five start system, it easily transfers to the percentage. With the "zero" score, causing no stars.

```
 0 Stars 0 points
 1 Star  1-19
 2 Stars 20-39
 3 Stars 40-69
 4 Stars 70-89
 5 Stars 90-100

```

You could go with any other point system. And say that the player passes the level once he gets 50% or any number of stars you choose. I'd use it as a tool for the player, so that he can have reference how good he actually is in the game.

```
 0 Stars 0 points
 1 Star  1-2 points
 2 Stars 3-5 points
 3 Stars 6-7 points
 4 Stars 8-9 points
 5 Stars 10 points

```

---
Tags: scoring
---


# Question
Title: Correct way/How to think to plan out "control/animation flow"?
So basically, a problem I've had in past attempt at making games (little playing around with stuff): how to do a correct, non-sloppy way of planning the flow of animations/control?

Let's take an example: you have a character, that can walk in the 4 cardinal directions, and can attack. It's that simple. Obviously, you can only walk in one direction at the same time, and let's assume you can attack when not moving in a direction only.

How would you take upon implementing this? Don't know if I'm clear, but what'd your thinking process go like?

I always end up with a huge mess of ifs and else ifs to get the animations to represent what is actually supposed to happen after moving in a direction, ie. character after having moved up, will maintain it's upwards facing (will stay on the "up" animation); Have the facing direction when moving be consistent: if you start walking left, it gets the left animation, correct. Then you start walking upwards at the same time, or downwards, and you'd like the animation to keep @ being left. You start walking up, up animation. And as you start moving left or right after starting to move up, you maintain up animation.

See what I mean? I'll be here for clarifications on the question, sorry if confuse.

For 4 directions it'd not be that hard to do something "decently structured", but when things start adding up, it becomes so confuse!

Edit: Another thing I hadn't thought about: I was simply, upon WASD, altering the object's velocities, and handling all the animation stuff through what velocities were involved. Which leads to wrong things I had thought about, such as if I get pushed, it'd walk left stupidly instead of backing off facing the direction it had.

**Another edit:** What I want is an answer of the sort: "First, for movement, you'd have a look at all the possible directions, and have an int or such indicating what's the current direction. Do a big switch, and inside of each direction, you'd have ifs for further x and y, but not z, because that's gonna be englobed in whatever. Then you should also have another control layer directly on the input handling to help filter unwanted actions or combinations, such as, you don't want to press A and D and have the velocities cancel each other out. For such, you'd have some further "status" for the object..." something of this kind! Thanks!

# Answer
> 2 votes
The way I would do it would be to have my character object have it's own render method, and a member variable to hold direction data. You could make an enum to define the different possible states if you wanted to. Then within the render method, check what state the direction is in (possibly using a switch/case) and render the corresponding sprite.

Wherever you handle your input, have that method update the character object's direction. This way your main code remains readable and uncluttered, but if necessary, you can delve into the character object's implementation if you need to know exactly how things are done.

Unfortunately, I can't think of a better way to do this other than using if-statements to set specific states based on specific inputs. But maybe someone more clever than me can come up with a better way.

EDIT: Ah, I slightly misunderstood your problem. If you want to keep the original sprite state when pushing two direction inputs at the same time, I would just check to see whether the direction state was already set to a "moving" value wherever you check your input. If it's already set to something, then don't set the new one.

# Answer
> 1 votes
**For every animation have a name for it** like "left" or "up" **and a sprite sheet associated with it** and all its rects for the images. Then **keep a variable of the state** like the number 0 for attacking and the numbers 1 through 4 for the directions and also **keep a variable with the frame the animation is on.**

**Then just render the next sprite from the current animations sprite sheet** and change the frame number.If a player pressed the left key change animation to 'left' for example.

---
Tags: animation, movement, input, control, direction
---


# Question
Title: How to know if a model is composed of a group of models?
I've downloaded a model, and try to ungroup the model and learn how this model was made. However, the big model in the image below can not be ungrouped anymore.

I feel that this model is composed of a group of models, but I cannot ungroup this model and unlink it. Is there other methods to test if this model is a model or a group of models?

Thanks in advance.

> Full Size: https://i.stack.imgur.com/VF2SM.png

# Answer
If you open up the scene explorer (Alt+Ctrl+O), you can see what the scene is composed of:

If there are multiple meshes, you'll be able to see them here. If it's all one mesh, it will show up as a single mesh.
> 2 votes

---
Tags: models, 3d-meshes, 3dsmax
---


title: How to use JBullet in LWJGL?

text:
# Question
Title: How to use JBullet in LWJGL?
I have got a problem, because I wan't to add collision detection to my 3d game, which I am developing in Java, using the Lightweight Java Game Library (LWJGL). I have googled a bit, and I have found this interesting library, called JBullet, which is a port of Bullet for C/C++. But I can't find **any** tutorials covering, how to add collision detection to my 3d shapes in LWJGL. Is there any simple way to do it, or please direct me to a tutorial, covering that topic.

# Answer
> 6 votes
The library comes with examples of how to use it. All of the source code for the webstart examples comes with the library.

There's also a tutorials section in the wiki page for jBullet.

Further, most of the tutorials for the c++ version are applicable to the Java port. You will just need to modify the class and function names to work with the Java syntax and naming conventions.

---
Tags: java, lwjgl
---