# Question
Title: HTLM5 canvas game (easeljs) slow peformance on ipad (ios7) with phonegap
I have developed a game with easeljs for HTML5 Canvas. the game is a single HTML5 page with canvas and a lot of javascript.

All this time I tested the app on iOS Safari (iPad3 iOS7) with 40~50 fps via a local server. when I packed in a xcode app with phonegap, it becomes incredible slow near to 10fps.. I noticed the same behaviour when I added the page to homescreen.

There is any way to make make a good performance with html5 canvas app games for ipad (iOS7)?

# Answer
> 0 votes
Ok, I found the solution for this.

The actual phonegap implementation uses default webViewer, which is quite slow. Ludei (www.ludei.com) has a great solution for HTML5 canvas high performance games, CocoonJS. It works great on iOS and Android, there is not for WindowsPhone. However there is no need for it on Windows Phone 8. Windows Phone 8 has the highest native HTML5 canvas performance I ever seen.

so Don't use Phonegap. Try CocoonJS!

# Answer
> 3 votes
My understanding is that Mobile Safari enables JIT compilation of JavaScript which is a pretty significant performance boost.

Due to security reasons, the JIT compilation is not available to a UIWebView within native apps, such as PhoneGap wrapped applications.

It seems that homescreen apps also run inside of the non-JIT UIWebView, although I read a few places that perhaps this restriction had been lifted recently.

Further reading:

---
Tags: html5, performance, html-canvas, ipad
---


title: how to call the specific animation?

text:
# Question
Title: how to call the specific animation?
I have a script to control the player simply moves Left, move right, etc.. but the animation when winning, losing, or Light, just put it on the animation and animator and no script for it.

I wanted to ask. if player enter at the collider, how to call animation light ?

```
void OnTriggerEnter2D(Collider2D theCollider)
    {
        try
        {
            // how can i call animation light //
        }
        catch { /*On error do nothing*/ }
    }

```

# Answer
If you are using the legacy animation system you can simple call `Play` from the `Animation` component.

For mecanim I think that you need to change some variable into animation state machine that triggers the animation, check out:
> 1 votes

