title: How to get a component from an Entity?

text:
# Question
Title: How to get a component from an Entity?
In my Entity class I've got a function that returns a specific component, that looks like this:

```
template<typename ComponentType>
ComponentType* GetComponent() {
    for(unsigned int i = 0; i < m_Components.size(); i++) {
        if(ComponentType* cmp = dynamic_cast<ComponentType*>(m_Components[i])) {
            return cmp;
        }
    }
    return NULL;
}

```

I heard that dynamic\_cast is not really elegant and that is also slow. Is there a way to optimaze this code and if so how? Is it really a big deal or does it not matter in a small Super Mario sized 2D platformer?

# Answer
> I heard that dynamic\_cast is not really elegant and that is also slow.

"Elegant" is the most worthless word in a programmer's vocabulary. Strike it from your lexicon.

Every programmer has an utterly different idea of what "elegant" means. If you like the code and it works, why worry about if some armchair engineer on the Internet thinks it's "elegant" or not? It's not their code, it's not their project, it's not their concern.

Regarding whether `dynamic_cast` is slow: it's not the fastest option but it's a perfectly good one. Much bigger and more complex software than your game manages to use `dynamic_cast` frequently and still work just fine.

> Is there a way to optimaze this code and if so how?

There's always a way to optimize code. Do you have a measured and verified performance problem?

Your `GetComponent` is not optimal, no. There's a few things you can do to make it faster if you want.

You can cache the component type using a `type_index` which can be constructed with the `typeid` operator. This won't work as intended if you're querying for base classes/interfaces, though.

If using the `type_index` then sort the list and do a binary search instead of a linear search. If you stick with `dynamic_cast` then sorting wouldn't quite work, though you could cache the results and do binary searches on those. `boost::flat_map` provides a premade data-structure for this or you can roll you own with a `vector` and `std::lower_bound`. You could also use a hash table but C++'s `unordered_map` is not likely to be faster unless your objects have a very large number of components (hundreds or thousands) for some crazy reason.

Querying a "system" in ECS parlance using an O(1) hash table of game object IDs to component indices would maybe be faster than the binary search... maybe. As with all performance work, measure and find out for sure. It'll depend on a lot of factors.

Your real perf gain will just come from not calling `GetComponent` more than you have to. Doing work faster will never be as fast as not doing it at all.

You can replace the standard RTTI with a custom system (difficult and only slightly faster) or a simple enum (inflexible) or a string name (slower) or several other options. I've been checking lately whether the default RTTI is fast enough for big AAA games and perf-sensitive apps (at least on PC and the latest consoles) and so far the data I have indicates a strong "Yes."

> Is it really a big deal or does it not matter in a small Super Mario sized 2D platformer?

Almost certainly not a big deal. If you want to know for sure, measure your performance and find out. The engines I work with will have entirely different bottlenecks than your code, which will have different bottlenecks than any other engine or game.

Measure.

Then make a hypothesis about anything you can improve, update your code, and measure again and make sure you see the changes you expected. Often you'll get a surprising regression, even if you're doing what some game industry veteran on the Internet told you is the obvious fix.

Measure again.
> 5 votes

# Answer
It depends how often you call this function. If you call it only at start of a game and save pointers you shouldn't care about `dynamic_cast`. If you call this function in game loop (why?) better avoid it. But if your game is small I think \`dynamic\_casts' will not decrease performance significantly even if it will be called in game loop few times per frame.

To avoid dynamic\_casts you can add static function `GetType` to each component that returns type of component (for example enum). So check will be:

```
if ( ComponentType::GetType() == m_Components[ i ].GetType() ) {
    return cmp;
}

```

But if you want to write engine and allow to add new types of components by other people without changing engine code you can't use enum as `GetType` return value. In that case you can use 32-bit value. If someone wants to add new component he adds `int GetType()` method and returns some random number, like this:

```
static int GetType( ) {
    return 12636354;
}

```

In this case two different types of components almost always will have different `GetType` values. Of course almost is not always so you should add some code that checks if some two types of components returns same value. You can make it in some kind of component type registrator class.
> 2 votes

---
Tags: c++, entity-system
---


# Question
Title: How to output to the Oculus and a 2D screen?
We'd like to present an Oculus game to a large group of people. Not everyone will have an Oculus headset, so we'd like to output to both the Oculus and a second display. The problem is that the project uses an Oculus plugin to render its output, so all they output is two distorted circles, which doesn't display well when not wearing the Oculus headset.

I thought of making a second Unity client (the "audience" client, running on the same computer as the Oculus application) that receives the output texture of an "audience" camera from the client running the Oculus version.

My question is: Can I use the network to send the output of a camera to the "audience" client so I can set it up for the second display, bypassing the Oculus plugin? How would I get the input on the "audience" client to map it to the screen?

# Answer
# Best solution

Run an OVR Mirror and display another output window on your projector/monitor. You can attach it to one of the OVR 'eyes' if you are feeling lazy, or create a new camera and run it from there for better performance.

# Using networking

You would run the client in 2 ways:

1. Directly answering your question: To Remotely see everything **exactly** from the "main camera", means rendering on the original program/host. This is done using a render texture. Now divide this texture up into an array of coloured pixels, and send this multi-million length array to the remote client as a message... for every frame. Expect delays, low resolution and high complexity.
2. A **better** way of using networking to mirror a scene is to run the program like a "multiplayer game" where everything has a *network view* attached to it and is replicated on the secondary app. Essentially you are connecting a "spectator" to the game. This still adds complexity because "single-player" games are often hard to convert to "multiplayer".

# Another way without networking

Use the oculus in extended view, and run the app in a super-widescreen resolution popup window. Render your "Main\_Camera" in one half of the resolution, and the Rift viewports on the other half. This is similar to OVR Mirror windows, without window boxes but less predictable (very dependent on specific resolution, monitor placement etc).
> 2 votes

---
Tags: unity, camera, networking, screen, oculus
---


title: Constraining Movement to Path/Splines

text:
# Question
Title: Constraining Movement to Path/Splines
First of all take a quick look at this :

https://www.youtube.com/watch?v=LQtKP-EymFM

So this is to give a idea of what I mean by following a path, basicly I am trying to understand how something like that would work out, I don't mean the sonic like motion, what I want is how do I constraint the movement to predefined path. But still being able to Jump.

The trouble I am having is how does it behave when falling from the loop? how does it know in the Spline/Path it should align to?

What I want is a some sort or explanation on how something like that would be implemented, the motion is not my concern.

# Answer
You don't constrain the vertical or lateral movement. The path line is only for controlling the depth and direction of the player character.

You can see from the video the little white line that's attached to the green path. That white line shows where the character is "attached". The white line is just the closest point on the line to the player. Imagine you can draw a perpendicular line to the path that always faces 'forward'. This line defines the 'forward' and 'backward' for the character as well. We'll call that the forward vector, and that's the most important thing we get from the guide path. The forward vector tells us how to move the character in each update iteration. If your character has forward velocity heading into a corner, the forward vector is going to steer your character around that corner.

Basically, you need to find the closest point on the guide path, and use the forward vector found from that point to steer the character. Most of the time that'll just be regular old forward. However, that forward vector will also steer you around 3D corners and it'll rotate the character so they can move through the loops.
> 1 votes

---
Tags: movement, splines
---


title: Gamemaker Key Press Duration

text:
# Question
Title: Gamemaker Key Press Duration
I am looking for a way to track the duration of a key press in gamemaker. I was looking into alarm functions, but I figured there's a more elegant way. How can I track the duration of a keypress?

# Answer
You could simply have a variable that you will increment each step if the key is currently down, and read its value once the key is released.

Create event:

```
keyTimer = 0;

```

Step event:

```
if (keyboard_check(ord('A'))) {
    keyTimer += 1;
}

```

Key A Released event:

```
timePressed = keyTimer;
keyTimer = 0;

```

In this example, I am reading the time the user has pressed the A key and putting the value in the timePressed variable.
> 2 votes

---
Tags: game-maker
---


# Question
Title: Optimizing Collision Detection in a 2D Game
I am optimizing my "little" Java (LibGDX) shooter game, and perhaps unsurprisingly, collision detection is a "bottleneck"; I've kind of reached my performance goals already, but I want to tweak the game anyways.

Every monster in the game can collide with every other monster + friendly bullets. The game is a single-screen shooter. I am using a QuadTree.

In my Sprite/Entity-class, I have a method:

```
public boolean canCollideWith(Sprite s) {
    return true;
}

```

This method is called twice in a loop within a loop, meaning that when enough Sprites are added, it gets called a lot. It shows up as a high HotSpot in VisualVM.

I override the method in various sub-classes, e.g. in the Bullet-class:

```
@Override
public boolean canCollideWith(Entity e) {
    if (friendly) {
        return (e instanceof Monster && !(e instanceof Player))
                        || e instanceof Missile;
    }
    else
        return e instanceof Player || e instanceof Warp;
}

```

...and in the Monster-class:

```
public boolean canCollideWith(Entity e) {
    return e instanceof Bullet && ((Bullet) e).isFriendly() || e instanceof Monster || e instanceof Tagger || e instanceof Flower || e instanceof Shockwave;
}

```

I don't really like these instanceof's in the first place... what would be an elegant and a fast solution to optimize this (hopefully both :)?

Excluding the QuadTree part, here's my whole collision detection method:

```
public static void collisionDetection(Array<? extends Sprite> sprites) {
        for (int i = 0; i < sprites.size; i++) {

            Sprite s1 = sprites.get(i);

            if (!s1.isCollidable()) continue;

            for (int k = i + 1; k < sprites.size; k++) {

                Sprite s2 = sprites.get(k);

                if (s1 == s2) continue;

                if (!s2.isCollidable()) continue;

                if (!s1.canCollideWith(s2)) continue;
                if (!s2.canCollideWith(s1)) continue;

                boolean intersects = s1.intersects(s2);

                if (intersects) {
                    s1.fireIntersectionEvent(s2);
                    s2.fireIntersectionEvent(s1);

                    s1.intersectsWith(s2);
                    s2.intersectsWith(s1);
                }
            }
        }
    }

```

Thanks for any ideas.

# Answer
> 3 votes
The most effective way to improve collision check speed is to decrease the number of entities that needs to be checked against. Spatial partitioning such as octree helps but you can make further improvements.

Suppose if currently you have one big list of collidables contains objects and bullets and in each collision check step you are looping through all the objects (ignore spatial partitioning for now) and you are interested in finding out whether objects and bullets collide. Bullets and bullets do not collide. If that is the case, then there is no need for bullets to be included in the collidables list. Applying this strategy, you would create 2 object groups, bullets and objects.

In each step for objects:

```
- update new position
- add to collidables list
- check for collisions
- resolve

```

In each step for bullets:

```
- update new position
- check for collisions
- resolve

```

Assuming you have equal number of bullets to objects ( most games have far more bullets than objects ) then you would have decreased the neccesary check by a factor of 4!

Keep applying this strategy and re organize objects into groups and you should probably see a large improvement in performance.

# Answer
> 1 votes
Your canCollideWith method should be so that `s1.canCollideWith(s2) == s2.canCollideWith(s1)`I think. If not it means that collision will differ according to your array order. And if both return the same results you can test that only once.

Then in your code, you give two differents definitions of your canCollideWith method `canCollideWith(Sprite)` and `canCollideWith(Entity)`, so when you call your `canCollideWith` method with a sprite, I think it won't call the method with an entity passed and it will always return true.

---
Tags: java, collision-detection, libgdx, performance
---


# Question
Title: Collision between Mesh Plane and 2D Sprite
I've just recently started programming using Unity and made a couple of games with it, I'm trying out more and more advanced stuff as I do more games, but right now...

I'm trying to make a game that's basically a way simpler clone of pokemon y/r/g/b (I'm only concerned about tile placement, player movement / collision, and dialogue boxes at this time)

I tried about 3 methods for tile placement and found that using a mesh worked best for me (using tiled and tiled2unity) and imported the tmx files into unity.

Now, I just dont know where to go from here.

Starting with the player, I don't want to add physics since most games like this doesn't really have physics involved. So I tried adding a box collider to the player then a controller that uses transform.translate. Unfortunately, I dont think the colliders work nicely with transform.translate.

In this scenario, is the best setup for the player simply just using a kinematic rigidbody2d then adding the code/methods to collide with the map? Also since translate might be a bad idea, is transform.position a better alternative to use? (note that the player moves in increments in a "tile-like movement", any comments or suggestions?)

I'm also quite surprised by the lack of simpler games such as this one. Most of the examples I can find online are physics based platformers and top-downs that use code like velocity, addForce, with physics components involved. Any available source code that I could study would be welcome.

(I've also posted this on Unity Forums but people frequent here more often)

# Answer
> 0 votes
I have a simpler solution without using any physics or rigid bodies. For your character, it need to have both x,y position as position in screen and i,j as position on the grid with a flag called isMoving. When the character wants to move to i+1, j. Check if the cell at i+1, j is free. If so, set flag isMoving to true and set character i,j to i+1, j and do the necessary animations(changes to x,y) that walks the character from i,j to i+1,j. As long as isMoving is true, the character will not respond to any movement commands. When the character finishes his walk to the destination grid, set isMoving to false and repeat.

# Answer
> 0 votes
Actually, there's no ready response for your problem. You can solve it in a variety of ways.

If you are working with a "tile-like movement", you can simple check the next tile to see if is passable and only compute the movement if it is. It's a simple check if you have a array representing your world. Or a limited raycast if not.

Also, Unity documentation says something in the lines "if it moves, attach a rigidbody to it". So, you can do it, and set "Gravity Scale" to 0. But depends on what works best for your particular case.

---
Tags: unity, 2d, collision-detection, sprites, tiled
---


title: Tetris rotation without using arrays

text:
# Question
Title: Tetris rotation without using arrays
I am making a Tetris clone. Is there any way that I can avoid using a 2D array for storing a Tetris block?

**EDIT**: Suppose I have an array to store an L-shaped piece:

```
1 0
1 0
1 1

```

But for the sake of rotation, I do that shape as this:

```
0 1 0 0
0 1 0 0
0 1 1 0
0 0 0 0

```

I can do this in either objects or arrays. If I use objects then create four objects for each "square", and I can store the position of each square, and rotate it about the piece's center. But I am finding a better way to optimally perform a rotation on the piece. I believe rotating this array 90 degrees would take O(n^2) time. I try to avoid making rotated copies, and instead rotated on the fly. What algorithm or approach should I use?

# Answer
> 1 votes
If you really really really wants to you can store the data as a 1D array with each 2 pairs means an block's x and y position. Like so \[-2,0,-1,0,1,0,2,0\] with (0,0) being the implicit center of rotation. You can improve on this further by not using array of ints but pack your data into the smallest bits possible.

---
Tags: optimization
---


title: adventure game architecture

text:
# Question
Title: adventure game architecture
I would like to make an adventure type game functioning similarly to machinarium or broken sword. The only way I can think of doing this is to draw an image as a background on a canvas and use some animated sprites that moves around and responds to touches on the screen.

But having a runnable that keeps re-drawing the canvas seems like a waste of memory to me, especially when it comes to larger images like the background.

I'm pretty new to game development and canvas animations and I was wondering if anyone could point me in the right direction? What would be good training for an adventure type game?

# Answer
One of the most commonly used methods to render images involves double buffering. All of the data to be drawn to the screen is drawn to the "Back Buffer", and at the end of the draw routine, it swaps positions with the "Front Buffer" which is located on the screen. Your 2D screen has no understanding of the concept of layering, so if you don't redraw the background each frame (or use an algorithm to only redraw the exposed pixels) then you wont have a background. This is just one (though the main) approach to rendering to the screen, but there is no way to get around having to draw what you want to see on the screen.

Your initial idea is going in the right direction. Stay the course.
> 3 votes

# Answer
My generic advice would be not to worry too much about performance when you're starting out. As mentioned in the other answers, it's possible to redraw only those portions that have changed, but you're already getting into a level of performance optimization that's premature when you're learning to create the basic architecture of your game. When you're ready to do optimization, it's worth analyzing the problem in terms of what are the ACTUAL bottlenecks of your game, not what seem like they ought to be.

In general, it's very common to have a main game loop that cycles through:

1. Getting user input
2. Updating Game Logic
3. Drawing the scene

Where, in step 3, you're drawing the entire scene, even those parts that don't necessarily need to be redrawn. As far as a useful starting point, I recommend this blog post:

http://www.godpatterns.com/2010/08/how-to-make-adventure-game.html

In particular, you're going to want to learn about such things as navmeshes, which are pretty fundamental to that genre.
> 1 votes

# Answer
If you are starting to develop your adventure game, you probably have a great story, graphics, music... Sometimes it may be a good idea to try some free engines and editors just to get an idea how they work - and use them as an inspiration. Or use them for your project, of course. I mean for example something like GameStylus, which is a specialized on-line game editor and game engine for adventure games - and it is free.
> -1 votes

---
Tags: java, android, architecture
---


# Question
Title: Is AGS outdated for Point & Click Adventures?
I am working on a Point and Click Adventure game being coded on the AGS engine, and just recently, the question of 'is this outdated?' has come up.

I'll admit, AGS is a rather old, and kind of went out of style with the P&C genre itself, but I have not found anything quite like it that specializes in this specific format of games.

So, is it outdated, and if so, is there a better alternative?

# Answer
> 29 votes
There are currently three popular graphic adventure game engines on the market:

Each of the engines has a different *philosophy*, and generally, the games developed with each of these engines end up having very distinct styles.

But there is nothing preventing you from using one of these engines and developing something out of the conventional style - except for a few minor details, their feature sets are very similar.

I'll give you a quick run over the main characteristics of each of the engines, so that you know what is available to you. In comparison, it might be reasonable to say that Adventure Game Studio is not as modern as its siblings, but I'll leave that judgement to you.

**Adventure Game Studio**

*Image from Gemini Rue developed with Adventure Game Studio*

**Wintermute Engine**

*Image from Alpha Polaris developed with Wintermute Engine*

* Very powerful and flexible
* Supports 3D characters and shaders
* Significantly more difficult to use
* Free and open source

**Visionaire Studio**

*Image from The Whispered World developed with Visionaire Studio*

* Smooth, high resolution graphics
* Extremely easy to use
* Does not require any scripting
* Requires commercial license

Note: The developers are currently trying to add support for 3D characters and a few other features that should make it capable of competing directly with Wintermute.

# Answer
> 3 votes
I think it depends on what you are trying to achieve ...

a lot of retro p+c pixel games tend to be made using AGS & there is as mentioned loads of help on the community as well as plenty of free games, demos & so on for download but it does lack support for high resolutions seeing as it only goes up to 1024x768 (I think)

-- * --

As for me I chose Visionaire Studio because it works in a similar way to VB (visual basic) - a lot of the game design process can be done visually & by selecting actions & options via dropdown menus, tabs & pop-up boxes as opposed to having to write loads of code.

I wanted full HD support! various set resolutions from 320x200 to 1920x1200 or you can set a custom value in the explorer tool. (standard HD res is 1920x1080)

Also as far I'm aware there is a working mac port intended for the next release as well as loads of other nice new features - some to do with audio side of things.

Plans are also made for multi-platform support in future releases - iOS, Android etc but they don't know how long until they get implemented.

Also there is now a lot more support on the community as well as project starter templates, some video & text tutorials & finally some LUA Script examples.

-- * --

I haven't tried wintermute so can't say much about it.

-- * --

there is also another engine I know of but haven't tried called "SLUDGE - Adventure Game Engine" - which is also free open source. http://opensludge.sourceforge.net

-- * --

Safe :)

# Answer
> 1 votes
The answer to your question really relies on precisely defining "outdated" and then comparing that definition against the features of the development tool. For example, does the tool support your (presumably modern) target platform? Does the tool support the quality of audio you need? etc.

Although you should probably make such a list of requirements as part of evaluating the tool, another important aspect is playing examples made with this engine. Have you tried a bunch of games made with AGS? Do those games demonstrate what you have in mind? Trying out concrete examples will go a long way toward confirming that "yes, this is the right tool for my project." Just be wary of basing your judgement entirely on examples others have made rather than your own investigation of the tool.

# Answer
> 0 votes
It depends on what exactly you need. I don't think it is outdated, but I would think twice about who is my target group (friends? millions of people around the world?) and how easy the development should be. If you, for example, come to the conclusion you want a game for friends and most of them use mobile devices then it may be a good idea to create a game for these devices - using, for example, GameStylus system - simple on-line editor, Android adventure engine, free... imho very easy to use and quite modern (including HD and multilanguage support, of course).

---
Tags: adventure-game-studio
---


# Question
Title: Very simple open source games in various languages?
Are there any very simple open source games available just to demonstrate the basics of the programming techniques? Preferably something which fits in to a couple hundred lines of actual code. Specifically, I'm looking for an open source game written in Objective-C and Cocoa.

I would also appreciate one written in C.

All the projects that I find online are relatively complicated.

# Answer
> 3 votes
If you want 200 lines, then the only type of game I can think of would be a good old-fashioned text adventure. :) Don't underestimate the challenges of that.