# Answer
If you are using Mecanim (which, by your question, I guess you're doing), you can create for example a trigger variable in the Animator, and set it from your code wherever you want. Triggers are basically like booleans, but you don't specify any true/false value. Instead, you just set them from your code, and they will be "true" just for a moment. After the transition has been made, Unity deactivates the trigger automatically.

```
Animator animator = GetComponent<Animator> ();

void OnTriggerEnter2D (Collider2D col) {
    animator.SetTrigger("light");
}

```

This will cause the trigger variable "light" that you have set up in your animator (using the animator window where you have all the transitions between states and so on) to be active just for a moment, before deactivating it automatically after the transition to the Light animation has been made.
> 1 votes

---
Tags: c#, unity
---


# Question
Title: Does Unity have existing support for Timelines?
I am planning the development of a game in Unity3D, and trying to come to terms with what the engine has already provided, and what I must code myself.

The game itself is going to be a rhythm game, which means synching audio and graphical events so that they always play when they're supposed to. What I'm looking to avoid is a potential scenario of lag where either the audio or the graphics starts to progress faster than the other.

When we discussed this type of coordinating system in my game design class back at university, my professor called this type of design a "Timeline" class. The idea being that you can instantiate one or more of these to progress at different rates, schedule things to happen in the future, and synch up periodic events. However, calling this a "Timeline" class seems to have been limited to my professor himself, as googling for whether a certain API features "Timeline" functionality has been a fruitless endeavor.

Is there some more common name for this kind of functionality? Does Unity have any pre-existing methods to coordinate the scheduling of events like this, or is this the kind of thing that needs to be built onto the engine? And if it does, I'd appreciate being pointed towards some tutorials!

# Answer
> 10 votes
While this functionality isn't available in Unity, a basic implementation of such a timeline shouldn't be too hard to do.

Here's how I would go about that:

* Your *Timeline* class internally uses a priority-queue as data-structure to store events.
* An *event* could just be a time and a callback. So adding events to the timeline would be as simple as: `timeline.AddEvent(0.25f, MyCallback)`.
* With every `Update`, the timeline class would:

1. Increment the playhead (a simple `float`) by the elapsed time
    2. Check the *head* of the priority queue and remove and call the callback of all the events that have a priority (eg. time) smaller or equal to the current playhead.

If you need some sort of *rewind* or *replay* functionality, it would of course be foolish to remove all the events from the queue (meaning you would have to add them again when rewound). Instead you could also use an array that holds your *events*. An event would consist of a `Time` and `Callback`. You would have to keep your array sorted by `Time`.

Then instead of removing items from the array, you would keep track of the current *array-index*, and with every update seek ahead from that index and execute all callbacks with `Playhead >= Time` while also increasing the index accordingly.

Implementing a faster playback-speed works with both implementations and would be as simple as:

```
Playhead += Time.deltaTime * playbackSpeed

```

# Answer
> 4 votes
No, Unity3D doesn't have such an API out of the box.

It does support coroutines, though, and I suggest you look into them. Coroutines generally make scheduling and syncing events really easy.

# Answer
> 1 votes
I'm not sure if this is new since the answers in 2012, but Unity actually does have support for timeline control via the (Legacy) Animation Editor.

Although this feature is intended mainly for animating object parameters with curves, it includes the ability to trigger scripts on Animation Events. These scripts could drive your graphics and audio.

---
Tags: architecture, unity
---


title: Slight pause/delay when moving

text:
# Question
Title: Slight pause/delay when moving
I've been working on this little framework for my game today and realized that moving delays when moving around. I've used SFML before and have had the same problem, but never bothered to fix it. I'm wondering if anyone has had a similar issue and has found a solution. Here's an example of the code which is giving me the slight pause in movement:

```
int main(){
    sf::RenderWindow window (sf::VideoMode(640, 480), "Window");
    //window.setVerticalSyncEnabled(true);

    sf::Texture tex;
    tex.loadFromFile("Assets/Textures/player.png");
    sf::Sprite s;
    s.setTexture(tex);

    while (window.isOpen()){
        sf::Event event;

        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed)
                window.close();
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
            s.move(0.01f, 0.0f);
        }

        window.clear();
        window.draw(s);
        window.display();
    }
}

```

The delay/pause/whatever I'm experience is very slight but I can notice it and it's really bugging me. Just seeing the slight break in movement when none of the values alter makes my programming mind extremely sad.

# Answer
I've had the same type of quirk, and after some experimentation I've found that it's caused by the `while (window.pollEvent(event))` loop.

I re-worked my method just to read the message

```
(window.pollEvent(event));

```

at the beginning of the

```
while (window.isOpen()) {

```

and then go from there. This causes the frame rate to skyrocket, and you'd definitely want to put in a tick System, but unfortunately I'm in class at the moment. When I get home I'll post my code snippet.
> 0 votes

---
Tags: c++, sfml
---


title: Tile System with moving Platforms

text:
# Question
Title: Tile System with moving Platforms
I am using a tile based system where the level is stored in a char:

```
        char[,] Level2 = {{'.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.'},
                          {'.','.','.','.','.','.','.','.','.','.','.','.','.','.','+','.'},
                          {'.','.','.','.','.','.','.','.','.','.','.','.','.','.','.','.'},
                          {'.','.','.','.','.','.','.','.','.','.','.','.','#','.','.','.'},
                          {'.','.','.','.','.','.','.','-','-','-','.','.','#','.','.','.'},
                          {'.','.','.','.','.','.','.','.','.','.','.','.','#','.','.','.'},
                          {'.','.','.','-','-','-','.','.','.','.','.','.','#','.','.','.'},
                          {'.','.','.','.','.','.','.','.','.','.','.','.','#','.','.','.'},
                          {'#','#','.','.','.','.','.','.','.','P','.','.','#','.','=','.'},
                          {'#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'}};

```

I set a platform down and then have it move up and down or left and right. Useing a list that uses a class like so `List<Block> Blocks;`. This list holds the texture, position, and blockstate.

### How would I call upon the platform and then move it so that it will collide with the `'+'` or the wall (`'#'`)?

```
        for (int x = 0; x < tileWidth; x++)
        {
            for (int y = 0; y < tileHeight; y++)
            {
                //Background
                Blocks.Add(new Block(background, new Vector2(x * 50, y * 50), 0));

                //Impassable Blocks
                if (Levels[level][y, x] == '#')
                {
                    Blocks.Add(new Block(blockSpriteA, new Vector2(x * 50, y * 50), 1));
                }
                //Blocks that are only passable if going up them
                if (Levels[level][y, x] == '-')
                {
                    Blocks.Add(new Block(blockSpriteB, new Vector2(x * 50, y * 50), 2));
                }
                //Platform Stoper
                if (Levels[level][y, x] == '+')
                {
                    Blocks.Add(new Block(movingArea, new Vector2(x * 50, y * 50), 3));
                }
                //Vertical Moving Platform
                if (Levels[level][y, x] == '=')
                {
                    Blocks.Add(new Block(platform, new Vector2((x * 50), (y * 50)), 4));
                }
                //Player Spawn
                if (Levels[level][y, x] == 'P' && player.Position == Vector2.Zero)
                {
                    player.Position = new Vector2(x * 50, (y + 1) * 50 - player.Texture.Height);
                    player.Velocity = new Vector2(0, 0);
                    player.initialVelocity = 0;
                    player.Time = 0;
                    player.isJumping = false;
                }
                else if (Levels[level][y, x] == 'P' && player.Position != Vector2.Zero)
                {
                    throw new Exception("Only one 'P' is needed for each level");
                }
            }
        }

```

# Answer
> 0 votes
If your maps are small, which the one above seems so, using a list of blockCollidable = true items. Then when the character is moving have an

```
foreach(Block currentBlock in Collidables)
{
  if (player.X + tileWidth > currentBlock.X && player.X < currentBlock.X + tileWidth)
  {
    if (player.Y...)
    {
      //Collision Code
    }
  }
}

```

Using that for your map editor you can easily add a check box on any block and make "invisible" blocks that are just collidable = 1 background blocks, or whatever you want to add.

---
Tags: xna, c#, 2d, tilemap, platformer
---


# Question
Title: How can I know when a player quits out of a turn from the Game Center UI?
In an iOS Game Center managed turn based game, if a player quits out of turn from the Game Center UI, then `turnBasedMatchmakerViewController:playerQuitForMatch` isn't called (as expected). However, the other players don't seem to receive any `handleTurnEventForMatch:` notifications either. Is this correct?

If this is the expected behaviour, how is the game to become aware that someone has quit in this way?

# Answer
> 0 votes
Never mind, it seems to have been one of the regular sandbox notification outages.

I tried exactly the same code and devices again today, and this time the second device received a `handleTurnEventForMatch:` with the quitting player's `matchOutcome` equal tot `Quit`.

---
Tags: ios, game-center
---


# Question
Title: How do I convert a horizontal, panoramic skymap texture into a "dome" version of itself?
How do I convert the following skymap image:

into a "dome" version like the one below?

I'm looking towards making use of Adobe Photoshop for the task at hand. However, I'm at a loss on what tools I'm going to use and how I will go about it.

So, **how do I convert a horizontal, panoramic skymap texture into a "dome" version of itself?**

# Answer
A simple method using only Photoshop:

1. Crop the image vertically to remove anything that should be below the horizon (ie. not part of the sky dome)
2. Scale up the height of the image to make it square
3. Filter -\> Distort -\> Polar Coordinates
> 7 votes

---
Tags: textures, uv-mapping, skybox
---


# Question
Title: Using Blueprint to spawn objects at runtime in Unreal Engine 4
Using UE4's "Blueprint" visual scripting system, how can I dynamically spawn objects at runtime?

# Answer
I would recommend watching: https://www.youtube.com/watch?v=rhCGy9ceRPI

It will show you how to spawn something from pressing a key at a target location, I would say just replace the key press with the Initialize Level function.

Not sure if that might be what you are wanting.
> 2 votes

---
Tags: unreal
---


title: Creating very rough 3D models

text:
# Question
Title: Creating very rough 3D models
I am not a modeller, more into the programming side. However say I wanted to create an open world type of game using U4. Is there a way to create very rough models, say of buildings, cars, trees, terrain etc, without having to fine detail them, so I can lay the skeleton of the game as a blueprint.

I know all these models would have to be redone properly but I would want to experiment creating the overall structure of the game world environment in a very rough way first.

I take it I would just be creating block(cube) like structures in say Blender, exporting these models and then loading them up in the U4 editor for placement?

# Answer
So what you would probably need to do is the following:

1. Create a simple model in Blender, 3Ds Max, Maya,... whatever 3D package
2. Export that model to .fbx (check settins if you have materials or something
3. Take this .fbx file and drag it in the Content Browser of Unreal Engine.
4. At this point you should fill in some data about the model, normally you only have to change the name and the package.
5. Done. You can now drag your model from the Content Browser in your scene.

NOTE: This is based on my experience with UE3. The Content Browser part might be different with UE4 because it uses those blueprint things.
> 1 votes

# Answer
I would not be sure in the C++ method, but using the editing view port I would recommend watching these quick tutorials for building a basic level.

https://www.youtube.com/watch?v=I8WBF4AyAX4&list=PLZlv\_N0\_O1gaCL2XjKluO7N2Pmmw9pvhE

He builds an office with a sliding door in like 20 minutes, along with textures, lighting, etc. So pretty sure you could piece together like an entire landscape fairly quickly using the same basic methods shown in this tutorial playlist. And it is using everything that comes with UE4, no need to import.
> 0 votes

---
Tags: c++, models, unreal, world-design
---


title: Animating feet seperately from the body

text:
# Question
Title: Animating feet seperately from the body
I have a character and I would like to animate a walking animation for it. However i get the following result when I animate it:

(ignore the green lines/ markers/ sound) As you can see the foot animation is also being applied to the character with predictably bad results. I currently have one animation which applies to the entire character which the foot is a part of. This animation has two layers and can be seen here:

The real problem I am having is how does one get an animation to only apply to a section of the character? I know this can be accomplished with avatar masks but i believe those are only for 3d animations/projects (this is 2d) but if you can get this to work with 2d animations please explain.

The animation that I am using just changes positions, and rotations which is unfortunately applying to the entire object. It also should change the sprite of the feet however this is not taking effect. Ignore the fact that there is only one foot, the other was disabled but exhibits the same behaviour as is seen in the shown foot.

This is a 2d project.

# Answer
> 1 votes
As Savlon said, this can be done as in the Tower Bridge Denfense demo. Basically you just have to separate the feet from the rest of the body using the sprite editor (slicing the different parts of your sprite asset). The feet will be children of your main player object. After that, you just need to create a new walking animation for the whole character and animate the feet along the timeline.

---
Tags: 2d, unity, animation, movement, layers
---


# Question
Title: How can I implement Objective-C libraries in Unity?
I've been a "hardcore" developer for sometime now, as I've always worked with pure code reactive rendering, and contributed to `Cocos2d` library some time ago , (It is the one I used for my games) . But **I've come to realize that most of the work I'm doing by setting up my game environment , user interface and everything else is becoming a bit repetitive, and complicated**, as position must be tested each build , debugging sometimes involves exploring the deep down framework and I've decided to try out a full game development environment.

Some friends have recommended me `Unity` for mobile development (If you could give me any better advice I'd be grateful) but my main concern is my custom libraries I built on Objective C for multiplayer real time connectivity, it's probably thousands of lines and I wouldn't like to write them all over again.

**Is there any way I could invoke my objective-c library in Unity ?**

I know it's probably a vague question but can't seem to find where to start! Any guidance will be highly appreciated!

# Answer
Plugins for Unity can be written using Objective C; refer to this page: http://docs.unity3d.com/Documentation/Manual/PluginsForIOS.html

However I wouldn't assume that a code library of thousands of lines that wasn't designed to be used as a Unity plugin will work as a Unity plugin. It's all free so you could download Unity, fire up the demo project, and then try to integrate your Objective C library.
> 5 votes

---
Tags: unity, objective-c
---


# Question
Title: What is the average team size for mobile games like these?
I know that it is maybe too broad question but please give me at least some guidance. What is the average team size for mobile games like in https://play.google.com/store/apps/category/BRAIN?feature=category-nav

There are quite different by size and complexity games but I just need examples like: Game X was developed by N programmers for M months (or at least "It seems to me that game X will need N programmers for 5 months to be completed").

By "Team size" I mean mostly programmers (but I will really appreciate more info about other specialists that are needed for such project).

To put some context: I am freelance Android and PHP developer working mainly on intranet and b2b systems that are consisted by both android app(s) and server back end. Although I really like this area sometimes it is hard to find new projects. At the same time, every now and then, I receive inquires like "Can you create clone of game X and how long will it take" or "I have this idea for a board/puzzle game, how long it will take?". So far I stay away from such projects but I am really tempted to start/join such project and I will appreciate any helpful information.

# Answer
> 7 votes
First of all, don't discount the other people you need. Some games require mostly artists and some require mostly programmers. A game which requires you to move blocks around a dynamic world probably needs more programmers, but a game where you travel the world playing cards probably needs more artists.

The other thing to consider is the other aspects of these kinds of projects. The project needs to be managed, it needs to be thoroughly tested, it needs someone to do quality control, you need people who can market the game, someone to do the finances .... There's a lot of these things. For a mobile game not all of these require full time dedication and so maybe a few can be done by the same person, but they're also important and if you're having your programmers or artists take on these kinds of roles as well, then you may need a couple more artists and programmers.

So basically I believe it's all based on circumstance. Personally I work in a team of 5 main people; me as programmer, 1 marketing guy, 1 artist, 1 animator, and one general lawyer/game design/management/just kinda useful to have guy. But on top of that we have been lucky to get help with other things, like someone helping us with marketing and another helping with QC, without them really being a part of the team.

So I think it's a question that can never really be answered definitively. There are plenty games made by one person that do well, and others which had 20 on a team. The truth of the matter is you should maybe just feel it out on a project by project basis. Once you've done some requirements analysis you should be able to make a good guess at how many people you'll need and how long, just like any other programming project.

# Answer
> 4 votes
NimbleBit makes various successful iPhone games (Pocket Frogs, Tiny Tower, Sky Burger, Textropolis, Dizzypad, Scoops, etc.) and has just 3 people. 3 very talented people mind you, but 3 people. They also have games that are very simple at a core level of gameplay and art; they don't require a massive amount of developer generated content, which is time consuming and expensive to create.

Another thing to look at along with team size is development duration and production cycles. Small teams can be light and agile, big teams not (always) so much. 3 people and 3 months to develop a game seems like a good model, especially given the volatility of the app market. A year invested in an app that doesn't "stick" and create revenue is a year wasted. Compare with being able to put out 3-4 apps in that same year, and if any one of them "sticks", spend more time on it and expand on it. If it fails and just doesn't click with the market, abandon it and move on.

# Answer
> 3 votes
there are 2 competing ideas in projects for number of "workers", and they both have applications to programming/development

```
"many hands make light work"

```

the more works the faster things go (if everyone has a specialty, and can do their job well), and

```
"to many chefs spoil the soup"

```

if person X is working on section Y of the project, and person A is also working on it then both peoples modifications have to be taken into considerations, and in many cases their work needs to be manually merged.

then comes the question of time, and this directly relates to the number of people, but not always. there is a "fallacy" in computer science that I have seen multiple ways called the "1 man month", it basically means that one person cannot create a fully featured solution to a computer science project in one month. though this has also been the site of some debate, and statements of "I can do that", but the thought is that it takes more then one person (sometimes it takes people with specific talents) to get things accomplished.

then questions like this can very easily be used to ask how "many other people do I need to do, or something like project X?" when the truth of the matter is this is not a question for others, but an honest self-reflective question for yourself. then have you done a SWAT analysis (especially S, and W) of yourself, and your possible team?

yes it is possible to find how many people made these games, but that doesn't "explicitly" mean that you will be able to do it with the same number of people.

# Answer
> 3 votes
World of Goo was made by two people.

For a casual\puzzle game on ios you need a single programmer and one or two artists\musician, more people will usually only slow down development or be of very little help.

Two people (plus outsourced music) is usually the best number as ios titles doesn't really do that much of an income in the average situation (read: the market is nowhere near the goldmine everybody imagine)

# Answer
> 2 votes
"1. Angry Birds was made by a team of four people and took eight months to finish because it was such a low priority for the company. "

According to: http://www.iphonedevsdk.com/forum/off-topic/61675-angry-birds-10-things-you-probably-didnt-know.html

# Answer
> 1 votes
This is a fascinating and insightful presentation on gaming development where he discusses the pros and cons of working in groups of developers for years at a time as opposed to working on games independently a few days at a time and pretty much everything in between. How the process works and how few or many required is discussed as well.

---
Tags: android, iphone, mobile, puzzle
---


title: Drawing line from sprite with a touch

text:
# Question
Title: Drawing line from sprite with a touch
I am working with cocos2d for the iPhone and I have a question about how to implement the following. I have a circle shaped sprite on my layer. When I touch the sprite and move my finger a line must be drawn from the sprite to where my finger is. When I move my finger on the screen the line must follow (straight line). When I release my finger the line should disappear. In a good looking way I should be able to restyle the line into an arrow.

Can anyone move me in the right direction for this ?

Kind regards

# Answer
> 0 votes
I do something like this. Just store the start touch location on ccTouchesBegan, store you end point on ccTouchesMoved and then draw lines in the draw method between the 2 stored points.

# Answer
> 0 votes
You could use CCMotionStreak to achieve a nice fade effect for your line. This is how CCMotionStreak looks like.

If you want a simple line, without any fancy effects, then you can use the method `[drawSegmentFrom]` of CCDrawNode.

---
Tags: cocos2d-iphone
---


title: What is Ogre::String?

text:
# Question
Title: What is Ogre::String?
I was working with the OGRE .NET bindings (MOGRE) for quite a long time. To improve my (not that good) C++ skills, I am switching from C# to C++.

After implementing a basic OGRE application, I was curious why Ogre has it's own String class **Ogre::String?** Why is it used and not **std:string**?

Can/shall I mix these String types and what shall I use in my OGRE application for non-OGRE tasks/methods?

# Answer
> 5 votes
Frameworks in C++ tend to use their own string implementation to solve Unicode and localization issues. Unicode support in C++ is generally not that good even in C++11. std::string can't store Unicode characters.

If you want to take advantage of unicode and probably localization you may want to use their string.

---
Tags: c++, ogre
---


title: How necessary are shader coders?

text:
# Question
Title: How necessary are shader coders?
I know that gameplay mechanics programmers, either directly working with source or with scripting are needed, however there are so many shaders written already that I would imagine you could find anything to meet the visual effects you are looking for, is this a fair assumption?

# Answer
> 1 votes
Shader programming is a highly specialised section of general Graphics Programming. Like any other highly specialised section of development, it depends on two factors; namely the **Team-Size** and the **Goals** you wish to achieve

**1. Team Size:**

On smaller teams, having an entire resource (read: person) dedicated to ONLY shader programming might be a huge overkill. In smaller teams, your general graphics programmer (and in some cases, THE programmer) would probably be enough handling most of the coding needed in that direction

On larger teams and as we go towards AAA development end where there are usually multiple graphics programmers on a team, having highly specialised people usually leads to more efficient and better optimised code; meaning you can squeeze more performance out of the hardware

**2. Goals:**

Here, by goals, I mean the graphical goal of the project. If you are creating a game with not much new stuff going on on the graphics side, then you *might* be able to find something to fit your needs specifically

On the other hand, if you are going for a more unqiue, new or innovative technique (like implementing a SIGGRAPH paper) then you very likely would need a more specialised coder dedicated to the shader coder alone

Also, on the note of

> I would imagine you could find anything to meet the visual effects you are looking for, is this a fair assumption?

This could almost be said for almost all areas of the game development. There has to be enough tutorials about AI, UI, graphics, sound, networking and all other fields of the development that you could argue the same thing. However, these samples are either too generic to be optimised, or too optimised to be easily plugged into your code, without extensive knowledge from your side on what the code expects, does and achieves

So while you may find a shader somewhere that does exactly what you want, if you don't have a moderate understanding of its code, you might come across a bug that will just block your progress completely. And this might not even be a bug, but just coming out of different expectations between you and the code author

# Answer
> 1 votes
Shader coding is a pretty specific skillset, however it is one that anybody who calls themselves a graphics programmer *nowadays should* be familiar with since writing shaders has become absolutely crucial to that profession. It's not quite as simple as just jumping in and integrating samples you can find online, because you need to make different shaders work *together* and be *performant*. That requires an understanding of the larger graphics pipeline and all that goes into it, on GPU *and* CPU.

You can get by without another coder. But you will be spending a lot of time learning, if you are not already quite familiar with writing shaders (and by proxy, engine code) yourself. You may be burnt out before you ever get anything worthwhile running -- consider that. Like any specialised field such as writing physics engines or AI, it is a highly specialised skillset and way of thinking, with many pitfalls.

If the goal is to get a working game (demo) up and running, and your human resource is limited, then I would not recommend diving into GPU programming unless you have are least 5 years of professional technical programming experience. Because it will take up a lot of your time, even so.

# Answer
> 0 votes
Well, you usually need someone to make your game looks good whether was a good artist a great shader writer or both.

### The actual question that should be asked, do we need an expert level shaders writers with low level hardware knowledge or not?

If you are making the next AAA title and want to squeeze every last cycle from your GPU then and want your game still to look good, shader/graphics programmers are far more important than in smaller games. Knowledge in hardware and low level shader optimization is essential in achieving visual effects without making your game crawl, let's say games like Battlefield and Crysis.

This is nicely summarized in this slideshow

> I would imagine you could find anything to meet the visual effects you are looking for, is this a fair assumption?

Again the same point applies, but keep in mind that shaders found in tutorials are usually unoptimized, due to the nature of tutorials. Finally if you are making a smaller/mid game you probably need better artists than expert level shader coders.

---
Tags: c++, shaders, game-mechanics, scripting
---


# Question
Title: Why is my Snake' tail rendering the wrong sprite?
I am making a snake game in Unity. The game is simple, using `Texture2D` to display the head, tail and body parts.

I am stuck with this problem: I stored 4 textures (each one for one of the four directions) for the head and tail. I check the direction and in `onGUI`, I select the appropriate image. The snake displays correctly, but the tail image doesn't:

How can I fix this?

# Answer
Without seeing your code, it's hard to give on solid answer, but here's an idea that might help you:

The tail always points away from the previous piece of the snake.

If we see the last piece of the snake as the tail, then the one that comes before it gives the direction of the connecting end of the tail, and the opposite direction is then the direction of the taily end of tail.

Here's a poorly drawn ascii picture to indicate the situation:

```
o o }         < 0 0 }
v

```

The second picture should 'logically' have the tail pointing down as in the first, but because the next piece is to the right of it, the tail should point to the left.
> 2 votes

---
Tags: unity, textures, rendering, gui
---


# Question
Title: How do I combine images into a single entity in libgdx?
I've googled this but can't seem to find anything on "concatenating" two images, especially with libgdx.

Any ideas?

# Answer
Do something like this:

1. Create a rendertarget
2. Set it to be the target for drawing
3. Draw image one to it.
4. Draw image two to it.
5. Save this render target, holding the combined images.
6. Set the backbuffer as drawing target.

This question presents the same problem and its solutions should work flawlessly also for your use-case. Just draw your textures with the spritebatch, enabling the framebuffer object created before.

It's easy to Google for details on this...
> 1 votes

---
Tags: java, textures, libgdx, image
---


# Question
Title: Can UE4 be used from multiple locations with a single license?
I want to subscribe to Unreal Engine 4 with my small game development team. But before we do, we have a question: can we also use UE4 from multiple locations at the same time? So that all of our developers have access to UE4 with just the fee of $19/month?

# Answer
> 2 votes
The licence is per user, you need one for everyone working on it. They can then install/use it on as many PCs as they want.
There is no Git support or anything like that included. There is also nothing stopping you from using it, C++ works quite well with Git...

---
Tags: unreal
---


# Question
Title: Is this Possible to force gameobjects (coliders etc) to get stretched based on the aspect ratio of the screen?
Well with unity3D, I am in big trouble whenever I use sprites. As for textures I compensate for a evener look by Stretching it (Screen.width & Screen.height- that's fine for low end 2D games). Now If I have an Image and based on content of Image (Let's say I want to add BoxCollider for the walls in image). It works, but for only one aspect ratio. As I am making game for Android. I am having bunch of different resolution & Aspect ratios. Is this possible to stretch my coliders or other game objects so that I can Work easily???? please help me. I am in a rush :(

# Answer
> 1 votes
I have a 'full width UI' script that deduces the aspect ratio of the screen relative to some reference screen dimensions, and adds a scale to the transform to compensate for a change in aspect ratio. Then I build my UI to the reference screen dimensions (in my case 1024 x 768). At runtime, the actual screen width is asked for, and the adjustment ratio calculated. E.g. if the screen width is 1280, then a ratio of `1280/1024 = 1.25` is needed. That ratio is set as a scale along the x axis on a transform which is the parent of all of my UI, effectively stretching it horizontally until it occupies the whole screen.

NB: This is separate from the code which scales the entire UI to fit the resolution (e.g. if the screen was set to 800x600 instead of 1024x768, then my UI needs to be scaled down by 0.78125 in both axes to occupy the same space. In practice, I handle that part by altering the camera projection, but I call it out because changing the aspect ratio is a separate thing than changing the resolution (because the latter needs to preserve the aspect ratio, not alter it).

---
Tags: unity, collision-detection, textures, sprites
---


# Question
Title: What is the advantage of wrapping D3D in a class versus a namespace?
Almost all the tutorials and books use a class wrapper for Direct3D. But I haven't found any scenario in which using more than one instance of Direct3D system (the "device" and state, et cetera) is required.

Is there any advantage to using a class instead of a namespace? Is there ever a case where using more than one is required?

# Answer
Certainly you could just wrap your D3D usage up into a namespace containing free functions and that would be fine. It's not *wrong*, per se, but it does have limitations. D3D is inherently object-based, and those objects store state. By hiding it behind a free-function façade you'd actually *remove* flexibility (you *could* create more D3D devices but you *can't* create more instances of your free-function façade).

Plus, most abstractions over D3D exist to simplify the interface, and that usually involves storing some state yourself. Doing so in a free-function API is similarly limiting (you store it in private global variables in your translation units, and you can never have more than one) or cumbersome (you implement what is essentially C-style object-orientation, passing the state object to each of your free functions, which is rather silly in C++ where you have better mechanisms to do this).

It is thus generally better to abstract D3D via wrapper classes and objects rather than namespaces, unless your needs are exceedingly trivial. This also offers the following benefits:

* If you want, and are comfortable with both D3D and OpenGL, you can design the wrapper API such that the implementation could be swapped out, providing you both a D3D and OpenGL renderer. This is a fairly popular rationale, although it is not always done well or really necessary(\*). In C++ specifically, this helps force implementation hiding which cleans the surface of your API (clients don't have to pull in D3D or GL headers themselves).
* You can potentially mock the abstraction's implementation for testing purposes. It's usually rather difficult to unit test rendering, but the ability to build automated, *not-strictly-unit* tests to avoid bug regressions *is* useful.
* You don't unnecessarily pessimize your system into assuming only a single instance of this API can exist when you really don't have a rationale to impose that requirement.
* Free-function APIs can't be passed to functions as arguments; objects can. This is a huge win, in my experience, because it forces you to have explicitly-specified dependencies in your APIs. It's obvious from some other API if it depends on the renderer because it will take instances of the renderer in its parameters (or something). This helps self-document your code, and it also helps you notice when you have a problem of overly-promiscuous dependencies (the design problem where you find that you have to "pass the renderer to everything").

(\*) With modern OpenGL, I'd argue that new projects should just use OpenGL and abandon D3D. That was before the announcement of D3D12, and once more concrete information about D3D12 is available I might revise that argument.
> 1 votes

# Answer
Game engines often provide an interface for their renderer. This hides specific implementations for Direct3D/OpenGL/GCM render code. The main advantage to this is that you can have classes/wrappers for each graphics API but you only ever use the same renderer interface regardless of the target platform.

Classes are generally used for their polymorphism functionality where the interface class is an abstract class and is inherited by each graphics API class.
> 1 votes

---
Tags: architecture, directx, oop
---


# Question
Title: How can I get a direction vector from a an Euler angle?
Im trying to get a directional vector from an euler angle. But im not getting how to do it. This is what i got so far.

```
escapeAngle += 90;
var radians = escapeAngle * (Mathf.PI / 180);

var escapeAngleAsDirectionVector = new Vector2 ();
escapeAngleAsDirectionVector.x = Mathf.Cos (radians);
escapeAngleAsDirectionVector.y = Mathf.Sin (radians);

escapeAngleAsDirectionVector = transform.TransformPoint (escapeAngleAsDirectionVector);

```

# Answer
> 3 votes
You can create a rotation quaternion from your Euler angles. By multiplying it with a vector 'right', you get a Vector2:

```
Vector2 v = Quaternion.Euler(x, y, z) * Vector2.right

```

# Answer
> 0 votes
The correct formula is `V = {r*cos(theta), y*sin(theta)}` to get a vector from an angle with line at angle theta of length r, so your calculations look right. BUT one thing you need to account for is if the angle is negative. then you would have to add 360 to the angle.

E.g.

```
if(esacapeAngle < 0)
    escapeAngle += 360;

```

Another thing you should probably check if the angle is greater than or equal to 360 after the addition, because that wouldn't be valid either.

```
if(escapeAngle >= 360)
    throw error

```

then do the rest of your calculations.

This will give you a perpendicular vector though, as you add 90 to the angle.

Converting Polar coordinates to Cartesian coordinates

---
Tags: mathematics, linear-algebra
---


title: Why isn't the bitangent calculated?

text:
# Question
Title: Why isn't the bitangent calculated?
In teh tangent space vertex attributes why is the bitangent (aka binormal) provided as an attribute instead of calculated?

If the three vectors of the tangent space must be perpendicular then the bitangent can be calculated as the cross-product of the other two vectors. There are technically two perpendiculars here, but surely we could consistently calculate the one we want, even if it requires a boolean marker to negate it.

Similarly the bitangent itself doesn't need a full vector to be represented. From the normal alone we know the plane on which the tangent must reside. In theory a simple angle would be enough to calculate the tangent vector.

Given that GPU memory is at a premium why do we provide the full vectors for these values rather than calculating them (with reduced data input)? Or am I wrong in assuming the tangent space must be a cartesian system?

# Answer
I'm pretty sure many games do calculate the bitangent by crossing the normal and tangent. In the games I've worked on, that's what we did. We also stored a 1-bit "flip" value to indicate whether the tangent basis should be right-handed or left-handed. As you say, this saves memory, plus the bandwidth used to fetch the memory; and if you reconstruct the bitangent in the pixel shader it also saves an interpolator (which can be a nontrivial cost).

However, it's not always correct to do this. The tangent and bitangent vectors are derived from the UV mapping, so if the UV mapping is distorted then these vectors need not be orthogonal. Therefore the bitangent can't be correctly reconstructed from just the normal and tangent.

On the other hand, in practice, people tend to model things in such a way that the mapping is close to orthogonal most of the time, and it's difficult to notice lighting errors due to slightly wrong bitangents.
> 1 votes

---
Tags: mathematics, 3d-meshes, normals
---


title: Bloom only on line renderer

text:
# Question
Title: Bloom only on line renderer
How do I apply the Bloom Effect Line Renderer's only? I'm using the bloom effect from the Unity Pro image effects script but it's affecting the way light is rendered to the scene.

# Answer
> 3 votes
Typical bloom effects are applied as a post-process to the entire rendered frame. This makes it difficult to bloom only select objects. Even windowing the bloom to a region around the lines risks blooming unrelated content that comes too close.

Instead, you can try "pre-blooming" your LineRenderer content - using a wider ribbon and baking a soft surrounding glow into its texture or calculating one in its shader. This is approximate (tricky to get the bloom distance constant in screen space), but simple to implement.

The enemies in Lovers in a Dangerous Spacetime use a "fake bloom" approach like this.

A more rigorous approach is to put your lines on a layer that is not seen by your main camera. Then you can manually render them to a separate render target, using the main camera's depth buffer to ensure they are occluded correctly (this requires some Graphics.SetRenderTarget jiu jitsu, and is not for the faint of heart). Now you can bloom this render target independent of the rest of the scene, and composite it into the rendered frame at the end, without affecting other in-scene content.

# Answer
> 0 votes
You should try a Replacement Shader to replace only the material set on the line renderer. You can then keep shading from that material and add a blooming effect around it (by playing with the bloom shader).

I can't remember if it's in Unity's standard assets or a package from the asset store...

---
Tags: unity, effect, bloom
---


# Question
Title: Why would you use software rendering over hardware rendering, today?
As opposed to CPU or software rendering I assume?

Wouldn't generally all current rendering be GPU based, seeing as you would be using OpenGL or Direct X?

Could someone give me some info here, can't find any suitable answers?

# Answer
As you clearly already know what GPU rendering is... let me answer what you seem to be asking.

Traditionally, hardware rendering has carried a stigma of being very complex. This has in large part been due to the design of the application programming interfaces (APIs) which have not been well-geared to concealing complexity; that is, the learning curve has been steep. It has also been in part due to an understanding that writing 3D applications -- for which these APIs are heavily geared -- is far more complex than writing 2D ones. Re interface complexity, I'm referring to interfaces like OpenGL and DirectX. Re 3D vs 2D, I'm referring to the mathematics and geometry which goes into constructing 3D scenes, vs. the simplicity with which the untrained mind can approach 2D problems.

However, in recent years, not only has learning material become much more available, but also, many libraries that wrap the underlying complexities of these interfaces have become available and have lowered the barriers to entry. All of this has fed back into a cycle of increased interest which was already present due to the increasing importance of visualisation, slick user interfaces, and performance on low-powered devices.

So software rendering and 2D rendering have been good entry points and focus areas for those who were new to graphics and / or wanted to create a product where rendering did not take too much of the available time on a project. At least in regards to 2D, this still applies; technology has largely covered the gap in bringing 2D rendering to GPU.
> 9 votes

# Answer
There are some really good answers here, so just to supplement them.

A major driving force behind software rendering is capability. This was touched on in one of the answers, but I'm going to make an opposing point: software rendering can actually be *more* capable than hardware rendering, not less.

With hardware you're generally limited to the capabilities of the hardware itself, although OpenGL for one is capable of software-emulation of a lot of things that may not exist in hardware. What that means is that if you try to use Feature X but the hardware doesn't support it, one of two things will happen: either you'll drop back to software emulation (the typical OpenGL scenario) or you don't get to use it at all (the typical D3D scenario).

With software rendering you get to write the code yourself. You get to manipulate things and have full control over what happens down to the pixel level. To give an example of a blast from the past, Quake had pixel shaders implemented in software back in 1996, at a time when 3D cards (they weren't called "GPUs" then) could barely rasterize a few dozen textured triangles.

This is more the case with current GPUs too, but there are still significant parts of the graphics pipeline that are exposed as fixed functionality (or not even exposed at all).

Software rendering can scale out better. It's only relatively recent that we've seen multi-GPU setups becoming really viable, but software can scale across many many CPU cores in many many servers. You can have entire server farms dedicated to this, and professional render farms will still use software rendering.

Software can expose different rendering paradigms. Current hardware is very focussed around the triangle/vertex/fragment/rasterization paradigm; it's a case of picking one thing and optimizing it until it screams for mercy. GPUs are still a poor choice for e.g ray tracing, which is more commonly implemented in software.

Of course when it comes to a direct apples-to-apples comparison a GPU will beat software any day of the week - provided we're comparing areas where GPUs are stronger. But that's not to say that they're stronger in every area. Despite that, and for the purposes of this SE site, using hardware is generally the way to go but just be aware that there are use cases out there where software is also viable.
> 23 votes

# Answer
Hardware or GPU rendering is, as you guessed using the graphical processing unit (aka Video Card) to render an image. The opposite is software rendering where the CPU is used.

Software rendering is usually used as a fallback when there is no (suitable) GPU available. However since the GPU is orders of magnitude faster software renders are almost never usefull since a CPU will usually not be able to render images in real time. Software rendering is useful when a high precision is needed of if extremely complicated formula's are required to render the image. Since CPUs are more general purpose then GPUs and thus have more capabilities. However this argument is becoming less and less valid as GPUs nowadays can handle more and more complex task and are no longer limited to just 32bit floats to represent numbers.
> 12 votes

# Answer
I think this is a really good question.

What I can imagine is:

* VRAM is more limited than general RAM memory. In case of GPU rendering - every texture is more of an issue. You can store in average about 4 to 8 times more data in RAM than VRAM. Of course this scenario assumes that there is no system that is responsible for freeing/pushing unused/required textures from/to RAM/VRAM
* In terms of multithreading it's a lot easier when you work with the software rendering - no need to share contexts
* If you are doing 2D graphics - usually most frameworks carry on the implemetation of Dirty Rectangles Evaluation - what solves many performance issuess.

Still, rendering using OGL/D3D gives a lot more performance and possibilities. Shaders can do really amazing things, that are almost impossible with software rendering.

But technigques such as blitting, using colorkeys, have their own kind of feeling as if you were at the base level, the origin of computer graphics world.

I think it's at least good to know about the software rendering. It's really a very exciting world, not mentioning that it is the root of all what we see today.
> 3 votes

---
Tags: opengl, directx, rendering, gpu, software-rendering
---


# Question
Title: What is the utility of squared radius and inverse squared radius for lighting computations?
On one of the slides from "DirectX 11 Rendering in Battlefield 3" PowerPoint I noticed the folowing code:

```
struct Light {
    float3 pos; float sqrRadius;
    float3 color; float invSqrRadius;
}

```

I don't understand why would they store the squared radius and even the inverse squared (which I believe is simply 1-squared radius) instead of simply storing the radius? How are they using this data in their computations? Moreover, what about cone and line lights? This struct must be only for the point lights, I can't see it working for other types - there is not enought data. Still I would love to know how they use that square and invSquare.

**UPDATE:** Ok I finally got it.

Here is the classic light attenuation equation, easily found on the net:

```
float3 lightVector = lightPosition - surfacePosition;

float attenuation = saturate(1 - length(lightVector)/lightRadius);

```

It is relatively costly as `length(lightVector)` is actually doing this:

```
length(lightVector) = sqrt(dot(lightVector, lightVector);

```

moreover division operation `(/lightRadius)` is also quite costly.

Instead of computing light attenuation this way, you can compute it the following way, which would be much faster:

```
attenuation = saturate(1 - dot(lightVector, lightVector)*invRadiusSqr);

```

where invRadiusSqr can be pre-computed at CPU level and passed as a shader constant.

Moreover, you get a quadratic light attenuation as a result (instead of linear in the former case), which is even better, as IRL light has shown to have quadratic falloff.

Thanks everyone for your help!

# Answer
This is simply a kind of optimization given that `invSqrRadius = 1/SqrRadius`, instead of calculating the inverse squared radius for each light every time they simply cache it, the reason is that division is usually a "slow" operation at least when compared to multiplication.

This optimization is relevant especially:

* when the operation is done a huge amount of times for each light, so caching the value will free extra CPU/GPU cycles
* And assuming the memory access time for reading the value is actually faster than recalculating it.

Regarding how it is used, I am not sure about their specific implementation, but regarding `1/sqrRadius`, this is simply used for light attenuation, falloff and culling. It's also relevant for directional and spotlight, the only difference in case of spotlight is that you need to calculate the spotlight factor *after* applying the attenuation. Regarding directional lights like sun, it usually doesn't have any attenuation or falloff, so I would guess it will be ignored.

\[EDIT\] Just to elaborate more, it is *not* irrelevant data. The light Irradiance can be calculated using the following equation:

> **E** = Phi / 4\*pi\* rSqr;
>
> Where
>
> **E** is the area density of flux.
>
> **Phi** is radiance flux.
>
> **4\*pi\*rSqr** is the surface area of a sphere.

This equation explains why the amount of energy received falls off with the squared distance.

Another point is you need to calculate distance between the vertex and the light to calculate the light contribution on a specific vertex (this value is unlikely to be cached), the vertex can be in or out the light range which brings us to the next point where `Radius Square` is useful for culling.

If you want a practical example for calculating light falloff and culling, this is especially useful in tiled based deferred renderers, here is one example.
> 23 votes

# Answer
invSqrRadius isn't 1 - sqrRadius; it's 1 / sqrRadius.

It means that you can multiply by invSqrRadius, instead of dividing by sqrRadius (as division is typically much more expensive than multiplication)
> 6 votes

# Answer
The other answers here dealt with the inverse square radius, but I'm going to look at the squared radius instead (which concept3d touched on, but I believe it merits further discussion).

What squares are useful for is distance comparisons. We know that calculating the distance between two points involves a square root, and square roots are expensive to calculate, but if all we want to do is *compare distances* (in order to find which is less or greater, and do something interesting based on the result) we can throw out the square root.

If sqrt(x) \> sqrt(y) then it's also the case that x \> y.

For a light, the squared radius is the same as the distance between the light's center and it's maximum extent - squared, of course.

For lighting computations this can be used for an early-out case. If the distance between the point you're lighting and the light's center (squared) is greater than the squared radius, the point recieves no light and you don't need to run the rest of your computations. This is therefore just an optimization (a fairly common one) - we can use squared radius to do the distance comparison without expensive square roots, and at a cost of just a subtraction and dot product.

I, of course, don't know if this is *exactly* what BF3 is using it for, but I would expect that I'm not too far off the mark.
> 6 votes

---
Tags: lighting
---


# Question
Title: How can I play an animation in response to an event?
I've written a script to play an animation, but it starts immediately as my level loads. Instead, I want it only to start when triggered by some event or after a given timeout.

How can I do this?

# Answer
Uncheck the "Play Automatically" checkbox in the Inspector (Animation section). Obviously make sure you select the appropriate GameObject or prefab first.

Then use `animation.Play('yourAnimationName')` in the appropriate event handler.
> 2 votes

---
Tags: unity, animation, events, timer
---


# Question
Title: How to add a nice looking muzzle flash to the tip of my guns
I am making a top down shooter and would like to add a muzzle flash to the tips of my guns. So I have an idea of what I want to do which would be just a circle that would fade from yellow to white or from white to yellow, don't really know yet. I actually have know clue how to fade in and fade out colors in libgdx so don't know how to do that. I guess I could also pass in a texture that I can color yellow and append that to the tip of the gun but still would like to add a color fade. Of course, these are just my crappy little ideas. Anyone else have a better idea that would look better graphically and if so could you try to describe it in some detail that would be great.

Thanks!

# Answer
> 1 votes
Of course there are many ways to do muzzle flashes for top-down games, and it's often subjective and depends on your situation. However, by far the most common approach I've seen is to simply use a texture that is shown for a very short time when the gun is fired.

As an example, I'll use a game I made during a recent game jam, where I used the same approach.

Here's one of the textures (on black): This is then shown for 100 milliseconds.

You can play the game online to see how it looks in action.

Muzzle flashes add a lot of polish for very little effort. Animation is often not required because it is such a brief effect.

Some other things you can consider (keep in mind these will fall under subjective territory):

* Adding a temporary light source at the muzzle
* Randomly selecting different muzzle textures to use every shot
* Very subtle animation
* Use different shapes and colors for the flashes to give guns a unique character
* The size of the flash subtly affects the player's perception of how powerful the gun is (similar to how the gun looks and sounds). It might look strange if a powerful gun has a subdued muzzle flash and vice versa.
* If you want, do a little research on muzzle flashes in real life, as this can help you make more interesting muzzle flashes. For example, many distinctive muzzle flashes are due to different flash suppressors.

---
Tags: 2d, graphics, libgdx
---


# Question
Title: How to get a Coordinates of a 3D Object in Android
How is it possible to click on an area of a 3D Model (.obj-File) for example a cube, where you can get different Events of the six sides. For Example the orange area of the picture gives me a value of an Integer. The Cube can be rotated 360°.

# Answer
I assume this cube is made of triangles. You can simply ray cast the scene and check Ray/Triangle intersection for every face triangle. The ray cast function will return the triangle index and the 3D intersection point, once you have this info you can do what you want. You need to look for Unproject and ray/triangle intersection.
> 0 votes

---
Tags: android, 3d
---


title: Basic 2D Enemy AI

text:
# Question
Title: Basic 2D Enemy AI
This is the basic layout of my game: http://www.youtube.com/watch?v=qcd-CcKWjGU&feature=youtu.be

To make him move I just made it so you click left or right to move, just for a test.

Anyway, I just need an idea on what I need to do to the enemy follow the player. I'm not sure what variables I need and if I need some sort of angle variable so he can move in all possible direction. I probably just want to start out by making it follow the player on the x direction and then start making him move towards the player. This is my first time really having ago at proper AI as the last game I made invlolving AI what just making the enemy move right and turn left once reaching a certain point and vice versa.

This is all really have so far:

```
rectangle = new Rectangle(
                (int)position.X,
                (int)position.Y,
                texture.Width,
                texture.Height);

        float et = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        position += velocity;

        if (InputManager.Instance.KeyDown(Keys.Left))
            velocity.X = -3f;
        else if (InputManager.Instance.KeyDown(Keys.Right))
            velocity.X = 3f;

        if (velocity.X > 0)
            facingRight = true;
        else if(velocity.X < 0)
            facingRight = false;//This is just so that the enemy will look in the right direction of the way he's moving.

```

I also have an origin which is a Vector2 of the enemy's centre which I feel I may need.

# Answer
When there are no obstacles, you just need to check if the enemy is left or right, above or below the player-character. You can do so by comparing their X- and Y- coordinates. Then move the enemy in that direction.

When there are obstacles and you want your enemies to find a path around them, you will need a route-finding algorithm like A\*.
> 1 votes

# Answer
This should do the job, it will follow the player and face the player as well. Hope this helped.

```
using UnityEngine;
using System.Collections;

public class ChasePlayerAI : MonoBehaviour {

  public Transform target;//set target from inspector instead of looking in Update
  public float speed = 3f;

  void Update() {
    //rotate to look at the player
    transform.LookAt(target.position);
    //correcting the original rotation
    transform.Rotate(new Vector3(0,-90,0),Space.Self);

    //move towards the player if distance from target is greater than 1
    if (Vector3.Distance(transform.position,target.position)>1f) {
      transform.Translate(new Vector3(speed* Time.deltaTime,0,0) );
    }
  }
}

```
> 1 votes

# Answer
As Philipp stated, you just have to compute a vector from the enemy to the hero and move the enemy in that direction. That's how you do it when there are no obstacles:

```
// heroPos is the position of the hero.
Vector2 direction = position - heroPos;

//assuming here that velocity is a length and not a vector.
position += direction*velocity;

if (direction.X > 0)
    facingRight = true;
else if(direction.X < 0)
    facingRight = false;

```
> 0 votes

---
Tags: xna, c#, ai
---


title: SDL_GameController automatic detection

text:
# Question
Title: SDL_GameController automatic detection
Here's something that's been bugging me all day: Controller detection in SDL.

First thing is that it doesn't automatically detect when a controller is connected. Finding out when a controller is disconnected is no problem:

```
if(joystick.closed > 0) { SendEvent(E_CONTROLLER_DISCONNECTED); //cleanup }

```

I simply have a little loop to detect for new controllers:

```
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
joysticks_.Clear();
joysticks_.Resize(SDL_NumJoysticks());

```

Which *works* but is very, very slow. Regardless if I have a controller plugged in or not, this step alone takes 10-20ms. Even spacing it apart every few seconds, there are obviously noticable lag spikes whenever I am doing the detection; even with another thread, the lag spikes are still there. However I have not found any better alternative.

This type of behavior is imperitive to proper operation. This is especially so since if a controller gets disconnected, it won't automatically re-open in SDL when I reconnected it. Is there any better way to do this?

Oh, and as another point to make, I don't want to use SDL Events. They do basically what I've listed above, but don't work well with my existing multithreaded approach.

# Answer
> 5 votes
There's only one clean way, and that's to use a SDL\_Event regardless. I don't know how you are handling event so that it is inconvenient in your architecture, but have you considered Event Filters ?

Basically you register a callback that catches the events before they are pushed to the event queue. If the event is a SDL\_JOYDEVICEADDED or SDL\_JOYDEVICEREMOVED event, you can handle the joystick behavior there or warn some other thread and return 0 (do not push the event in the queue). Else you do nothing and return 1 (push the event in the queue). That way you can treat joystick event as soon as they are spawned, and you don't need to treat every event in the queue first.

For more specific answer, we need more specific details of your architecture.

---
Tags: sdl
---


# Question
Title: How to use camera transformation without depending on (1,-1) scale during spriteBatch.draw()
I am creating a 2D platformer type game in XNA.

I currently have a camera object, with a position/rotation/zoomlevel that I use to generate a transformation matrix to pass to SpriteBatch.Begin(). This allows me to draw at in game coordinates instead of screen coordinates.

The relevant bit of the Camera code:

```
public Matrix GetViewMatrix() {
            cameraMatrix = Matrix.CreateScale(new Vector3(1f, -1f, 1f))
                   * Matrix.CreateTranslation(position.X, position.Y, 0f)
                   * Matrix.CreateScale(new Vector3(zoom,zoom,1f))
                   * Matrix.CreateRotationZ(rotation)
                   * Matrix.CreateTranslation(new Vector3(screenWidth*0.5f,screenHeight*0.5f,0));
            return cameraMatrix;
}

```

Which is used like so:

```
spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null,
                  null, null, camera.GetViewMatrix());
//Draw Stuff
spriteBatch.End();

```

The problem is, that in order to get anything to actually draw, I have to scale by (1,-1) when I call spriteBatch.Draw(), otherwise I believe the textures get depth culled.

```
spriteBatch.Draw(content.Load<Texture2D>("whiteSquare"), Vector2.Zero, null,
                 Color.White, 0f, Vector2.Zero,
                 new Vector2(1f, -1f),
                 SpriteEffects.None,0f);

```

Notice the Vector scaling argument in the 3rd line of the last sample. My question is twofold:

1. How do I avoid having to pass this scaling argument/calling the longest form of spriteBatch.Draw() (kind of a violation of DRY, though I could wrap it I suppose).
2. Am I doing something wrong (not "it doesnt work wrong" but "thats the wrong way to approach that problem" wrong)? I have seen mentions of viewport.Update() functions and Matrix.CreateOrthagonal etc, but I'm not quite sure if using them is simpler/better than a simple custom camera sort of deal.

Thank you very much.

---

EDIT: After re-reading my post, and the first answers/comments, I think I have been thinking about this problem wrong.

I dont actually want to draw in game coordinates. What I want, is to be able to specify and work with game coordinates in such a way that positive y-axis is up, and that 1 unit of game distance equates to 1 meter equates to however many screen pixels it takes to make sure that you always view (for example) 10 meters of game distance from the left border to the right border of the viewport.

Preliminary experimenting led me to believe that passing in a world transform matrix to the spriteBatch.begin() method was the way to go about this, but now I think it may be a little more complicated. Does anyone have any advice for achieving the above goal? I have seen example code where every drawable entity implements a drawable interface that comes with a world translation matrix based on current entity position/etc, but where would I use such a matrix? Do I seperate spriteBatch.Begin()/End() calls for every drawable entity?

Sorry if this is a poorly formed question, trying to even wrap my head around the concept of the goal is proving difficult.

# Answer
> 1 votes
What you probably want to do is create wrapper around `SpriteBatch` or create extension methods for `SpriteBatch` that apply the desired per-sprite inversion to each `Draw` call. Then you could just do:

```
spriteBatch.DrawWorldSprite(texture, position, color);

```

(You could even create an overload with a scaling parameter, that does appropriate multiplication so you can scale things normally.)

This is by far the simplest thing to implement and use. It also doesn't violate DRY.

(It's been a while since I've done something like this. I can't remember if you need to mess with `SpriteEffects.FlipY` or origin changes to get the maths right.)

---

Note that the culling you are experiencing is not depth-culling. It is back-face culling. The default rasterizer state is `RasterizerState.CullCounterClockwise`. Changing it to `RasterizerState.CullClockwise` or `RasterizerState.None` will fix the culling issue. But you may find that your sprites are still upside-down.

---

The people suggesting `Matrix.CreateOrthographic` are probably suggesting you use `SpriteBatch` with `BasicEffect`. I don't think you need it, but it's handy to know about.

`SpriteBatch` basically provides an equivalent to a projection matrix (for "client space" or "screen space"), and using `BasicEffect` allows you to override that.

(Note: The matrix you pass to `Begin` is the equivalent of the view matrix, and the parameters to `Draw` are functionally equivalent to a world matrix.)

---

As an aside: You have the right idea with working in a sensible "world space" as much as possible, in this case with Y+ = up, and limiting the amount of code that transformation for rendering touches. Violating DRY on every draw call is nasty, but so is working in a convoluted co-ordinate system, just to suit rendering.

# Answer
> 0 votes
To #2: yes, you are doing it wrong. You are trying to change the framework's 2d coordinate system, with its origin at top left (this follows texture coordinates convention in directX). You are allowed to make that change; the trade-off is that you have to do it all the time, with every draw. Since that's what you seem to dislike, you might consider the drawback to be too great.

Depending on how far you are into your platformer code, it may too late to stop that effort and just "go with the flow". I assume you've already built some physics and logic that needs the y-coordinate to be positive-up. But if you can change it (never too late to refactor!), then you won't have to scale-flip everything all the time.

---

Edit: I do see that you already made this choice consciously. You wanted to operate in world coordinates, rather that screen coordinates. Again, this is a fine choice to make, but `Spritebatch` operates in screen coordinates. Quandary.

You could stop using `Spritebatch`. You can render world-space quads fairly easily. You'll miss out on other batching features the 2d portion of XNA gives you. But it's just more tradeoff consideration.

About your DRY consideration: if you just dislike passing too many parameters, you might consider C# named parameters. It could make your method calls cleaner.

---
Tags: xna, c#, 2d, matrix, platformer
---


# Question
Title: How to retrieve a cube collision by faces
I work for a while on a minecraft game (voxel). I am front a problem for a long time about the collision detection. I want recover the cubes collision from my highlighted black's cube like on the picture , but only on the sides. And not on the edges ! Actually i got all cubes in red and green when i check with the boundingBox method. Actually i use the method with the class "BoundingBox" to check for collisions. Can anyone help me or direct me on the best way for retrive the right cube ?

Code example with the boundingBox methode for check the collision

```
List<Node> nodeParent = regions[modelSelected.regionIndex].Nodes[modelSelected.Id].Where(m => modelSelected.BoundingBox.Intersects(m.boundingBox)).ToList();

```

i want to get only the green cube and not the red .. From the black cube in the middle

Thank's a lot guy

# Answer
you are in a voxel engine which means that each box should have a discrete x, y and z coordinate thus:

if you have a box at index (x, y, z) then you can get all neighbouring boxes by getting the boxes at index `(x, y +/- 1, z)`, `(x +/- 1, y, z)` and `(x, y, z +/- 1)`

edit: after some more info...

just detect the collisions for a line between the center of the current cube and the center of the potential neighbouring cube,

thus instead of intersecting with the bounding box of the cube you intersect with 3 lines strechting from `(x, y-1, z)` to `(x, y+1, z)` and `(x-1, y, z)` to `(x+1, y, z)` and `(x, y, z-1)` to `(x, y, z+1)`
> 2 votes

---
Tags: xna, c#, collision-detection, voxels, bounding-boxes
---


# Question
Title: Can I use a song from a YouTube remix in my game?
If I found a video with a remake/remix/version of a commercial song (for example, the theme of Super Mario Bros) with a CC BY licence, I can take this video for a commercial purpose like the background music of my game?

# Answer
> 10 votes
*Insert I-am-not-a-lawyer disclaimer here*

The notes of a song are already eligible for copyright. Taking the notes of a song and interpreting them differently creates a derivate work. This work must not be published when the copyright holder of the original song didn't give their permission.

When the composition of the song is not under a free license, the one who made a remix licensed as CC-BY likely already committed a copyright violation. The CC-BY license in this case is irrelevant, because they didn't had the right to publish the work under *any* license in the first place. When you reuse their work, you are also committing a copyright violation. Not against them but against the original IP holder (in this case Nintendo).

Such copyright trojan horses can not just slumber in the composition. Other parts of the work can also violate other peoples copyrights. Individual instrument or voice samples, for example.

What do we learn from that? Never trust allegedly free assets. When you want to publish a game, you should get a written contract from everyone who made your assets stating that they have the full copyright on the assets and that they will reimburse you for any 3rd party claims when it turns out that they have not. They will likely not be willing to give you that warranty for free, so you will have to pay them.

---
Tags: music, licensing
---


# Question
Title: How can I implement simple distributed processing in a Unity game?
I'm looking to set up a game which uses distributed processing. Just a simple brick shooter in unity with the distributed part being that the calculations for the falling blocks are handled by another PC and the transformations are sent back and applied to a clients machine.

To use this in Unity I assume I'll be using Remote Procedure Calls? Will I also require socket programming? Any other networking elements I require?

# Answer
> 1 votes
Depending on the requirements of your game, you'll only need to use RPC calls. That will require a NetworkView component (which you can set Observed to None, and State Synchronization to Off).

---
Tags: unity, networking
---


title: Negamax Checkers not working properly

text:
# Question
Title: Negamax Checkers not working properly
I'm trying to implement negamax in my checkers game. Sometimes the IA does the appropriate move, sometimes don't. Here is my code:

```
private int evalPawns(ArrayList<Pawn> pawns, int turn){
    int whiteCount=0;
    int blackCount=0;
    int who2move;
    if(turn == GameData.PLAYER1)
        who2move = -1;
    else
        who2move = 1;
    for(Pawn pawn:pawns){
        if(pawn.getPlayer() == GameData.PLAYER1){
            whiteCount++;
        } else {
            blackCount++;
        }
    }
    return  (whiteCount-blackCount) * who2move;
}

public int negaMax(ArrayList<Pawn> pawns, int depth, int turn){
    ArrayList<Pawn> pawnTemp;
    pawnTemp = copyPawns(pawns);

    Move[] legalMoves = getLegalMoves(turn, pawnTemp);
    int maxScore = Integer.MIN_VALUE;

    if(depth == 0 || legalMoves == null)
        return evalPawns(pawns, turn);

    for(Move move:legalMoves){
        makeMove(move, pawnTemp);
        int score = -negaMax(pawnTemp, depth-1, opponent(turn));
        maxScore = Math.max(maxScore, score);
    }
    return maxScore;
}

public Move findMaxMove(Move[] legalMoves, ArrayList<Pawn> pawns){
    int maxScore = Integer.MIN_VALUE;
    Move bestMove = null;
    for (Move move:legalMoves){

        makeMove(move);

        int newScore = -negaMax(pawns, 5, GameData.PLAYER2);
        if (newScore > maxScore){
            maxScore = newScore;

            bestMove = element;
        }

    }
    return bestMove;
}

```

Here are 2 moves examples:

# Answer
At first glance, it looks like you have the algorithm correct. The part that jumps out as possibly wrong is this:

```
if(maxScore == 0){
    bestMove = moves[rand.nextInt(moves.length)];
}

```

`maxScore` of 0 means that the best move the AI can make will lead to no change in the relative number of pieces per player (assuming both sides continue to play correctly). I would expect that to happen a lot in checkers. Choosing a random move in that situation seems like a bad idea.

The other thing you haven't covered is what happens when there is no legal move to make. That should be scored as a game loss for the player whose turn it is.
> 0 votes

# Answer
For any adversarial search you need to be sure your evaluation function is consistent with the implementation, the move iteration is correct for each turn, that you are reversing any applied moves properly, and that your initial invocation is correct.

It looks to me as if you are not calling it properly for the second player, for the first player the invocation is normally negamax(node, depth, 1), but for the second player it is normally -negamax(node, depth, 1).
> 0 votes

---
Tags: java, ai
---


# Question
Title: How can I export a .FBX file from Unity3D at runtime?
I want to export an object as a `.fbx` at runtime in Unity3D.

I've made a C# script to export a mesh filter or skinned mesh renderer to a `.obj` file at runtime, but I want the animation and skin support that only `.fbx` supports.

After some research, using the Autodesk FBX SDK or some other external `.dll` seems like my best option. How do I call Autodesk's FBX SDK at runtime? Is there another external `.dll`s I could use for this?

Another option could possibly be to write the mesh information as a text file, then convert to `.fbx` to export.

# Answer
> 1 votes
Autodesk has a FBX Converter, which can take .objs and output .fbx. Included is a command line tool, which you could call from your game at runtime. As long as you do not want to have that functionality distributed to every player, that should be enough.

---
Tags: c#, unity, fbx, export
---


# Question
Title: Why aren't subsequent glDrawArrays showing up?
I am attempting to redraw with the same arrays using glDrawArrays in a GLKView on iOS. When I comment out any two of these calls, the other draw call draws as I expect. My last hunch was that I was attempting to draw at the same depth, so I introduced a depth uniform and am setting the depth in the vertex shader like so:

```
gl_Position = vec4(position.xy, 0.1*depth, 1.0);

```

the depth coming in is a lowp vector with a value of 0, 1, or 2. This didn't have any effect.

Here is my drawRect: method

```
- (void)drawRect:(CGRect)rect
{
    glClearColor(0., 0.0, 0.0, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Render the object again with ES2
    glUseProgram(_program);

    // the colors
    glBindVertexArrayOES(_vertexArray);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _wheelMaskTexture);
    glUniform1i(uniforms[UNIFORM_TEXTURE], 0);

    glUniform1f(uniforms[UNIFORM_COLOR_DEPTH], COLOR_DRAW);
    glUniform1f(uniforms[UNIFORM_COLOR_ANGLE], _angle);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    // the sat
    glBindVertexArrayOES(_vertexArray);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _satMaskTexture);
    glUniform1i(uniforms[UNIFORM_TEXTURE], 0);

    glUniform1i(uniforms[UNIFORM_COLOR_DEPTH], SATURATION_DRAW);
    glUniform1f(uniforms[UNIFORM_COLOR_ANGLE], _satAngle);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    // the bright
    glBindVertexArrayOES(_vertexArray);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, _brightMaskTexture);
    glUniform1i(uniforms[UNIFORM_TEXTURE], 0);

    glUniform1i(uniforms[UNIFORM_COLOR_DEPTH], BRIGHTNESS_DRAW);
    glUniform1f(uniforms[UNIFORM_COLOR_ANGLE], _brightnessAngle);

    glDrawArrays(GL_TRIANGLES, 0, 6);
}

```

My GLKView is set up with a `drawableDepthFormat = GLKViewDrawableDepthFormat24`. I haven't set up any transforms because what I'm drawing is basically a simple color wheel.

There is no world or model transform. I'm simply drawing the same square 3 times one on top of the other without transforming. There are 3 different mask images that are used to mask out the fragments that I care about in the fragment shader like so:

```
gl_FragColor = vec4(rgb, texture2D(wheelMask, texCoord).a);

```

Why wouldn't all three `glDrawArrays` calls draw as expected? As I mentioned early any one of them by themselves draws as expected. As it is, with all three, only the first `glDrawArrays` draws as expected.

# Answer
You do not apply any transformation to the rectangles. So the codes renders the same geometry 3 times with modification applied to the material. Suppose we have a 3x3 screen (i know very small)

and your rectangle ends up drawing over these pixels

```
[x][x][ ]
[x][x][ ]
[x][x][ ]

```

your final framebuffer after the first draw call could look like this:

```
  color      depth
[r][r][ ] [0.1][0.2][ ]
[r][r][ ] [0.1][0.2][ ]
[r][r][ ] [0.1][0.2][ ]

```

note: r is for red, i didn't feel like writing a full 4 byte color (1,0,0,1) .1 is the distance from the screen to the fragment at this location.

for the first quad, all the fragment were colored because there was nothing yet. so you end up with (in this case) 6 new fragment

now when you draw your second draw call. you don't change the geometry. when the top-left fragment is generated, it'll generate the exact same depth. So since the new depth is not closer then the old depth. a new fragment is not generated and the 2nd material is not colored.

A new fragment is generated according to

```
newDepth<oldDepth

```

and not

```
newDepth<=oldDepth

```

because if 2 fragment are at the same depth it assumes that they are at the same position. Since depth buffers are usually 16 bit (65536 different numbers) it means depth in opengl is discrete rather then continous (like real euclidean space). But they will skip the new fragment since it saves computation and that in reality you wouldn't really see the difference, except like in your case where you have 2 quads that are literally in the exact same position.

So to answer the question, if you want to see all the different materials. you need to transform the other instances of the quads (either rotate, translate or scale)
> -1 votes

---
Tags: ios, glsl
---


# Question
Title: How do I apply a Isometric tile to a Diamond shaped Div
I want to be able to apply my isometric tile

To a diamond shaped div

However I can't seem to create the isometric shaped div.

Closest I got to it was this http://jsfiddle.net/P3yKr/2/ but even then thats not going to allow me to apply the image as the background for it.

# Answer
> 0 votes
You can leave your divs as rectangles, and simply make the corners of the image transparent. You will have to a little math when detecting clicks properly, but it will be easier in the long run.

I have created a modified version of your tile with transparency:

And have made a rudimentary tiling system with this image in CSS: http://jsfiddle.net/jcpmcdonald/gMV76/20/

Alternatively, I might look into using an HTML5 game engine such as CraftyJS, or Isogenic Game Engine.

---
Tags: isometric, css
---


# Question
Title: How do you make a bullet ricochet off a vertical wall?
First things first. I am using C# with XNA. My game is top-down and the player can shoot bullets. I've managed to get the bullets to ricochet correctly off horizontal walls. Yet, despite using similar methods (e.g. https://stackoverflow.com/questions/3203952/mirroring-an-angle) and reading other answered questions about this subject I have not been able to get the bullets to ricochet off a vertical wall correctly. Any method I've tried has failed and sometimes made ricocheting off a horizontal wall buggy.

Here is the collision code that calls the ricochet method:

```
//Loop through returned tile rectangles from quad tree to test for wall collision. If a collision occurs perform collision logic.
for (int r = 0; r < returnObjects.Count; r++)
    if (Bullets[i].BoundingRectangle.Intersects(returnObjects[r]))
        Bullets[i].doCollision(returnObjects[r]);

```

Now here is the code for the doCollision method.

```
    public void doCollision(Rectangle surface)
    {
        if (Ricochet) doRicochet(surface);
        else Trash = true;
    }

```

Finally, here is the code for the doRicochet method.

```
    public void doRicochet(Rectangle surface)
    {
        if (Position.X > surface.Left && Position.X < surface.Right)
        {
            //Mirror the bullet's angle.
            Rotation = -1 * Rotation;
            //Moves the bullet in the direction of its rotation by given amount.
            moveFaceDirection(Sprite.Width * BulletScale.X);
        }
        else if (Position.Y > surface.Top && Position.Y < surface.Bottom)
        {
        }
    }

```

Since I am only dealing with vertical and horizontal walls at the moment, the if statements simply determine if the object is colliding from the right or left, or from the top or bottom. If the object's X position is within the boundaries of the tile's X boundaries (left and right sides), it must be colliding from the top, and vice verse. As you can see, the else if statement is empty and is where the correct code needs to go.

# Answer
It looks like your code to mirror the bullet's angle just flips the sign of the angle. This works great for reflecting an angle about the x-axis. 45 degrees becomes -45 degrees, etc.

Now imagine reflecting off a wall that itself has an angle of 90 degrees. In this case, 85 degrees is reflected to 95 degrees; 45 degrees becomes 135 degrees, etc. Basically you need to transform the bullet angle to be relative to the wall before flipping.

Instead of just doing `rotation = -rotation`, I would suggest a function for reflecting an angle about another angle `A`: `rotation = A - (rotation-A)`. (notice what happens when `A == 0`)

Now find the angle that your wall is at, and use that as A. You could use an if-else statement to choose between 0 and 90; or you could calculate the angle from the two endpoints of your wall, and then you could handle walls at arbitrary angles just as well as vertical or horizontal walls.
> 2 votes

---
Tags: xna, c#, 2d, geometry, angles
---


# Question
Title: Single or multiple inheritance for game world objects
So I am currently laying out on paper the system I want to code for a game in C++.

Now currently I am debating whether to have e.g. a class object\_door that inherits from another class object\_interactive, which inturn inherits from the base class object

OR

have a class object\_door that inherits from both the class object and another base class interactive.

Is there any advantage to either way of doing inheritance? Or is there maybe a commonplace convention for this?

# Answer
> 2 votes
**Update:** I have learned quite a bit about game programming since I wrote this. I think it would be relevant to mention Robert Nystrom's Game Programming Patterns book, which contains a lot of information on ways of structuring your game code.

---

## Multiple inheritance

In C++, you want to be careful with multiple inheritance. It can really add complexity to your code. Especially when you include two objects that have the same base class. This is known as the diamond problem. There are, however, cases were multiple inheritance has it's uses, as seen below.

### How to properly use multiple inheritance

In Java, there is a built-in `interface` type. This is the type of situation were an interface could be used. But as you know, C++ doesn't really have a built-in interface type. You instead create a class that contains only pure virtual functions to create an interface. This class shouldn't cause any diamond inheritance issues, however, so avoid letting this class inherit from other classes if it isn't logical to do so.

While this is still technically multiple inheritance, it still avoids a lot of the problems that can be introduced by normal multiple inheritance (like the diamond problem).

Again, multiple inheritance has it's uses, but can add complexity. I recommend that you read this SO page on multiple inheritance.

## Designing your game

Many times, you can think of how such hierarchies would by organized in real life. In this case, multiple inheritance may be the way to go (remember, this is only how *I* would design it if it was *my* game). Here is my reasoning: Not all doors are directly interactive (think of garage doors). Think. Later on, you may want doors that aren't interactive.

Doors are really just a concept that can be thought of in this way:

* All doors can be in an "open", or a "closed" state.
* All doors have some way of opening or closing them (except in the case of one-way doors). This may be direct, or indirect (as in a electrical signal).

This doesn't mean that you need to have an abstract door base class, but you should consider that you may want a Minecraft-like iron door (which can only be controlled by redstone). In this case, the only difference between wooden and iron doors is that iron doors have a different `onBlockRightClicked` method. So there isn't really a reason to have a single `door` base class (really, how many doors do you need?).

So if you don't need a `door` base class, what should you do? My recommendation is that you consider moving your `object_interactive` code to your base `game_object` class. This is because you may have a lot of items in your game that are interactive. I do not know exactly how you are doing things, but I would assume that you would have to cast every object into an `object_interactive` after checking that it is an `object_interactive` every time that you want to use them as an interactive object.

In the end, it really comes down to how your game is structured. It is really hard to tell you what to do unless we were actually on a team with you discussing this in person.

# Answer
> 1 votes
You might also want to consider a component based approach for your game. I can point you to these two articles on the subject:

If you search for "component based game architecture" or "entity component system" you should be able to find a lot more on the subject.

---
Tags: c++, inheritance
---


# Question
Title: LWJGL Resize window and glTranslate breaking screen resolution
I'm trying to make a 2D Tile RPG game with LWJGL but I'm having a problem with the display resizing. I want the user to be able to re-size the window to whatever size they want just by expanding it (as opposed to letting them pick a resolution option from a list).

See the images below for the problem.

At default resolution:

At a re-sized resolution:

As you can see the tile is drawn correctly in the first image. However, after moving the camera and resizing the display the tile gets cut off as it moves away from the bottom-left corner of the screen.

The default screen-resolution is 800x600. I have a camera object that moves based on the player using the WASD keys. I decide what's to be drawn by using glTransaltef(camera.x,camera.y,0). Should I use if(Display.wasResized()) in the game loop then get what the new resolution is and use it in the glTranslatef function somehow? Any help or suggestions would be great!

EDIT: I added the code in Fletcher D's answer however it produced this:

The tile doesn't get cut off anymore but in the image above the tile is being drawn at a size of 1x1 pixels. Also when the screen resolution changes the resolution of everything on screen changes, this is not what I want. I want the screen to simply display more of the world. As I said I'm using a panning camera that moves with the player's WASD keys. So if the world is currently being displayed at 0,0 to 800,600 and the player re-sizes the window to 1080x720 I want the display to show the world from -140,-60 to 940,660. (Maintaining the center of the screen at the moment of being re-sized.

# Answer
You need to change OpenGL's projection matrix so that it will change the area of the world that is drawn within your window. The projection matrix is what OpenGL uses to determine how the world will be *projected* onto the screen. Most likely, you're setting this in the beginning of your program to say "draw the area of the world from (0,0) to (800,600)." Then, when the window is resized, it just keeps doing that, stretching as necessary to fit in the window.

Since your game is 2D, I'm guessing you set up your projection matrix with `glOrtho()` in the beginning of your program. Sound familiar? Try this: When you notice that the window has been resized, call something like `glOrtho(0, WIDTH, 0, HEIGHT, -1, 1)`. You may need to tweak the actual values, but that should get you rendering a different area.

Notice how this means you can do `glOrtho(-WIDTH/2, WIDTH/2, -HEIGHT/2, HEIGHT/2, -1, 1)` and your camera will center to the point you want, instead of treating it as the lower left corner.

Edit: I just remembered you probably also need to change the viewport, to set the area of the screen which is being rendered to. Try this code whenever the window is resized:

```
glViewport(0, 0, width, height); //NEW
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, -1, 1);

```
> 1 votes

---
Tags: opengl, java, lwjgl, window-management
---