Here's a text adventure in Objective-C: http://www.spintz.com/electron/electron.html

# Answer
> 2 votes
You can find a few open source games written in objective-c on github. Although most are larger than a few hundred lines.

If you're looking for "tiny" examples and you like Roguelikes, you should check out the listings for the 1kb roguelikes contest. There are a couple C examples that are rather clever (though they probably aren't good learning examples, just fun to read.)

# Answer
> 1 votes
If your interested in FPS you can look at Cube Engine.

Also the Quake 3 Engine is available for free. You can find it on the id Software website. Bottom of the right side bar.

# Answer
> 1 votes
I am, very slowly, teaching myself programming (only need to grasp basic game logic) with the free book "Invent Your Own Computer Games with Python".

It's written with the idea that all an aspiring game programmer wants to do is get to the point of writing games, so that is what it lets you do, from the very beginning. In the end you will be making games that are pretty much what you describe here.

# Answer
> 0 votes
I've got the source for a simple one we're using for a code war competition at Windward Wrocks. It's in C# but that's close to Objective C.

# Answer
> 0 votes
An Allegro Game in 20 lines of code.

* It can be considered "free to use" since it is snippets on public forum
* C language
* some "dirty techniques" how to squeeze code in C
* some techniques how to make game simply
* at most 20 lines (there are few exceptions and there is a problem that C is maybe too compressible, because there is almost no restriction on newlines or whitespaces; LOC is usually a bad metric)
* Not sure if the "basics of the programming techniques" falls here, but there are certainly
    1. arrays
    2. function composition
    3. C boolean properties
    4. C comma properties
    5. C macro-processor properties
    6. C ternary operator
    7. boolean logic with multiplication and addition
    8. ...
* You would need some math background to understand some of them.
* Snippets have \< and \> instead of \[ and \] .

There is also Pac-Man for example.

It is something I would reccomend You if You are more advanced programmer, because some of these techniques are quite non-readable.Nevertheless, it is a nice set of techniques. Proper way would not be to make such "abominations" but to properly design, document, test (...) Your program and such code would be the result of many compression techniques applied on very good design. Please, this is not how You should program but a demonstration how much a game can be compressed.

# Answer
> 0 votes
Maybe it is a good idea not only look at open source games but to some freely available game systems (editors etc.) where you can find some inspiration for your data structures and what is behind it all. I mean for example GameStylus adventure game editor and engine, where - in the editor - you can clearly see what data structures are in the back of the game and how they are used.

---
Tags: open-source, objective-c, cocoa
---


# Question
Title: How should I organize my Unity scene graph?
In programming, we have coding conventions — self-enforced rules to help maintain order. Does such a convention or consensus exist on how to lay out scenes in Unity?

I've seen two styles of organisation:

* By proximity: Like, *building X → floor Y → room Z → healing potion Q*
* By type: A very flat scene graph with nodes like "Walls", "Doors", and "Healing potions".

What other options exist? Is there an overall best style? How do I choose the right one for my needs (e.g. indoor vs outdoor scenes)?

# Answer
It's a little confusing as Unity conflates the organization of scene items with its transform hierarchy. There's no way to bucket or organization items without parenting them to another object.

The best bet you will have is to make empty "folder" objects that have no components and no state but simply serve to be a named collection of objects. These folder objects should have only the default transform (positioned at the origin with no rotation and a uniform scale factor of 1) as otherwise their contents will be moved or transformed unintentionally.

For instance, you might make an empty object called "Props" with a default transform and place all of your prop objects under that, and then another one called "Enemies", and so on.

The scene itself (building -\> floor -\> item on floor) should *not* be represented this way. If the building is a complex model then it might have its own internal hierarchy of physics bodies, sure. The static level geometry (buildings and their static surfaces) are entirely separate from the gameplay items (potions). If you use objects for organization, separate along these lines: "Static Level" (containing buildings and the ground and whatnot) and "Collectables" (containing potions and other items).

Again, in that scenario, both "Static Level" and "Collectables" would be empty objects with default transforms that do absolutely nothing other than organize your content.

This is one of those little things that lead to folks like me saying that Unity is a great tool that gets the job done for prototyping and small/medium games but has piles of little quirks and oddities and shortcomings that make it fall just a little short of being a great tool for large-scale game development. A good game editor really should separate organization of in-game content and the transform hierarchy.
> 3 votes

# Answer
Scene graph organization is guided by the various consumers of the scene - see answer to "Scene Graph as Object Container?" Fundamentally, the scene graph associates objects such that they share some logic, physics, position, and/or render state.

So concerning organization-by-type, except for very simple games it would be a mistake to treat the scene graph as a kind of folder structure. At no time would one want to hide all the walls or rotate all the doors around a common point, so the containing object would serve no purpose other than to group its children and isn't taking advantage of the scene graph. It would be better to use a tag or code level data structure for behaviors like "open all doors" or "remove all potions."

Proximity takes advantage of the scene graph logic. For example, you could break your scene up into chunks so that you can turn distant chunks' visibility or logic off when they're too far away to have an affect on game play. So most larger games, on the surface, will appear to be organized by proximity.

However, a further confounding factor is that the scene graph is mutable. Consider a game where the player can drive a car. In terms of the scene graph, the player's avatar becomes a child of the car entity - we'd like to just move the car and not have write code to adjust the avatar ourselves. We would then feed the player's controller input to its immediate child, which would filter down un-handled actions to its children, and so on.

**Before**

```
PlayerController
    Avatar
Car

PlayerController.Left -> Avatar.WalkLeft

```

**After**

```
PlayerController
    Car
        Avatar

PlayerController.Left -> Car.TurnLeft -> Avatar.LookLeft

```
> 2 votes

---
Tags: unity, level-design, scene-graph, productivity
---


# Question
Title: Stroring components in arrays (entity component system)
I'm looking for ways to improve my ECS and I've seen many people suggest storing components in arrays. This seems great, considering fast access for a component using entity id and more importantly, fast iteration over elements of array (because systems do this all the time) and fewer cache misses than if I store components in Entity or use:

```
std::map<int,std::shared_ptr<Component>> components // where int is a component id

```

But I have some questions about this approach.

1) Do I have to create array for each component? Something like:

```
PositionComponent positionComponents[MAX_OBJECTS];
HealthComponent healthComponents[MAX_OBJECTS];
...

```

Or is there a better way to store different components contiguously in memory?

2) How can I get components using entity id if I do this?

I'd like to implement some function like this:

```
template <class T>
T* getComponent(int entityId) const {
    ... // ??
}

```

so I can then use it like this:

```
PositionComponent* pc = getComponent<PositionComponent>(entityId);

```

# Answer
> 11 votes
> This seems great, considering fast access for a component using entity id and more importantly, fast iteration over elements of array (because systems do this all the time) and fewer cache misses than if I store components in Entity or use:

Have you actually measured cache misses? Are they in any way being a problem for you? Would eliminating them for your component accesses be likely to have a measurable impact? Is it valuable for you to spend your optimization time worrying about them instead of focusing on parallelism or better GPU usage? Do you at least have measurements of your code before any such change so you can compare them to measurements from after the change?

Simply putting things in an array doesn't guarantee fewer cache misses, either. It's the first step of several to improving cache usage for components. It may be a false step for improving your overall performance, too.

> 1) Do I have to create array for each component? Something like:

```
PositionComponent positionComponents[MAX_OBJECTS];
HealthComponent healthComponents[MAX_OBJECTS];

```

A `std::vector` or the like would work just as well. Note that as the `vector` could reallocate its backing storage and invalidate existing existing iterators/pointers you'll have to use component indices rather than pointers.

You can also easily write a chunked storage means (like a `std::deque`, but not optimized for queues) that allows the structure to grow, keep fast iteration, and have stable pointers.

> 2) How can I get components using entity id if I do this?

```
template <class T>
T* getComponent(int entityId) const {
    ... // ??
}

```

You can store an additional `boost::flat_map` or `std::unordered_map` or a custom high-performance hash table that maps entity IDs to component indices for that component type.

You'll probably just want to map to an index or a temporary pointer (one you promise never to retain) as that allows the component holder to defragment its component collection. That both can potentially allow the holder to release blocks of memory and more importantly (for data-oriented needs) is essential to actually making iteration over components faster. It's likely going to be much faster to use your existing approach than it is to iterate over a huge and sparsely-populated array. Remember that with a sparse array (even if 99% occupied) you have to add an additional `if (isInUse)` check inside your loop over the components which is an additional read+branch instruction that can have a noticeably negative impact on your overall iteration speed.

See BitSquid's four articles on the topic. Those guys tend to focus on C-like code and eschew modern C++ approaches with identical performance but easier usage, but the underlying approaches they use are applicable in C, C++, C#, Rust, or similar languages.

# Answer
> 2 votes
> 1) Do I have to create array for each component?

Yes, but a vector would be more convenient, and equally performant.

> 2) How can I get components using entity id if I do this?

You should store the Entity ID on the components themselves. Keep your vector sorted by that ID, and then use vector::lower\_bound to retrieve the components. In my own testing, this lookup is actually faster than a map up to a certain point.

---
Tags: c++, entity-system
---


# Question
Title: The way of avoiding branching for textured and not-textured objects
I know that branching **is an expensive operation on GPU** (not as much as it used to be, but still).

The most common situation where I use branching is when I have both textured and non-textured models/objects rendered with single shader (switching between shaders is also quite expensive and it only differs in 1-2 small parts).

For example, here's some pixel shader for rendering 2D objects:

```
constbuffer constBufferPerObject{
    float4 textureCoordORColor; //hasTexture is true => it's texCoord(x,y), color otherwise
    bool hasTexture;
};

...

float4 PS(VS_OUTPUT input) : SV_TARGET{
    if(hasTexture){
        //input.TexCoord was calculated in VS (it's meaningless if hasTexture is false)
        return ObjTexture.Sample(ObjSamplerState, input.TexCoord);
    }else{
        return textureCoordORColor;
    }
}

```

What would be a smart way to re-write the `PS` **in order to avoid branching here**?

# Answer
> 4 votes
For best performance you should avoid changing uniforms as well as shaders by using vertex attributes.

Ideally pack all your 2D object textures into 1 single large texture (called an atlas) so you can render all your 2D objects in one call using a single vertex buffer.

In your large texture you also put a 4x4 white area and map the texture coordinates of all your color-only elements to the center of that white square.

Pixel shader:

```
float4 PS(VS_OUTPUT input) : SV_TARGET{
  return ObjTexture.Sample(ObjSamplerState, input.TexCoord) * input.Color;
}

```

If instead you were fetching at garbage texture coordinates randomly all over the place and ignoring it you'd be trashing the texture cache needlessly.

Fetching the white texture area lets the input.Color pass through, conversely using a white color lets the texture pass through.

Your vertex format needs UV coordinates (2 unsigned shorts should be enough precision), and 1 RGBA color (4 unsigned bytes) as well as the vertex coordinates (2 floats), for a total of 16 bytes per vertex, a good vertex size and alignment. If you need your 2D elements in 3D space then you'll need a larger vertex format.

With that you can draw all your 2D elements in one single draw call.

And on top of this by using pre-multiplied alpha you can even combine alpha blending and additive blending (glowing particles) in one single draw call.

```
Blend = SRC * ONE + DST * ONE_MINUS_SRC_ALPHA;

```

By using an alpha of 0 in SRC and a color value \> 0 you get an additive blending. To get regular blending the color has to be pre-multiplied with its alpha value so that when alpha is 0 then color in the texture and/or vertex is also 0.

---
Tags: shaders, hlsl
---


# Question
Title: How do I split a button graphic into a 9 patch?
I understand what a nine patch is but I don't understand how to create one with code. I've made an image with a 1-pixel black border, but how do I turn that into a nine patch?

How do I make a nine patch that is not a cube image?

This is what is happening when I run:

```
patch = new NinePatch(new Texture(Gdx.files.internal("nineEmpty.9.png")), 4, 4, 13, 28);

```

I want it cut like this:

# Answer
The documentation shows the correct usage of the NinePatch:

```
public NinePatch(TextureRegion region,
             int left,
             int right,
             int top,
             int bottom)

left - Pixels from left edge.
right - Pixels from right edge.
top - Pixels from top edge.
bottom - Pixels from bottom edge.

```

Additionally you can find a tutorial that covers the topic well here. I suggest you remeasure your graphic and adjust the inputs into the NinePath constructor accordingly. Make sure you don't have any white spaces that could throw off your calculations.
> 1 votes

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


title: Smooth Npc Movement

text:
# Question
Title: Smooth Npc Movement
I have an Npc in my rpg that moves around based on a Random() variable. My main goal is to have him walk in a random direction a small bit every 2 seconds. I only want him to move about 32 pixels every time he walks.

```
public void npcLogic()
    {
        rand = new Random();

        now = System.nanoTime();

        if((now - lastMove) >= moveSpeed)
        {
            if(rand.nextFloat() >= .4)
            {
                Game.npcX += 32;
                lastLook = 3;
            }
            else if(rand.nextFloat() >= .3)
            {
                Game.npcX -= 32;
                lastLook = 2;
            }
            else if(rand.nextFloat() >= .2)
            {
                Game.npcY += 32;
                lastLook = 1;
            }
            else if(rand.nextFloat() >= .1)
            {
                Game.npcY -= 32;
                lastLook = 0;
            }
            lastMove = now;
        }
    }

```

The problem is he jumps to his destination rather than smoothly walking there. I have tried setting a timer to move him slightly for a specific amount of time like

```
Long smNow = 0L;
Long smLast = 0L;
Long smSpd = 5000000L;

public void npcLogic()
    {
        rand = new Random();

        now = System.nanoTime();

        if((now - lastMove) >= moveSpeed)
        {
            if(rand.nextFloat() >= .4)
            {
                smNow = System.nanoTime();
                while((smNow - smLast) >= smSpd)
                {
                    Game.npcX += Player.SPEED;
                    lastLook = 3;
                }
                smLast += smNow;
            }
            lastMove = now;
        }
    }

```

but this Stops movement of the player character and he still jumps, and now way too far. So does anyone have any suggestion to make the Npc move smoothly while the player character can still move around?

# Answer
You need to set to NPC a new target once in a while (e.g. each 5sec) and move it towards the target each tick little by little. Then it will be smooth.

To avoid sharp turns upon setting a new target, you can mix target positions between old and new target for a second or two.

Additionally, you might want to Google for "Steering behavior"
> 3 votes

---
Tags: java, movement, rpg, npc
---


title: Need help creating points in an array

text:
# Question
Title: Need help creating points in an array
I'm creating a lightning geometry shader using hlsl that creates an array of points based on an arbitrary number of generations. The gist of what I want to accomplish is here: http://drilian.com/2009/02/25/lightning-bolts/

The problem is the fact that the pseudo-code uses a dynamic array which deletes the current generations line segment and then resizes to add new line segments. I can only use fixed sized arrays in hlsl.

My current code is as stands:

```
int generations = 4;
int pointsarraysize = pow(2, generations) + 1;
float3 points[pointsarraysize];
points[0] = startpoint;
points[pointsarraysize - 1] = endpoint;

for(int currentgeneration = 0; currentgeneration < genetations; ++currentgeneration)
{
    for(int i = 0; i < pointsarraysize; ++i)
    {
        if (i == pow(2, currentgeneration))
        {

        }
    }
}

```

So what i've got creates an array of the size of points I want to end up with and sets the start point and end point.

How do I fill the array so that each iteration over the array creates the points in the right place in the array? I can't simply iterate linearly and calculate points depending on the index position because calculating, for example, the first point in an array with 4 generations requires the start point point\[0\] and a generation 3 point, point\[2\].

Is this even the best way to fill the array or am I missing something that could simplify the problem? I want to be able to change the number of generations rather than hard coding a certain amount.

# Answer
The whole way I was going about it is wrong. I'll answer my own question in case anybody else comes here from google.

Instead of generating a whole tonne of points and appending them in one geometry shader to create lightning, the answer is to only generate each iteration of the lightning per geometry shader invocation to remove the need for having a dynamic array at all.

So, first you take a line into the geometry shader. Then you output only 2 or 3 line segments from the geometry shader (depending on if the lightning arcs or not, as per the second code section on http://drilian.com/2009/02/25/lightning-bolts/). Then use the stream output stage of the graphics pipeline to then invoke the geometry shader for the new line segments you just made.
> 1 votes

---
Tags: algorithm, hlsl, geometry-shader
---


# Question
Title: LibGdx sprite rotation vs Box2D physics rotation problem
LibGdx sprite rotation vs Box2D physics rotation problem

Tearing my hair out on this one. I am an experienced software developer, but very new to LibGdx and Box2D development.

I am writing a game where the game board is the size of the screen. The game board does not pan - it just fills the screen. For the descriptions below presume that the device is being held vertically, so that vertical is the longest length. Also, for the description below, presume that on a device with a 'normal' aspect ratio, circles will be rendered perfectly circular, but a device that is narrower than expected, the circles will be squashed so that they are taller than wide.

I have a number of circle shapes that are rendered to the screen.

Because different devices will have different width / height aspect ratios, I am happy for the circle shapes to be squashed on a device that is narrower on the horizontal than expected (I am trying to avoid maintaining identical aspect ratios and forcing black borders at the edges of the game board).

My problem is this: when Box2D debug renders the screen, showing the physics objects, the circle shapes maintain their width and height, even when rotated. To describe further, if a sphere is displayed with 0 degree rotation on a narrow device, it takes an oval shape that is taller than it is wide, as would be expected on a narrower than expected device. If you rotate the circle shape by 90 degrees, the Box2d debug renderer shows the rotation (there is a line that sticks out of the centre of the object at an angle that shows the angle of rotation) but the object maintains its taller than wide oval shape. This is correct, as a sphere on a horizontally narrower aspect-ratioed device will always be displayed taller than wide.

When I attempt to overlay a LibGDX sprite on top of the Box2D physics simulation (the sprite, in its unaltered form, is circular, and is then scaled to the devices aspect ratio), with a zero degree angle, it appears nicely mapped to the Box2D representation - taller than it is wide. However, when I rotate the LibGDX sprite by 90 degrees, it appears rotated the way a billboard image would be rotated, so it is now wider than it is tall (imagine drawing a taller-than-wide oval on a piece of paper and turning the piece of paper by 90 degrees).

It appears to me that Box2D applies rotation before it applies the camera scaling - so the circular object is rotated first (maintaining its circular shape under the hood), and then sqaushed to form an ellipse that is taller than wide on the screen. Whereas, the LibGDX engine applies the transforms in reverse. The object is squashed to taller-than-wide, then rotated, so it becomes wider-than-tall on the screen.

I have pasted the relevant code below:

```
//screen size in box2D metres
private static float screenHeight = 100.0f;
private static float screenWidth = 70.0f;

//set up the camera in the show() method
    cam = new OrthographicCamera(screenWidth, screenHeight);
    cam.position.set(screenWidth / 2, screenHeight / 2, 0);

//render method
batch.begin();
for (int i = 0; i < ballList.length; i++)
{
    ballList[i].render(batch);
}
batch.end();

//ball class render method
public void render(SpriteBatch batch)
{
    ballHappyImage.setOrigin(64.0f, 64.0f);
    ballHappyImage.setPosition(body.getPosition().x - 64.0f, body.getPosition().y - 64.0f);
    float scaleWidth = Gdx.graphics.getWidth() / 1400.0f; //hardcoded to make things fit correctly
    float scaleHeight = Gdx.graphics.getHeight() / 2000.0f; //hardcoded to make things fit correctly
    ballHappyImage.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
    ballHappyImage.setScale(scaleWidth, scaleHeight);
    ballHappyImage.draw(batch);
}

```

The images below show the Box2D debug rendered line drawings overlayed on the libgdx sprites.

# Answer
> 3 votes
The libgdx-utils library has a Box2DSprite class that takes care of all the difficulties in synchronizing the appearance with the physics body. It may be helpful to either use this library or see how they implemented the functionality you are looking for: bitbucket.org/dermetfan/libgdx-utils/wiki/Home

Example:

```
bodyDef.position.set(4f, 8);
bodyDef.angularVelocity = 5;

PolygonShape boxShape = new PolygonShape();
boxShape.setAsBox(2.5f, 3);

fixtureDef.shape = boxShape;
fixtureDef.density = 5;
fixtureDef.friction = .4f;
fixtureDef.restitution = .2f;

Body box = world.createBody(bodyDef);
box.createFixture(fixtureDef);
box.setUserData(new Box2DSprite(Assets.someImage));

ballShape.setPosition(new Vector2(-Box2DUtils.getWidth(boxShape), 0));;
fixtureDef.shape = ballShape;

box.createFixture(fixtureDef);

boxShape.dispose();

```

# Answer
> 2 votes
Try

```
sprite.setOriginCenter();

```

This should help

---
Tags: libgdx, sprites, box2d, rotation
---


# Question
Title: Is there an alternative to VBOs or deprecated functions to draw many small quads?
I was thinking about how to program a user interface in a 3D game. The problem is, immediate mode (`glBegin` and `glEnd`) is deprecated for a long time *but* I don't think vertex buffer objects (or arrays) are needed just for the (2D) quads I want to draw (and I don't think they are even efficient for plenty of small quads).

Are there any approaches on how to avoid vertex-buffer-objects/arrays *and* the deprecated functions?

# Answer
> 6 votes
Not really. Use vertex buffer objects. There can be perfectly efficient for large numbers of small triangles.

The thing is that you don't want to make one VBO per quad, but rather few VBOs into which you stuff multiple quads.

# Answer
> 1 votes
You can use instancing and a texture atlas to combine all the draw calls into a single one.

You only have a single 4 vertex VBO with the 4 corners `0,0 0,1 1,1 1,0` and an index buffer to draw them using `GL_TRIANGLES`.

Then in a separate VBO you have the position and size of the quad (in a single vec4) and the position and size of the texture to use in the atlas (again as a vec4).

```
in vec2 coords;

in vec4 location;//x and y is the relative offset and z and w is the scaling factor
in vec4 textureLoc;

out vec2 texCoord;//0-1 as you would without the atlas

main(){
   gl_Position = coords.xy*location.zw + location.xy;
   texCoord = coords.xy*textureLoc.zw + textureLoc.xy;
}

```

Then during the rendering you fill the second VBO with `position, size, texturePosition, textureSize`, set the attribute pointer as if they where one for each vertex and set the attribute Divisor to 1; draw with

```
void glDrawElementsInstanced(GL_TRIANGLES, 6, GL_Int, 0, numberQuads);

```

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


# Question
Title: 2D bouncing ball simulation - angular velocity
How does angular velocity of a ball affects it's speed after a bounce? I'm trying to simulate 2D bouncing ball physics. I've found a nice solution how to calculate ball's velocity after a bounce:

```
mVelocity.x *= 1 + mi * (e - 1);
mVelocity.y *= -e;

```

where `mVelocity.x` is a component of ball's velocity parallel to the "surface" of a bounce, `mi` is coefficient of friction, `e`\<=1 representsthe energy loss during the impact.

It's looks quite realistic, however I'd like to calculate angular velocity as well - and I assume it's also affecting how the ball actually bounces. I tried to achieve it using matrix found on wolfram site - http://demonstrations.wolfram.com/BouncingASuperball/ (it's in the bottom of the page), but its implementation doesn't look realistic at all, ball is acting very wierdly. How can I calculate it?

# Answer
> 1 votes
Forumlas here - http://www.kellegous.com/j/2006/02/19/bouncing-ball/ \- seem to be working quite well, however if anyone knows an alternative version, please post it.

---
Tags: physics
---


title: Normal mapping for Android and iOS

text:
# Question
Title: Normal mapping for Android and iOS
I'm making a mobile game for Android and iOS on Unity. At the moment I am researching and designing the technical aspects of the game. Since it is not plausible to use highly detailed models for mobile platforms, should normal mapped models be used instead?

Thus I have couple of questions about normal mapping. Are normal mapped models much more costly to make, in other words, do they take a lot longer to create? And are they much more expensive to render? At least there are no additional draw calls, but of course the shader is more complex.

# Answer
The model itself is not more costly to made but an additional texture is required. Depending on the artist a new texture has to be drawn or the bumpiness is created from a high detail version of the model. The is no general answer.

Unity states

*Normal mapped. This is a bit more expensive than Diffuse: it adds one more texture (normal map), and a couple of shader instructions.*

Normal mapping is a viable option on mobile platform if you stick to the mobile shaders.
> 2 votes

---
Tags: unity, textures, models, normal-mapping
---


# Question
Title: Transmission implementation in a car game
I'm trying to create a simple car game with manual gear changes. However, I'm having a bit of trouble implementing the gear changes.

Here's my current code for the "car":

```
int gear = 1; // Current gear, initially the 1st
int gearCount = 5; // Total no. of gears

int speed = 0; // Speed (km/h), initially 0
int[] maxSpeedsPerGear = new int[]
{
    40,  // First gear max. speed at max. RPM
    70,  // Second gear max. speed at max. RPM
    100, // and so on
    130,
    170
}

int rpm = 0; // Current engine RPM
int maxRPM = 8500; // Max. RPM

public void update(float dt)
{
    if(rpm < maxRPM)
    {
        rpm += 65 / gear; // The higher the gear, the slower the RPM increases
    }

    speed = (int) ((float)rpm / (float)maxRPM) * (float)maxSpeedsPerGear[gear - 1]);

    if(isKeyPressed(Keys.SPACE))
    {
        if(gear < gearCount)
        {
            gear++; // Change the gear
            rpm -= 3600; // Drop the RPM by a fixed amount
            if(rpm < 1500) rpm = 1500; // Just a silly "lower limit" for RPM
        }
    }
}

```

However, this implementation doesn't really work. The first gear works fine, but the following gear changes cause the speed drop. By adding some debugging messages, I get these speed values when changing at the RPM limit:

```
Speed at gear 1 before change: 40
Speed after changing from gear 1 to gear 2: 41

Speed at gear 2 before change: 70
Speed after changing from gear 2 to gear 3: 59

Speed at gear 3 before change: 100
Speed after changing from gear 3 to gear 4: 76

Speed at gear 4 before change: 130
Speed after changing from gear 4 to gear 5: 100

```

As you can see, the speed after each change is slower before the change. How would you take into consideration the speed before the gear change so that the speed wouldn't drop when changing gears?

# Answer
Calculate the new RPM based on the new gear and current speed of the car.

```
speed = (int) ((float)rpm / (float)maxRPM) * (float)maxSpeedsPerGear[gear - 1]);

```

so: instead of:

```
rpm -= 3600; // Drop the RPM by a fixed amount

```

use:

```
rpm = max(maxRPM,(float)maxRPM * (float)speed / (float)maxSpeedsPerGear[gear - 1]);

```

The speed will now be the same before and after the gear change, and you can accellerate/decelerate from there.

edit: added `max(maxRPM, calc)` as you want to limit it. Like in a car, this should result in a pretty sudden loss of speed
> 17 votes

# Answer
this is because there is no inertia in your speed computation. you just compute it as an absolute consequence of engine rpm and gear. but when you compute the new rpm after gear shift up, you empirically lower it by fixed 3600 rpm steps.

This is your mistake. the rpm dropdown is not fixed between gears. you can fix it by making a second array storing the exact number of rpm drop between each gear.

Second way you can fix it, is by using physically based calculations. You are doing a simulation, so you can do a numerical integration. Using time, `dt`, and euler integration, or Verlet integration. This sounds complex with names and all but actually is not.

Basically it would mean that you create a lookup table for engine torque at given rpms. Then you would take into account some air resistance increasing with the square of the speed. Then the simulation would calculate the next speed by reversing newtons second law, `f=m a`.
To find `a=f/m`, then Euler integration: `speed=speed+a*dt`. the `m` is about 1200 (typical car weight). `f` is the force derived from engine torque, reduced into the gearbox, and then converted to force using lever formula by considering the wheel's radius. (a vector cross product usually, but can be simplified by the multiplication of torque with radius. because netwton/meters multiplied meters = newtons.)

this way, rpm of engine is calculated backwards, as a function of the linear car speed.
> 29 votes

# Answer
Gears are used as a reduction mechanism.

Using a simplified transmission with just two ratios in the gearbox, one input gear (the engine) and one output gear (one of the ratios of the gearbox) we have two different reduction ratios.

So for an input gear with x teeth and an output gear of x/2 teeth, the speed of the output gear is twice the speed of the input gear ( a two to one ratio)

```
rpm2 = rpm1 * gearRatio

```

where:

```
gearRatio = teeth1 / teeth2

```

So instead of limiting each gear by hardcoded speed, we can limit it by ratio. You can then calculate the speed for a specific (rpmEngine, gear) pair, and, when the gear is changed, calculate the engine speed given the known speed and a new pair.

To simplify, using just an engine connected to two gears:

```
rpmEngine = 5000

gearRatio[1] = 2 #low gear:  one rotation of the engine results in 2 rotations output
gearRatio[2] = 3 #high gear: one rotation of the engine results in 3 rotations output

vehicleSpeed = rpmEngine * gearRatio[selectedGear]

```

so:

```
selectedGear = 1
vehicleSpeed = rpmEngine * gearRatio[selectedGear] #5000 * 2 = 10000

```

when shifting to 2nd gear, 10000 is the speed, so plugging that in the same formula, we now have:

```
vehicleSpeed = 10000 #computed above
selectedGear = 2

```

thus our new rpm:

```
rpmEngine = vehicleSpeed / gearRatio[selectedGear] #10000 / 3 = 3333.3

```

That 10000 would then be further reduced by a differential (which can be abstracted as just another gear, look it up if needed, sorry, can post jut two links) and then by the wheel size to calculate ground speed in kilometers or miles per hour.

You would have to take into account the fact that shifting into a lower gear raises the engine rpm, so a simple approach is to check **maxRPM** and limit the rpm after the shift to your maximum rpm, thus reducing the vehicle speed.

So basically, each time a gear shift occurs, you compute the engineRPM from the vehicle speed, limit it by maxRPM, and then get back to "normal" where you update the rpm from the user input and compute speed based on that.

For a realistic simulation, you have to take into account at least engine torque (v.oddou's answer) and clutch slippage, which combined would have these effects: \- when shifting up, assuming the shift is fast enough that the engine rpm does not fall, the speed will be raised while the engine rpm is lowered until they are balanced out \- when shifting down, the vehicle speed will be lowered until the engine will be raised to the new rpm but this probably goes beyond the "simple" implementation.
> 5 votes

# Answer
Keep in mind that an engaged manual transmission is a two-way device. The engine can accelerate the vehicle, just as the vehicle (more specifically its momentum) can accelerate the engine.

This was a real problem in early manual transmissions. Downshifting would suddenly kick the engine into a higher rpm, throwing ignition cycles out of sync and possibly causing the engine to stall. This was offset by expert driving where the driver had to rev the engine to the correct speed before releasing the clutch to engage the transmission.

That was until the **synchromesh** was developed. It is a mechanism that prevents the transmission from engaging until the input and output speeds are in sync.

So, what I suggest is that you emulate the synchromesh and not engage the transmission until the engine rpm and the car speed match at their current levels.
> 4 votes

# Answer
The existing answer seems far too complex. For a game, RPM is just an indicator on the screen. The actual speed is the real variable. The gear ratio determines how you convert the engine speed to RPM's. Changing gears changes the ratio, but not the speed. Obviously, the RPM also changes as the inverse of the gear ratio.

Overrevving (downshifting past your 8500 RPM limit) is something that you'd implement separately, but it's a bad things in cars and you can let it be a bad thing in your game.
> 2 votes

# Answer
As others have mentioned, vehicle speed should be the real value and RPM should be derived from that. Upshifting should cause an engine's rotational speed to decrease because the ratio of RPM per km/h will "instantly" change but the vehicle speed won't.

I would suggest, however, that engine torque should increase with RPM up to a certain limit and fall beyond that. The rate at which a vehicle accelerates should be proportional to torque divided by the gear ratio, minus air drag which is proportional to the square of speed. If consecutive gears have a 1:41:1 ratio, then optimal shifting for acceleration will occur at the point where torque in the lower gear has fallen to about 70% of what it would be in the next higher gear.
> 2 votes

# Answer
Building on @v.oddou, using

```
max(maxRPM, calc)

```

would cause the RPMS to max out instantly when the gears are shifted, not allowing for any smooth transition from gear to gear. The proper way would be to solve for RPM's using the speed variable as an equation.

```
speed = (int) ((float)rpm / (float)maxRPM) * (float)maxSpeedsPerGear[gear - 1]);

```

Solve for rpm

```
rpm = (maxRPM * speed) / maxSpeedsPerGear[gear - 1] ;

```

since gear is 1 higher than is was before, RPM's will be lower.
> 2 votes

---
Tags: simulations, car
---


# Question
Title: How do I load textures with SFML for OpenGL?
I'm looking at NeHe's texture mapping tutorial. It looks overly complicated for just loading a texture.

Is there a way to load a texture in SFML and then use it in Open GL? I use SFML for my windowing.

# Answer
> 16 votes
Welcome to OpenGL, where the fast things come for free and the easy things are made hard.

If you thought that sample was long and complicated, "just for loading a texture", then you've seen nothing yet. Wait until you have to load DDS textures, process HDR textures, support cubemaps, render to a texture, etc.

Loading a texture in OpenGL consists of two components:

* Getting the data from your image format. You could load a texture from a file or generate it procedurally. It doesn't matter, as long as you end up with a nice array of color information.
* Putting the data on the videocard. The data needs to go from system RAM to video RAM.

The first part should be easy, because SFML comes with a standard image loader.

```
sf::Image img_data;
if (!img_data.LoadFromFile("images/avatar.png"))
{
    LOG_ERROR("Could not load '%s'.", "images/avatar.png");
    return false;
}

```

Next, we'll have to generate an OpenGL texture object.

```
GLuint texture_handle;
glGenTextures(1, &texture_handle);

```

There are a number of choices for binding a texture. There are the three main types: 1D, 2D and 3D and you have support for cubemaps (+X, -X, +Y, -Y, +Z, -Z). However, in 99% of the cases, you will want a 2D texture.

```
glBindTexture(GL_TEXTURE_2D, texture_handle);

```

Now we get to the interesting part. Let's upload our data to the video card.

```
glTexImage2D(
    GL_TEXTURE_2D, 0, GL_RGBA,
    img_data.GetWidth(), img_data.GetHeight(),
    0,
    GL_RGBA, GL_UNSIGNED_BYTE, img_data.GetPixelsPtr()
);

```

Finally, we can set a number of texture parameters. These answer questions like: what if we use a texture coordinate that is outside of the range (0.0, 1.0)? Do we wrap around (`GL_REPEAT`) or do we do nothing (`GL_CLAMP`)? They can also be used to explain to the videocard that we want to use linear interpolation on our textures.

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

And now you should be able to bind your texture using `glBindTexture` and use it to draw textured meshes.

# Answer
> 2 votes
SFML 2.0+ makes it even easier to load a texture;

```
sf::Texture texLid;
std::string image2="images/top.jpg";
if (!texLid.loadFromFile(image2))
{
    std::cout << "Could not load" << image2;
    char c;
    std::cin>>c;
    return false;
}

glEnable(GL_TEXTURE_2D);//tell OpenGL to use textures when drawing

sf::Texture::bind(&texLid);//select this texture for OpenGL rendering

```

---
Tags: opengl, c++, textures, sfml, loading
---


# Question
Title: Can I query the Game Center APIs from C++, without Objective-C?
I am writing a game that needs Game Center leaderboards. These however, are not very extensive leaderboards. I just need the ability to submit a score automatically when the player completes a level. Then, when a player visits a specific in game screen, it queries his/her position on the leaderboard and returns the value and the position. I don't need the UI, or any achievements. Just need those values.

Is this information possible to query using C++? I am using Cocos2d-x and would like to keep all of it C++ if possible.

# Answer
> 7 votes
> Is this information possible to query using C++?

Not practically, no. Apple's Game Center API is an Objective-C one. Technically speaking, you could make a bunch of bare calls to `objc_msgSend` if you were hell-bent on avoiding Objective-C code, but this is not practical. Instead, you can create a simple wrapper for the relevant Game Center calls by creating a C++ header file:

```
// GameCenterAccess.h
#pragma once

void submitPlayerScore (int score);
int getPlayerScore ();

```

and implement those functions in an Objective-C++ file (one that ends with the `.mm` extension; you can use a regular `.m` file if you aren't going to do anything C++-specific in the header, such as use namespaces):

```
// GameCenterAccess.mm
#include "GameCenterAccess.h"

void submitPlayerScore (int score) {
  GKScore * scoreObject = [[GKScore alloc] initWithLeaderboardIdentifier:/* your leaderboard id*/];
  scoreObject.value = score;
  [GKScore reportScores:@[scoreObject] withCompletionHandler:^(NSError * error) {
    ... // scores reported
  }];
}

int getPlayerScore () {
  GKLeaderboard * board = [[GKLeaderboard alloc] init];
  [board loadScoresWithCompletionHandler:^(NSArray * scores, NSError * error) {
    ... // do something with board.localPlayerScore
  }];

```

and so on (the above code is not tested, but should be a reasonable-enough approximation of reality; you'll want to do something smarter with the asynchronous nature of the queries).

You *can* use the leaderboard API in the way you describe: simply store a simple score per player, and not bother with all the related UI and achievements (the act of supporting Game Center will make your game appear in the Game Center app and show all the "required" Game Center stuff that the OS forces on you, but you don't need to do more than that). But you will need to use some portions of the API, and consequently to wrap them in some fashion in the above wrapper interface.

For example, to transmit a score you'll need the `GKScore` API and the `GKPlayer` API to represent the player obtaining the score, as well as the `GKLeaderboard` itself.

---
Tags: ios, leaderboards
---


# Question
Title: How can I detect continuous touches/pressed with Unity 4.6's UI elements?
I've recently switched to Unity 4.6. My previous workflow when creating continuous-input controls (the kind where you measure continuous touch input on a single button) was to create a `GUITexture` and then perform hit-testing on that texture as long as a finger was touching the screen.

With the new GUI there seems to be no way to measure this type of input, as `GUITextures` objects can no longer be created and the new UI types don't support hit testing.

I'm talking about a button that's supposed to act like a car accelerator where, for example, a simple `OnClick()` doesn't work because I need to measure if the button is being pressed continuously rather than it working as an on/off toggle. How can I implement this?

# Answer
It turns out you *can* implement this using the event system.

The `PointerDown` and `PointerUp` events can be used to track when the start and stop of the continuous touch. I'm currently using them, and they work fine. It's preferred to use events rather than checking on every frame, I guess.
> 2 votes

# Answer
Use the EventTrigger component for more events that aren't build-into the button element.
> 0 votes

---
Tags: unity
---


# Question
Title: How can I extract a list of Minecraft items and recipes?
I'm designing a robust system for resolving item dependencies in Minecraft and to do so, I need to maintain a database of items and recipes. Right now, this database has to be hand-crafted (no pun intended); I would like to know if it is possible to somehow query the Minecraft jars (or perhaps more realistically, `grep` through them) to extract this data automatically.

How can this be done? The project is currently in Python, but it can still be ported to Java without much fuss at this stage. (For the curious.)

# Answer
Minecraft's item and crafting recipes are defined in code, not in data. So you'll have to decompile the `.jar` files to do any useful analysis. To include mods in this analysis, you'd need to decompile them as well.

The main Minecraft server contains an `Item.java` file that lists all items along with their item IDs. The format of the calls that insert items into the registry is pretty simple and amenable to extraction via `grep` and some regular expressions. For example, on a not-necessarily-very-recent copy of the file, they look like:

```
REGISTRY.a(325, "bucket", item);
REGISTRY.a(326, "water_bucket", (new ItemBucket(Blocks.WATER)).c("bucketWater").c(item).f("bucket_water"));
REGISTRY.a(327, "lava_bucket", (new ItemBucket(Blocks.LAVA)).c("bucketLava").c(item).f("bucket_lava"));

```

Similarly, you can find recipes defined in `CraftingManager.java`:

```
this.registerShapelessRecipe(new ItemStack(Items.BOOK_AND_QUILL, 1), new Object[] { Items.BOOK, new ItemStack(Items.INK_SACK, 1, 0), Items.FEATHER});
this.registerShapedRecipe(new ItemStack(Blocks.FENCE, 2), new Object[] { "###", "###", Character.valueOf('#'), Items.STICK});

```

By exploiting these patterns, you can parse out a set of items and recipes for the main Minecraft application easily enough. However, because you're relying on source code parsing this technique is subject to being trivially broken in the likely event that the code structure changes (it may already be broken, I am looking at an old copy of the decompiled code to find these examples).

Worse still, mods may not use the same patterns and you are certainly likely to see different patterns across mods. You may be able to build a system that uses a unique, slightly-modified set of parse rules for each mod (and the main application), and this may be less work in the long run than manually adding *every* item and recipe to your database... but it's unfortunately still subject to being trivially broken by new version of the mods or the main executable.
> 1 votes

---
Tags: minecraft-modding, databases, automation
---


# Question
Title: Open source level editor for HTML5 platform game?
A natty GUI editor is very helpful to create level map. I want to use some open-source choices rather than build my own from scratch. I found Tiled Map Editor but it doesn't work for what I want.

Though I'm building HTML5 game, I don't have to use a HTML5 level editor as long as it can output well-formatted map files which my javascript can read.

**Edit:**

Sorry for the confusion. Tiled does not work for me because to make the player perform a 'tricky' jump, sometimes I want to set the distance between two platforms to, say, 7/3 or 8/3 tiles. But in Tiled I get only 2 or 3. If Tiled can do this, please teach me.

# Answer
> 6 votes
Tiled is very well suited for a platformer. But it really depends on how you design your tiles. Usually you'll have small tiles that are repeatable and form your landscape. Special corner- and edge-tiles can be used for a better look. Here's an example of such a sprite-sheet.

If you'd like to position sprites freely (eg. you're not working with tiles), I can recommend an editor like GLEED2D. The editor writes to XML files, but these can easily be changed to something else by using XSLT or some other way of processing the XML data.

# Answer
> 2 votes
I use Tiled too.

It seems strange that you're trying to do. You can create an Object Layer in TIled and set a position for your platform, but it is mostly used for movable objects. If your platform will be fixed it's weird not having an exact size in tiles. Maybe you're using the wrong technology to make your scenarios. Maybe using Bitmask will help you. See this tutorial, it has several ways to implement a platform map.

Anyway, some alternatives to TIled are TileStudio and Dame. But Dame are made for use with Flixel(as3), maybe it will be difficult to integrate with HTML5.

# Answer
> 1 votes
More relevant for HTML5 would be ImpactJS which is a framework but a level editor included. Granted the cost is $99 but you get a working platformer game, the level editor, support & the framework.

http://impactjs.com/

Definately worth a look and could be a great starting point for a game.

# Answer
> -1 votes
If you're looking at something free for now, try the MightyEditor http://mightyfingers.com/editor-features/ Cheers!

---
Tags: javascript, html5, level-design, map-editor
---


# Question
Title: When two RPC methods have the same name, which is called?
I have a situation where I would want two of the same components( in a hierarchy ), to be on a GameObject. If this component has an RPC method, it obviously cannot change name per instance of the component.

Which RPC method will be called? Unity says this:

"if two RPC functions in different scripts have the same name only one of them is called when RPC is invoked"

This says nothing about which will actually be called. Does Unity define a behavior for when this happens? Is there any alternatives that will avoid this?

# Answer
> 2 votes
Other than to specify that "only one" is called, Unity does not guarantee any behavior in this case. The most likely scenario, which you can determine through experimentation, is that either the *first* RPC that becomes registered/known to the system is called, or the *last* one is. However, this is an implementation detail.

Unity explicitly does not want you to care about which function is called in the scenario you're describing; there are several potential reasons, including:

* This could be because their implementation of the RPC mechanism trades efficiency of dispatch for the inability to deterministically resolve overloaded RPC names.
* Alternatively, this allows them the flexibility to change their implementation in the future without worrying about violating an API constraint.
* It's kind of a bad habit to have two RPC methods with exactly the same name in the scene, as it complicates things and makes it harder to reason about execution flow. By not providing a guarantee they are discouraging you from this behavior.

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


# Question
Title: How can I prevent text rendering from looking ugly when in motion?
I'm drawing a name above the player's head in a 2D top-down view game. The code to draw the string looks like this:

```
Vector2 textPos = new Vector2(
  (positionX * 2 * world.Map.TileWidth + (16 -(SmallFont.MeasureString(mName).X / 2))),
  (positionY * 2 * world.Map.TileWidth - 32));

spriteBatch.DrawString(SmallFont, mName, textPos, Color.White, 0, Vector2.Zero,
  1, SpriteEffects.None, 1);

```

The text is drawn to the position right above the player's head just fine, and it follows the player as he moves just fine as well. But the problem is that when the player moves, the text kind of gets thicker and ugly. I tried screen capping it but the screenshot doesn't capture the problem (because it's just taking a single frame, I presume).

How can I fix this?

# Answer
> 1 votes
XNA is based on D3D9, which has the dreaded "half-pixel offset problem." Pixels are dots, not squares, even though we like to think of them as the latter. In D3D9 you can visualize pixel coordinates as referring to the center of the cell they would illuminate; however we often consider origin of our coordinate systems to be at the "upper left" (or a similar corner) and thus there is a delta between the coordinate frame's origin at the pixel coordinate.

The D3D documentation has a decent write-up on the topic:

> The preceding diagram correctly shows each physical pixel as a point in the center of each cell. The screen space coordinate (0, 0) is located directly at the top-left pixel, and therefore at the center of the top-left cell. The top-left corner of the display is therefore at (-0.5, -0.5) because it is 0.5 cells to the left and 0.5 cells up from the top-left pixel. Direct3D will render a quad with corners at (0, 0) and (4, 4), as shown in the following illustration.

The above shows the mathematical frame of the quad, but D3D can't fill only a portion of a pixel, it must approximate. When you have textures quads rendered thusly (as you do when drawing text), the approximations D3D does to filter the results looks unpleasant. In the MSDN link, they provide an example where the above 4x4 quad has a unique set of pixel colors but still ends up looking mushy:

This could be what it happening to your text. Note that if true, it would be possible to eventually capture a screenshot of your text in it's blurry form, although you may have a hard time getting that to happen normally depending on the resolution at which your players end up moving in the world; you might have to set up a contrived example rendered at fixed coordinates to do so.

The solution is, fortunately, rather simple: subtract 0.5 units from the components of your vertex positions in transformed screen space.

Another good write-up of the issue can be found here.

---

Now, you also mentioned that you had difficulty capturing a screenshot of the blur. While I noted this could be due to how your characters move in the world, if you really can't reproduce the blur even with a fixed, contrived example then it's quite possible there's actually *nothing wrong* at all. You could simply be seeing motion blur, or other similar visual artifacts related to your eyes and persistence of vision.

However, I'm inclined to believe the issue is in the placement of the quad vertices in screen space and/or your texture filtering options (as has been previously noted in the comments).

---
Tags: xna
---


# Question
Title: Rendering a fullscreen quad is leaving a one pixel line on the left and top
I am rendering a fullscreen quad using XNA. I am having an issue where the top pixel line and left pixel line are not rendered. It should be black in the picture. Can anyone tell me why this might be happening?

The effect's intent is to fade the screen out or in by adjusting the alpha of the pixel.

`HLSL`

```
float3 c;
float a;

float4 ShadeVertex(float3 pos : POSITION0) : POSITION0
{
    return float4(pos, 1);
}

float4 ShadePixel(float2 p : VPOS) : COLOR0
{
    return float4(c, a);
}

technique Simple
{
    pass FirstPass
    {
        VertexShader = compile vs_3_0 ShadeVertex();
        PixelShader = compile ps_3_0 ShadePixel();
    }
}

```

`QuadRenderer.cs`

```
internal sealed class QuadRenderer : GameComponent
{

    #region fields

    private VertexPositionTexture[] triangles;
    private short[] indexData = new short[] { 0, 1, 2, 2, 3, 0 };
    private GraphicsDevice gfx;

    #endregion

    #region constructors

    public QuadRenderer(IGameEngine engine)
        : base(engine)
    {
        this.gfx = engine.Device.Graphics;

        // texture coordinates semantic not used or needed
        this.triangles = new VertexPositionTexture[]
                     {
                       new VertexPositionTexture(new Vector3(1, -1, 0),
                                                 Vector2.Zero),
                       new VertexPositionTexture(new Vector3(-1, -1, 0),
                                                 Vector2.Zero),
                       new VertexPositionTexture(new Vector3(-1, 1, 0),
                                                 Vector2.Zero),
                       new VertexPositionTexture(new Vector3(1, 1, 0),
                                                 Vector2.Zero)
                     };
    }

    #endregion

    #region methods

    public void Render(Effect effect)
    {
        foreach (EffectPass p in effect.CurrentTechnique.Passes)
            p.Apply();

        this.Render();
    }

    private void Render()
    {
        this.gfx.DrawUserIndexedPrimitives(PrimitiveType.TriangleList,
                                           this.triangles, 0, 4,
                                           this.indexData, 0, 2);
    }

    #endregion

}

```

# Answer
Sorry for the late reply, but saw an answer (by GameDevSE's own Josh Petrie) to another question here that reminded me of this one, and it seemed like it could also apply here. Don't know if its truly relevant, but it could be worth a look.

It basically discusses the half-pixel offset problem, in which a pixel can end up being misaligned by 0.5 units due to the differences in placement of the pixel occupying the center of its cell, and the placement of co-ordinates in the standard co-ordinate system. This can result in the actual pixel being offset from the specified point by 0.5 units in the X and Y direction.

In regards to your FSQ, I am also using a FSQ, and I have not noticed this issue with my engine. However, your FSQ does differ from mine slightly, so I'm not too sure if that might also be a problem as well. My FSQ is basically the one described in this guide (pages 5-6), so it also might be worth trying out as well to see if it fixes your problem.

One thing I did notice was your vertices assembly, and how each corner has a TextureCoord of `Vector2.Zero`. Mine looks something like this:

```
VertexPositionTexture[] vertices =
{
    new VertexPositionTexture(new Vector3(1, -1, 0), Vector2.One),
    new VertexPositionTexture(new Vector3(-1, -1, 0), Vector2.UnitY),
    new VertexPositionTexture(new Vector3(-1, 1, 0), Vector2.Zero),
    new VertexPositionTexture(new Vector3(1, 1, 0), Vector2.UnitX)
};

```

Another minor part to consider (Especially if your effect has multiple passes) is your Render function. IMO, it should look like this:

```
public void Render(Effect effect)
{
    foreach (EffectPass p in effect.CurrentTechnique.Passes)
    {
        p.Apply();
        this.Render();
    }
}

```

This will ensure that the FSQ is drawn once per pass, as you code will currently only apply the last pass in your effects technique. Its a minor thing, but if you have PPC's (Post Processing Chains) built into the shader file (pass 1 draws the scene, pass 2 applies a Post Processing Effect/Filter) then you can get some odd stuff happening.

Hopefully some of this helps. If I come up with or find anything else, I'll include it here.
> 2 votes

---
Tags: xna, graphic-effects
---


# Question
Title: How can I support the clamping of quaternion-based rotations?
Currently I have an orbiting camera that fixates on a single point. In the node-based structure, `_cameraNode` is a child of `_cameraTargetNode`. I am able to orbit around the target node via the following code snippet:

```
Urho3D::Quaternion rotY = Urho3D::Quaternion(1.f, Urho3D::Vector3(dy, 0.f, 0.f));
Urho3D::Quaternion rotX = Urho3D::Quaternion(1.f, Urho3D::Vector3(0.f, dx, 0.f));

Urho3D::Vector3 curPos = _cameraNode->GetTransform().Inverse().Translation();

_cameraNode->RotateAround(curPos, rotY, Urho3D::TS_LOCAL);
_cameraNode->RotateAround(Urho3D::Vector3::ZERO, rotX, Urho3D::TS_PARENT);

cameraNode->LookAt(Urho3D::Vector3::ZERO, Urho3D::Vector3::UP, Urho3D::TS_PARENT);

```

Now what I want to do is clamp this movement. I want to be able to orbit within a set area between the two following values:

```
const Urho3D::Vector3 rotClampMin = Urho3D::Vector3(0.f, -45.f, 0.f);
const Urho3D::Vector3 rotClampMax = Urho3D::Vector3(90.f, 45.f, 0.f);

```

`RotateAround` sets both the angle and position of `_cameraNode`, so I must pre-compute the values with the clamping in mind. I would like to avoid working with Euler angles as much as possible. How can I clamp my rotation prior to calling `_cameraNode->RotateAround`?

# Answer
I was able to do this by applying the correction after the initial transformation, though I would prefer an answer that applies the correction prior to the initial transformation so as to avoid transforming the camera twice.

After the:

```
_cameraNode->RotateAround(curPos, rotY, Urho3D::TS_LOCAL);
_cameraNode->RotateAround(Urho3D::Vector3::ZERO, rotX, Urho3D::TS_PARENT);

```

I added the following logic:

```
Urho3D::Vector3 curRotation = _cameraNode->GetRotation().EulerAngles();
Urho3D::Vector3 correction = Urho3D::Vector3::ZERO;

if (curRotation.x_ < rotClampMin.x_)
    correction.x_ = rotClampMin.x_ - curRotation.x_;
else if (curRotation.x_ > rotClampMax.x_)
    correction.x_ = rotClampMax.x_ - curRotation.x_;

if (curRotation.y_ < rotClampMin.y_)
    correction.y_ = rotClampMin.y_ - curRotation.y_;
else if (curRotation.y_ > rotClampMax.y_)
    correction.y_ = rotClampMax.y_ - curRotation.y_;

curPos = _cameraNode->GetTransform().Inverse().Translation();

rotX = Urho3D::Quaternion(correction.x_, Urho3D::Vector3(1.f, 0.f, 0.f));
rotY = Urho3D::Quaternion(correction.y_, Urho3D::Vector3(0.f, 1.f, 0.f));

_cameraNode->RotateAround(curPos, rotX, Urho3D::TS_LOCAL);
_cameraNode->RotateAround(Urho3D::Vector3::ZERO, rotY, Urho3D::TS_PARENT);

```

This works perfectly.
> 1 votes

---
Tags: quaternion, urho3d
---


# Question
Title: Physics simulation methods for large delta times?
What physics simulation methods are most suitable for really big delta time (hours to weeks)?

In addition, would I face any problems combining different methods for big and small delta times?

# Answer
> 5 votes
You'll likely be using constant acceleration for these large time spans (which could be zero acceleration). The derivative of constant acceleration with respect to time is 0. That means it doesn't change with respect to time, so it doesn't matter how large your delta time is.

This little integration with respect to time provides the equations you need.

```
a = a
v = at + v0
s = .5at^2 + v0*t + s0

```

Where: a=acceleration, v=velocity, v0=initial velocity, s=position, s0=initial position, t=time

Using this strategy you can use times spans from milliseconds to weeks if you wanted to. Combining them would be taken care of in the `v0` and `s0` parameters of the equation.

To handle collisions you'll have to implement strategies similar to those used for high speed small objects. First calculating the new position using the equation above, then sweeping between the old and new position for all objects. Since any one of those objects could have intersected each other (minutes or days before), this can get very complex. It's likely that since you have such large delta times, hopefully you'll have plenty of time to process these potential collisions.

# Answer
> 2 votes
Lets take an example with gravity.

In the below function, assume we have class member variables for position and velocity. We need to update them due to the force of gravity every dt seconds.

```
void update( float dt )
{
   acceleration = G * m / r^2;
   velocity = velocity + acceleration * dt;
   position = position + velocity * dt;
}

```

As `dt` gets smaller and smaller, our simulation gets more and more accurate (although if `dt` gets too small then we can encounter precision errors when adding tiny numbers to large numbers).

Basically, you have to decide the maximum `dt` your simulation can handle to get good enough results. And if the `dt` that comes in is too large, then simply break the simulation down into smaller steps, where each step is the maximum `dt` that you allow.

```
void update( float dt )
{
   acceleration = G * m / r^2;
   velocity = velocity + acceleration * dt;
   position = position + velocity * dt;
}

// this is the function we call. The above function is a helper to this function.
void updateLargeDt( float dt )
{
    const float timeStep = 0.1;
    while( dt > timeStep   )
    {
        update( timeStep  );
        dt -= timeStep ;
    }

    update( dt );  // update with whatever dt is left over from above
}

```

So with this strategy, you can just adjust `timeStep` to whatever fidelity you need ( make it a second, minute, hour, or whatever is needed to get an accurate representation of the physics.

# Answer
> 1 votes
Most games tend to use the simple Euler method of forward integration (that is, integrate the velocity into the position over time, and integrate the acceleration into velocity). Unfortunately,the Euler method is only suitable for very small timescales and short runs.

There are more complex methods which are more accurate over very long time scales. The most popular and easiest to implement is perhaps Runge-Kutte-4. RK4 determines the position in the future by sampling four positions and velocities in the past and interpolating. It tends to be much more accurate than the Euler method over longer time-scales, but is more computationally expensive.

For instance, if you want to compute the physics of a real orbiting planet updating every few days of real-time, the Euler method will cause the planet to shoot off into space after only a few orbits due to numerical errors. RK4 will generally keep the planet orbiting in roughly the same shape many thousands of times before accumulating too much error.

However, implementing collisions into RK4 can be very challenging...

---
Tags: physics
---


# Question
Title: In HLSL, what is the difference between "static const" and "#define" for constants?
So far I've been declaring all my constant variables as `static const` in my HLSL code, yet virtually every single shader example I've come across uses `#define` instead.

I know the reasons I would I use static const in C++ over the preprocessor and I just carried it into HLSL as well. However, I'm curious if there are any side effects or pros/cons to this, besides the standard C++ "static const versus #define" arguments.

# Answer
It basically doesn't matter.

`#define` uses token-pasting to insert the specified value into the shader code whereever it occurs; the shader itself will see the token as if you simply hard-coded it at every occurrence instead.

A `static const` variable in, in actuality, a variable. Specifically, it is a variable that is initialized once, whose value persists between function calls, and which cannot be changed. Being a variable, can have the same things that all other variables can have: additional storage and type specifiers (`precise`), more complex types (such as `float4`), semantics and register assignments (see here for all the things). However, specifically for `static const` variables, most of those extras aren't allowed or don't apply (particularly since a global static *is not visible to the application code*).

The `static const` version may allow some compiler optimizations (minor ones), especially if the type of the variable is more complex (such as a `float4` or matrix type), but that seems unlikely to matter much.

In the end, choose the one you prefer stylistically.
> 6 votes

---
Tags: directx, hlsl
---