title: C++ entity component system framework

text:
# Question
Title: C++ entity component system framework
I have found several entity system frameworks for other languages besides C++, like Ash and Rush for ActionScript and Artemis for Java and C#.

My question is whether there exists a framework like one of the ones mentioned above for C++?

# Answer
I looked into the C++ port of Artemis. I was wrong about it being out of date, it's actually as recent as January of this year. It looks like the author is off to a good start. I would recommend picking up from what he's already done. It would be a great learning experience as Mike C said. If you take a look at the source for Artemis, you'll find that it's actually pretty small, and pretty simple.

Just remember to give back to the community when you're done! I'm sure Arni Arent and Tiago Costa (creators of Artemis) would put up a link to your port on their website too. Good luck!
> 3 votes

# Answer
More recently, looks like some other work has been done on Artemis ports that employ more C++ '11 features: here (github), which is a faux-fork of this (bitbucket).
> 3 votes

---
Tags: c++, software-engineering, component-based
---


title: Calculate combat result between 2 units

text:
# Question
Title: Calculate combat result between 2 units
I need to know the best way to calculate an outcome between 2 types of units. Each unit has 3 factors: Health, AttackPower, Defense

There is also a last factor of anti-troop which says that one trooper is better against a certain type. So this factor must be taken accounted for.

Can someone help me with this ?

Kind regards

Example

Unit1(attacker):

```
 Amount: 40
 Health/Unit: 10
 AP/Unit: 5
 Defense/Unit: 2

```

Unit2(defender):

```
Amount: 20
Health/Unit: 10
AP/Unit: 5
Defense/Unit: 2

```

How can I get a right outcome of who wins and with how many units left.

# Answer
> 4 votes
Based on the factors provided, a simple way to handle this would be:

```
EnemyHealth -= (PlayerAttackPower * Boost) - EnemyDefense

```

Where Boost would be the percentage of attack power boost you would get based on the unit you are attacking.

---

**Edit**

In the case of multiple units, I would do something like this:

```
// keep attacking until someone is wiped out
while (Players.Count > 0 || Enemies.Count > 0)
{
    //Loop through all player units
    for (int i = 0; i < Players.Count; i++)
    {
        //Loop through all enemy units
        for (int j = 0; j < Enemies.Count; j++)
        {
            //Get ratio of Player units vs Enemy units
            double PlayerRatio = Players.Count / Enemies.Count;
            double EnemyRatio = Enemies.Count / Players.Count;

            //Player attacks enemy
            Enemies[j].Health -= (Players[i].Attack * PlayerRatio * Boost) - Enemies[j].Defense;

            //Enemy is dead, remove him
            if (Enemies[j].Health <= 0)
            {
                Enemies.RemoveAt(j);
                j--;
            }
            else    //enemy still alive, attack back at player
            {
                 Players[i].Health -= (Enemies[j].Attack * EnemyRatio * Boost) - Players[i].Defense;
                 if (Players[i].Health <= 0)
                 {
                      Players.RemoveAt(i);
                      i--;
                 }
            }
        }
    }
}

```

# Answer
> 2 votes
I'm just throwing up a ball here:

Say you have two players. They have the stats HP/AP/Def.

Player 1: 100 / 15 / 10

Player 2: 100 / 22 / 7

Player 1 is a trooper, player 2 is an anti-trooper.

You could be doing a 'hit' each attack. Say player 1 goes first, and hits player 2 with 15 AP. Player 2 has 7 Def, so 15-7 = 6 damage inflicted. But, Player 2 is an anti-trooper, so he gets a x-2 bonus. Player 2 receives 6/2=3 damage, HP left: 97.

You can switch around with the values a bit, or the bonusses gained from being a trooper/anti-trooper. Another thing commonly done is to use the defense not as flatout damage reduction, but as a percentage reduction of the damage gain.

# Answer
> 1 votes
As Joetjah writed, Player 1 will cause 3 damage per hit (pl\_1\_dph), and Player 2 will cause (22 - 10) = 12 damage per hit (pl\_2\_dph).

So, 1 unit of Player 1 requires 100 / 3 ~= 33 hits to kill 1 unit of Player 2 (pl\_2\_hp / pl\_1\_dph).

100 units of Player 1 will kill 200 units of Player 2 within

(pl\_2\_hp * pl\_2\_units) / (pl\_1\_dph * pl\_1\_units) = (100 * 200) / (3 * 100) = 20000 / 300 ~= 66 hits

200 units of Player 2 will kill 100 units of Player 1 within

(pl\_1\_hp * pl\_1\_units) / (pl\_2\_dph * pl\_2\_units) = (100 * 100) / (12 * 200) = 10000 / 2400 ~= 4 hits

As you see, troops of Player 2 will kill all forces of Player 1 within 4 hits. Within that time, Player 1 also attacked 4 times, and will cause 4 * pl\_1\_units * pl\_1\_dph = 4 * 100 * 3 = 1200 damage total, which means, that 1200 / pl\_2\_hp = 1200 / 100 = 12 units of Player 2 will be killed.

Summary: with 100 units (dph = 3) of Player 1 and 200 units (dph = 12) of Player 2, Player 2 will win within 4 steps (hits) and loose only 12 his units.

Algo:

1) compute damage per hit for player 1 and 2 (dont forget "anti-" bonus)

2) compute minimum hits, required for each player to completely kill enemy army

3) compare required hits to choose the winner (as required\_hits)

4) compute damage, caused by looser to winner within required\_hits hits to decide, how many forces will loose the winner (all units of looser's army was killed)

---
Tags: combat, format
---


# Question
Title: Input handling in component based design
I know this question has been asked several times, but I'm still not sure how to implement input handling in a component based engine.

The component based design I used was based on T=Machine's blog series and on Artemis in which Entities are just ids.

There are three main ideas I have in implementing input handling:

1. The input component will hold events it's interested. The input system will translate key and mouse events to game events and loop through the entities with the input component and if they are interested in the event an appropriate action will be taken by the input system. This action would be hard coded to the input system.
2. No input component. You would register entities with specific events to the input system. The input system would then send messages (with the entity id and event type) to other systems so that these can take the appropriate action. Or as in the first case, the actions would be hard-coded to the input system.
3. Similar to the first method, but instead of hard coding the action to the input system, the component would contain a map of events to functions (i.e. `std::map<std::function>`) which would be called by the input system. This has the added effect of being able to couple the same event to different actions.

Would you recommend any of the above methods or do you have any suggestions that would help me implement a flexible input handling system? Also, I'm not yet familiar with multi-threading but any suggestions that would make the implementation thread-friendly are also welcome.

Note: One added requirement I'd like the implementation to fulfill is that I'd be able to pass the same input to many entities, like for example moving a camera entity and the player at the same time.

# Answer
I think that, just like my answer regarding *materials* in a component system, you're running in to a problem where you're trying to shove everything into a "component." You don't need to do this and in doing so you're probably creating a really cumbersome interface by trying to fit a bunch of square pegs into round holes.

It sounds like you already have a system that handles the acquisition of input from the player. I'd opt for an approach that then translates that input into actions ("move forward," or "move backwards") or events and dispatches those to interested parties. In the past, I've disallowed components from registering *themselves* for these events, preferring an approach where the higher-level system explicitly selected the "controlled entity." But it could work that other way if you prefer, especially if you're going to re-use the same messages for taking actions that were not stimulated directly by input.

I wouldn't necessarily suggest implementing camera-following behavior by having both the camera entity and the player entity respond to the "move forward" (et cetera) message, though. This creates an extremely rigid connection between the two objects that will likely not feel good to the player, and it also makes it a bit trickier to handle things like having the camera orbit the player when the player rotates left or right: you have an entity responding to "rotate left" by assuming it is slaved to the player, but that means it can't correctly respond if it were ever unslaved... unless you introduce that concept as some state you can check. And if you're going to do that, you may as well implement a proper system for slaving two physical objects together, complete with appropriate elasticity tweakables and so on.

Regarding multi-threading, I don't really see a need to employ it here as it would likely cause more complication than it's worth, and you're dealing with an inherently serial problem so you'd just need to involve a lot of thread synchronization primitives.
> 8 votes

# Answer
My experience might be biased but in multi platform projects the input devices are not directly exposed to the entity system.

The input devices are handled by a lower level system which receives the events from the keys, buttons, axis, mouse, touch surfaces, accelerometers...

These events are then sent through a layer of context dependent intention generators.

Each generator register for sate changes from components, entities and systems that are relevant to its functions.

These generators then send messages/intentions for routing to the intention system where entities have a component or directly to the right components.

This way you can simply rely on "always" having the same input i.e. JUMP\_INTENT(1), JUMP\_INTENT(0), AIM\_INTENT(1)...

And "all" the dirty platform dependent input work remains outside of your entity system.

---

Concerning the camera if you want to move it around the player it can register its own intent component and listen to intents you will send.

Otherwise when if follows the player it should never listen to inputs destined to the player. It should listen to the state changes emitted by the player (ENTITY\_MOVED(transform))... and move accordingly. If you use a physics system you can even attach the camera to the player using one of the various joints.
> 4 votes

# Answer
What benefit does an InputComponent bring? Surely it is the prerogative of the input command to decide what entities it is performing an action on. The classic example is that of making the player jump. Instead of having an InputComponent on every entity listening for "Jump" events, why not have the jump command lookup the entity marked "player" and perform the necessary logic itself?

```
Action jump = () =>
{
    entities["player"].Transform.Velocity.Y += 5;
};

```

Another example, from the OP:

```
Action moveRight = () =>
{
    foreach (var entity in entities.Tagged("player", "camera"))
        entity.Transform.Position.X += 5;
};

```
> 2 votes

---
Tags: component-based, entity-system, input
---


title: Minecraft like blocky-clouds

text:
# Question
Title: Minecraft like blocky-clouds
We are working on a minecraft-like block-based engine/lib. Lately I've started working a blocky-clouds as in minecraft;

So it appers that in minecraft, clouds are not procedural. I'm still looking if it is viable to procedurally generate blocky-clouds.

I tried something like but it doesn't quite fit for clouds.

```
float octave1 = SimplexNoise.noise(x * 0.004f, 1000, z * 0.004f) * 0.5f;
float octave2 = SimplexNoise.noise(x * 0.003f, 1000, z * 0.003f) * 0.25f;
float octave3 = SimplexNoise.noise(x * 0.02f, 100, z * 0.02f) * 0.15f;
this.Clouds[x, z] = (octave1 + octave2 + octave3 > 0.6);

```

Any ideas or suggestions?

# Answer
> 3 votes
Yes, it's viable. As with any artistic programming, it's something you'll have to tweak until you get the results you're after.

You can just generate 2D noise and have a static set of clouds like Minecraft, or you can use 3D noise and generate animated changing clouds.

# Answer
> 0 votes
I dunno about you, but using the heightmap of the world to calculate different densities of clouds may prove to be more 'realistic' or to appear more procedural. For example, use the getFirstUncoveredBlock(int, int); method in World (MCP unobfuscation), so that you know when for cloud entities to build up over seas and hilly terrain and to dissapear over sand and deserts. Just my two cents

# Answer
> 0 votes
It's quite viable. You just need to keep tweaking things until you get the results you like; procedural content generation is like that. This would probably be true even if you wanted to avoid doing the generation at runtime and produce a static texture map or something that defined the cloud pattern -- you'd likely just be tweaking the procedural controls for the Perlin filters in Photoshop, for example.

It looks like your current approach is based on generating noise and then thresholding it so you eventually have a Boolean value in your cloud map for "is this a cloud block or not." If that alone isn't giving you results you like, you might try applying varying degrees of thresholds in a loop instead of the simple test you've got now, with the hope of consolidating the contiguous blocks of cloud.

In fact, you could also look at it like generating organic rooms (caves for example) in a Roguelike. There's an article here on doing cellular-automata-based smoothing of an initially random data set to produce smooth cave-like rooms, which may be adaptable to your needs. The basic premise is to generate a random 2D grid of cloud and non-cloud tiles, and then for each tile in the grid, change it to a cloud or non-cloud based on how many tiles of whichever type are currently surrounding it. You can apply the algorithm any number of times to play with the smoothness. It might be worth a shot.

(It also might be neat to extend this into 3D a bit, not necessarily for the purpose of animating the clouds, as Byte suggested, which I feel may look odd in the discrete world of block-levels unless you also have varying degrees of cloud block opacity, but just for making actual 3D clouds that aren't constrained to a block plane as Minecraft's appear to be).

---
Tags: xna, c#, minecraft-modding
---


title: Rendering an object more than once

text:
# Question
Title: Rendering an object more than once
Right now I'm facing the issue of rendering the same objects more than once in Directx 11, as the object has:

* A diffuse shader
* A directional lighting shader
* A texture shader

Now the final color should be all of them somehow put together, maybe something like this:

* Render Diffuse
* Render Texture
* Render Directional
* Final Color = (Diffuse + Texture) * Lighting // Not sure about this though

But how can this be archieved? Without the EFFECTS FRAMEWORK!

# Answer
> 1 votes
You don't need the effects framework to use shaders, you can still just write a shader and create/bind it directly (for example, using this function for vertex shaders and VS's built-in HLSL compiler or D3DCompileFromFile).

You can achieve this by literally rendering the object multiple times, changing the shader that is bound each time, and setting the blending mode to do additive blending if that's what you want. However, that seems costly.

You could also just write a single shader that performs the appropriate computations for the diffuse term, direction lighting term, and reads the color from the read and modulates it by the lighting terms. This way you avoid the overhead of repeatedly rendering and changing shaders, and you get a bit more control over the way your color terms are combined (blending with the framebuffer isn't fully programmable, you can only pick from a pre-defined set of options, so that limits you somewhat).

---
Tags: c++, shaders, rendering, directx11
---


title: Android real time multiplayer over LAN

text:
# Question
Title: Android real time multiplayer over LAN
I've developed several games for the android platform and now planning to create my first multiplayer game. What I have in mind is basically just a 2-player game witch you can play with 2 phones over local area connection/WiFi.

Both phones need to be able to pass 3 integer values to the other phone in real time. So far I have considered using Socket's, but before I dig into it too deep I wanted to ask if there might be a better approach?

Thanks!

# Answer
> -2 votes
One option you might look at is Socket.IO.

There seems to be a lot of discussion of Socket.IO at Stack Overflow, including:

Alas, I couldn't figure out how to get one Android device to directly communicate to another Android device through Socket.IO, or even one step of indirection with both talking to a single WiFi access point between them. (I still don't know if that was a bug in my code, some sort of firewall in someone else's code, or an inherent limitation of Socket.IO). I did get one little demo working with one Android device sending messages to a web server, which forwarded the message to the other Android device.

# Answer
> -2 votes
Did you say both devices were in the same room?

Each Android device has a speaker and a microphone. In principle, it's possible for one app to to send a series of tones out the speaker, and then the other app to listen for the tones and decode them back to a message string. You could either (a) use the entire audio spectrum to send data, something like the acoustic couplers of the 60's and 70's, or (b) use a much narrower bandwidth from 15 KHz to the highest your device supports (probably 24 KHz) -- a much slower data pipe, but most people can't hear those frequencies any more -- it's ultrasonic to them.

Ham radio operators have developed many clever techniques for pulling extremely faint signals out of lots of noise.

"Communication over the Audio Jack for Android phones"

Reading sound on Android:

"Narrate's Zoosh software leverages smartphones' speakers and microphones to enable the same data communications between devices that today's NFC provides, but with ultrasonics frequencies that are inaudible to humans." -- Eweek, Slashdot.

---
Tags: java, android, multiplayer
---


title: Powder games: how do they work?

text:
# Question
Title: Powder games: how do they work?
I recently found these two gems:

http://powdertoy.co.uk/

http://dan-ball.jp/en/javagame/dust/

My question is: How are the physics with so many elements efficiently handled? Am I just severely underestimating modern computing power or is it possible to 'just' have a two-dimensional array, each cell of which describes what is placed at the according position and simulate each cell in every step. Or are there more complex things being done like summarising large areas of the same kind into a single data set and separating said set as needed?

Are there any open-source games like this I could look at?

# Answer
> 5 votes
There's certainly quite a few; I used to mod them. Note the links are for forum threads and source downloads. The two I have the best memories of are:

EngimaSand by xavierenigma (C++ | Java ) The Java one is newer.

BurningSand by sieben (C++) This one is very fast physics-wise.

The site is unfortunately close to death, but there's several threads here about physics.

EDIT: For anyone interested, I have mediafire'd the Java source for EnigmaSand here.

# Answer
> 5 votes
The physics in these games is simulated by use of a system based on a complex cellular automaton. It's significantly more complicated than the one used in, say, the Game of Life, and incorporates features that mean it's probably not a proper CA, but it's still relatively simple to calculate and has been for years. Not to go into too much detail, but the complexity of the algorithm is going to be quite small, perhaps even O(area).

It looks like there's also some swarm intelligence in there, which is also surprisingly efficient for the interesting effects it can create.

# Answer
> 3 votes
Many years ago Jos Stam started putting out his source code for fluid solvers. There is a very short bit of code that sets up a grid and solves the Navier-Stokes equations very fast. The full source is available on his page as well.

---
Tags: physics, efficiency
---


# Question
Title: XNA 2D: How to load/unload specific content by level
I'm writing a 2D room-based\* platformer using XNA, and I'm trying to figure out the best way to load resources based on what the current map requires. Basically, I need to (want to) dispose of the loaded tileset/textures and load just the ones the next map requests at every transition (ideally, I'll check if they're actually different first), without killing off the more universal textures (player sprites, etc.).

I've seen a few forum posts saying the best way to do this is to create a second instance of ContentManager, but they never go into detail on how to do this correctly.

Currently, my XML map files each contain strings with the filenames of all necessary assets. I was planning on having my XmlReader method load the textures as their names were read, but then I realized I knew neither how to instantiate the second ContentManager, nor where to instantiate it--i.e., should it be in the MapFactory class that's loading the map, or in the static LevelManager that's calling the MapFactory (passing the new ContentManager as a parameter to the MapFactory, along with the name of the desired map)?

Alternatively, is there a simpler/cleaner way to do this? I'm more concerned with the code being easily comprehensible than efficient right now, as this is my first attempt at this kind of game.

\*Ex. Castlevania, Metroid, but simpler (for now). I'd like to implement constant streaming eventually (chunks loaded as they are approached), but I want to get this part down first.

**UPDATE:** Instantiated the second ContentManager using `this.Services` inside the Game class (it was the only way I could find to get access to `Game.Services`, which is what everywhere online says to use in the ContentManager constructor). Should have thought of that sooner. For anyone confused by this in the future, the full line of code is:

`ContentManager myContent = new ContentManager(this.Services, "myContent")`

# Answer
> 4 votes
You could create specific classes for each level which inherit from ContentManager, and use a LoadContent() method in each, to override the base LoadContent() call.

You might also want to look at XNA's GameComponent class which itself inherits IDisposable. If each level was defined as a drawable game component, handling the disposal of each texture tilemap would happen when the game component itself is disposed.

# Answer
> 2 votes
There's a couple ways that you can do this. One way, using the content manager is to create a second one that is specific to your level's data (just use the existing manager's properties in the constructor of the new one). Another way, is to not use the content manager at all and for Textures/audio/etc use the FromStream static method to create them and then use .dispose to delete them (Maybe make your own content manager from that).

In regards to your map, you could make a static method like LoadFromXML or have a constructor option that loads from a file. You could even go through the hard work of making a content importer/processor for your map

---
Tags: xna, 2d, resource-management
---


# Question
Title: Playing basic imported animations in UDK
I'm trying to wrap my head around basic animations in UDK.

I've created a simple turret-like structure in Maya, rigged, skinned, and animated. It has 4 bones. I have done all the steps necessary for exporting and importing as an FBX (baked animations, etc.)

I've imported it into UDK, and can view both the AnimSet and SkeletalMesh in the Content Browser.

The AnimSet Editor previews the animation perfectly. This is a looping animation. I can load the SkeletalMesh into my scene, but I can't figure out how to trigger the animation.

**What is the simplest way to trigger this animation at run-time?**

I could have it start when the scene loads and loop indefinitely, or I could have it triggered by pressing a switch or using a trigger volume. I just can't figure out how to make that happen.

Also, any resources on diving deeper into this subject would be greatly appreciated as well. Thanks!

# Answer
The simplest way would be to create a kismet sequence.

Create some form of trigger mesh - or timer, that when triggered activates an animation on the skeletal mesh

There is some great reference on the skeletal mesh pipeline as well as kismet on the UDN

http://udn.epicgames.com/Three/VideoTutorials.html#Skeletal%20Mesh%20Pipeline%20-%20Using%20UDK
> 1 votes

---
Tags: animation, udk, maya
---


# Question
Title: Javascript - create a new bullet instance every time a user event is triggered
Basically I have a function that I need to create an object of every time the user presses space(event listeners not shown here).

```
function arrow(){
    this.x = playerXPos + 40;
    this.y = playerYPos + 40;

    this.init = function(){
        var arrowImg = new Image();
        arrowImg.src = "arrow.png";
        c.drawImage(arrowImg,this.x,this.y);

        this.x+=10;

        if(this.x > 500){
            keySpace = false;
        }
    }
}

if(keySpace){
    arrowObj.init();
}

```

This works great, but I can only have 1 arrow on the screen at once, which is rather limiting. Is there some way to create a new object every time the if statement is true, and store it in an array or something?

# Answer
You can use `new` to create a new object, initialize it and then store it in an array

```
// declare this array in a scope that persists (e.g. global scope or in a closure)
var arrows = [];

if(keySpace){
    // create new arrow, initialize it and store it in the array of arrows
    var newArrow = new arrow();
    newArrow.init();
    arrows.push(newArrow);
}

```
> 3 votes

# Answer
You could also do more or less the same thing, but alocate a fixed size array from start and then just fetch one that isent in use. This is much more memory friendly.

this is called memory pools.
> 2 votes

---
Tags: javascript, html5, projectile-physics
---


title: Oriented Bounding Box - How to?

text:
# Question
Title: Oriented Bounding Box - How to?
I've been trying to write my own collision code, less because I want to, more because I want to understand its working.

To do this, i've been working off of the popular collision book i'm sure you've all heard of: Morgan Kaufmann Real Time Collision.

I'm on the subject of Oriented Bounding Boxes. These are boxes that can have an orientaiton applied to them. If it matters, i'm doing my code in 2D. It seems easy enough to just cut out an axis from the books calculations.

Here is the OBB they define:

```
// Region R = { x | x = c+r*u[0]+s*u[1]+t*u[2] }, |r|<=e[0], |s|<=e[1], |t|<=e[2]
struct OBB {
    Point c;     // OBB Center Point
    Vector u[3]; // Local x-, y-, and z-axes
    Vector e     // Positive halfwidth extents of OBB along each axis
};

```

The confusing one is the Vector array, u.

Point c is the center 3 axis position of the box. Vector e is the width, height, and length of the box. Vector u\[3\] baffles me. My best guess is that it is the center-point of each of the 3 sides (with the reflected 3 finishing the box)

How does rotation work into this? Is the Vector u\[3\] taking the roation in somehow? How?

# Answer
The `u[3]` is a 3x3 rotation matrix mapping from the OBB's local space to world space. The three elements are the vectors that the x, y, and z axes of local space end up being mapped to by the rotation. So your guess was somewhat correct - the vectors do point to the center of each of three perpendicular sides of the OBB. However, they are unit vectors; the actual (half-)size of the OBB along each axis is stored in `e`.

The answer is actually in the comment above the struct. The expression `r*u[0]+s*u[1]+t*u[2]` is just multiplying the vector (r, s, t) by the 3x3 matrix `u[3]`.

For 2D, the equivalent of this data structure would have only a 2x2 rotation matrix, so you could define it as `Vector2D u[2]`.
> 6 votes

# Answer
The statement `Vector u[3]` is a matrix. A common method in computing and programming for performing rotations is to use an array of vectors to represent a matrix that defines the rotation of the object. In order to create a rotation matrix for an object you simply take a matrix of the same dimensions (in this case 3x3) and use the rotations in all three coordinate directions to construct a general matrix form.

A good resource for information on rotation matrices is the wikipedia page: http://en.wikipedia.org/wiki/Rotation\_matrix

For 2D there is only one rotation matrix to think of which is as such:

```
float theta;     // the angle of rotation
R= {{cos(theta), -sin(theta)},
    {sin(theta),  cos(theta)};

```

Once you get into 3 dimensional space rotation matrices tend to look a lot more complicated than they really are. In three dimensional space you can form a single rotation matrix simply by multiplying the rotation matrix for each coordinate directions like such:

```
 GenRotMatrix= XRotMatrix * YRotMatrix * ZRotMatrix;

```

Information for rotations of objects are commonly kept in an object known as a transform. The transform generally defines the position, scaling and rotation of an object in the world space.

I am not familiar with the book itself, so I cannot say with impunity that this is what he is doing as in computin there is always several ways of doing things. But if I had to hazard a guess this would be what he is doing. And the vector u is simply the general rotation matrix `GenRotMatrix` from above which represents the objects rotation in world space.
> 1 votes

# Answer
Is u\[3\] the direction the box is rotated in?

Think of a box centered at the origin, rotated by a vector (u) and then shifted to c.
> -1 votes

---
Tags: collision-detection, vector, c
---


title: Ghost replay - storage and timing

text:
# Question
Title: Ghost replay - storage and timing
I am working on a car race game and just implemented a ghost sprite for replaying past races. I use a physics engine and after much reading I came to the conclusion that the best way to store the ghost data for replay would be to record the car's position and rotation at given timepoints, as for example described here: https://gamedev.stackexchange.com/a/8380/26261.

But what would be a good way to find those timepoints during replay? An example would be a record with this data:

```
time: +3.19932 (seconds since race start)
position:  180,40 (position at that time)
rotation: 30.4 (rotation at that time)

```

But I have several problems with that:

1. When I replay, it's unlikely that I reach the exact timepoint at 3.19932 again - more likely, I will have a timepoint around 3.1 and have to find the closest matching record. When interpolating, even the closest matching above and below. This sounds very inefficient and time consuming?
2. In which list structure could I store these records for a later replay? An array? Doesn't that mean that search time for records matching a certain time will increase the longer the race is?
3. Which frequency should I use for timepoints? Each frame would be -I guess- overkill, rather I should save i.e. every nth frame and interpolate in between, which makes the storage questions in 2. even more difficult.

So is this idea even the right approach? If yes, how could I efficiently store and retrieve the data? Please note that I generally would like to go with using the data structure above, not deterministic gamestates and recording user input etc.

Thanks for any help!

EDIT: I realise I should describe the environment I use: Cocos2D for iPhone. There is a method `update:(ccTime)delta`. Ideally, this method would be called every 1/60 seconds, but there is no guarantee - `delta` is the actual time passed since the last gametick and could be a lot more or less than 1/60. It is in this method where I would like to store the current gamestate.

# Answer
> 8 votes
> Doesn't that mean that search time for records matching a certain time will increase the longer the race is?

Nope :)

Say you store it as an array (note the snapshots are in chronological order, but not evenly spaced):

```
snapshots = [
    {time: 0.0, position: {x,y,z}},
    {time: 0.41,    position: {x,y,z}},
    {time: 0.57,    position: {x,y,z}},
    {time: 1.10,    position: {x,y,z}},
    {time: 1.67,    position: {x,y,z}},
    {time: 2.05,    position: {x,y,z}},
    {time: 3.24,    position: {x,y,z}},
    {time: 3.86,    position: {x,y,z}},
    {time: 3.91,    position: {x,y,z}},
    {time: 5.42,    position: {x,y,z}},
    ...]

```

Then, when the replay/game starts, you get the first and second element from the array:

```
nextIdx = 1
previousSnapshot = snapshots[nextIdx-1]
nextSnapshot = snapshots[nextIdx]

```

Then in each frame (`currentTime` is the current time in this new game):

```
if currentTime > nextSnapshot.time
    nextIdx++
    previousSnapshot = snapshots[nextIdx-1]
    nextSnapshot = snapshots[nextIdx]

# Do your magic here, e.g.:
snapshotPairGap = nextSnapshot.time - previousSnapshot.time
ratio = (currentTime - previousSnapshot.time) / snapshotPairGap
ghostPosition = {
    x: previousSnapshot.position.x + ratio*(nextSnapshot.position.x - previousSnapshot.position.x)
    y: previousSnapshot.position.y + ratio*(nextSnapshot.position.y - previousSnapshot.position.y)
    z: previousSnapshot.position.z + ratio*(nextSnapshot.position.z - previousSnapshot.position.z)
}

```

Of course this could be optimized by caching some of the calculations. There's no searching through the array, just looking up specific indices.

# Answer
> 15 votes
It's not too hard. You can store your data at arbitrary points in time (the more, the better), and you can interpolate the values of the data based on the timestamp you're looking for and the data from two closest recorded timestamps, e.g.:

```
N | Time | Position | Rotation
1 | 0.05 | 1, 1, 1  | 0
2 | 0.15 | 1, 2, 1  | 0
3 | 0.25 | 1, 3, 2  | 30

```

Now imagine you want to get position and rotation at time 0.10. As 0.10 is between points '1' (meaning 0.05 time) and '2' (meaning 0.15 time), you need to interpolate these.

```
timestamp = 0.10
factor = (timestamp - Time[1]) / (Time[2] - Time[1])
position = Lerp(Position[1], Position[2], factor)
rotation = Lerp(Rotation[1], Rotation[2], factor)

```

`Lerp` is just linear interpolation.

So let's fill the gaps with some examples (\*).

```
N | Time  | Position    | Rotation
1 | 0.05  | 1, 1,    1  | 0
* | 0.075 | 1, 1.25, 1  | 0
* | 0.10  | 1, 1.5,  1  | 0
2 | 0.15  | 1, 2,    1  | 0
* | 0.20  | 1, 2.5,  2  | 15
3 | 0.25  | 1, 3,    2  | 30

```

HTH.

---
Tags: storage, timing, replays
---


title: Animation: mid-state

text:
# Question
Title: Animation: mid-state
At the moment I have a simple static texture. Now I want to animate my sprite. The texture is a simple human. When the user press the enter button, the human gets into state2. This is the standart state during gameplay. If the user presses now "space" the sprite should get into state4(4th texture). This would be very unsmooth, so I decided to make a State3(ist just displayed very short to make the animation smooth). Now the sprite is in state4. If the user now releas the "space"-key the sprite should return into State2. For smoothness there is State3 short between.

I use XNA. I have 4 states:

**State1** *press enter*" --\> **State2** --- "*press space*" --\> (short **State3** for smoothness) --\> **State4** --\> "*release space*" --\> (short **State3**) --\> **State2**

I hope you understand what I mean.

How can I solve this animation? Should I change the texture of the sprite?

# Answer
> 1 votes
Add a timer for transition between states and then decrease the time during state3. For examples:

```
enum State
     {
        state1,
        state2,
        state3,
        state4
     }

float timer;

// Your game loop update function
void Update()
{
   switch(state)
   {
      case State.state3:
           timer -= Time.detlaTime; // delta between frames in miliseconds
           if(timer <= 0)
           {
              state = State.state4;
           }
           break;
           /* Your
           *  logic
           *  here
           */

```

---
Tags: xna, c#, textures, animation, monogame
---


# Question
Title: Making Video Games In pure Java, where to go?
I have been programming for about a year now, and have a very good grasp on all the basic of programming in generally and am a pretty decent Java programmer, so now that I have the time I would like to start making games in Java. However, Id really like to not use any extra libraries, and just use pure Java for the first little bit until I fully understand the mechanics of a video game.

I have been looking around the internet and have seen more "best ways" to do this than I can count. So if somebody could point me in the right direction that would be great! (As in send me to the best, easiest to follow, and most up to date resource either print or on the web)

It just seems that no matter where I look I get completely different info on the same subject. So I would really appreciate if somebody could just give me a resource that follows whatever the current standard is. P.s typed on my phone so sorry for any typos :-)

Edit: I think I will simplify my question a little bit. In my main class where my game loop is should I be extending canvas, JPanel, JFrame, or something else? This is my main point of confusion right now because I have seen it done all these way and everybody has an opinion on what is better.

# Answer
> 2 votes
When you want the current standard method to build a game engine then I have to disappoint you: there is no such thing. The reason why you see so many "best ways" is that there is no such thing as a best way to program a game. There are countless ways to skin the cat. Some are faster or slower, some are cleaner or messier. In the end every game plays differenty, so it's just logical that they also work completely different under the hood.

Use your intuition and do what feels like it will result in an efficient and maintainable software architecture.

Regarding your question where your game loop should be:

I wouldn't recommend you to extend a GUI class and do it there, because it is usually a good idea to separate the visual representation from the gameplay itself. When you claim to be a decent Java programmer, you are certainly familiar with the MVC pattern. This pattern also applies well to game development. Implement the gameplay (model) in one class, the graphic engine which visualizes it (view) in another and the user input handling (controller) in a third class, and let them communicate through well-encapsulated interfaces. That way you can easily make changes to one without affecting the other.

# Answer
> 4 votes
You should really consider the lwjgl solution http://www.lwjgl.org/, even though you clearly stated in your question that you dont want to rely on libraries.

It includes alot of what you will need. Think about it again.

# Answer
> 2 votes
I found these youtube tutorial series to be very informative:

http://www.youtube.com/playlist?list=PL656DADE0DA25ADBB

http://www.youtube.com/playlist?list=PLlrATfBNZ98eOOCk2fOFg7Qg5yoQfFAdf

http://www.youtube.com/show/java2dgameenginedevelopment

# Answer
> 1 votes
The question is somewhat contradictory. First of all, if you want make game, even very simple you should use libaries that help you in that task. Otherwise you are just unreasonably making things hard for youself and simultaneously losing time (eventually you will be forced to use some kind of library or engine anyway). So if you think that using libraries somehow will hurt your gamedev skills in future - you are wrong.

There is no really "current standard" for game development, unless we are talking about some fundamental things such as ubiquitous "game loop". By "no standards" I mean that there are different approaches to different aspects of a game. As a result there is really no specific answer to how you should make your game.

I find it's easy to start by making clone of some simple game of the past, like Tetris or Breakout.

---
Tags: java, swing
---


# Question
Title: SetBase with a KActor descendant does not appear to function
I have a KActor descendant, which is a carging shot, kind of like in R-Type. When it starts charging, I do projectile.SetBase(Pawn) in the PlayerController where it is spawned. I've checked in the debugger, and its base is in face the pawn.

But it does not move with the pawn.

I have done this before, where I base KActors on a moving entity, and it moved with them. I must have done something differently, but I can't figure out what it was. Looking at the old code, I just did SetBase like I am now.

Any ideas where I might be going wrong?

# Answer
> 3 votes
The answer is that you have to SetPhysics(PHYS\_NONE) before basing it. Apparently this is not necessary if you are basing it on another descendant of KActor, since they will then be handled at the same time in the Tick cycle.

---
Tags: udk
---


# Question
Title: How to correctly check for HW T&L on Direct3D?
In theory, to check for HW T&L in Direct3D, one calls IDirect3D9::GetDeviceCaps and checks for the HWTRANSFORMANDLIGHT flag to be set in the returned structed.

However, the documentation states:

> The application should not assume the persistence of vertex processing capabilities across Direct3D device objects. The particular capabilities that a physical device exposes may depend on parameters supplied to CreateDevice. For example, the capabilities may yield different vertex processing capabilities before and after creating a Direct3D Device Object with hardware vertex processing enabled. For more information see the description of D3DCAPS9.

If I understand this correctly, GetDeviceCaps could return that HW T&L is not supported before creating a device, and return that it is supported after. But if I can create a device with HW T&L successfully, then there is no point checking for HW T&L support!

So my question is, is there any purpose to checking for HW T&L using GetDeviceCaps, or am I better off just attempting to create the device with HW T&L and seeing if it succeeds?

# Answer
> If I understand this correctly, GetDeviceCaps could return that HW T&L is not supported before creating a device, and return that it is supported after.

It's more the opposite case: if your hardware doesn't support T&L then no device creation params are going to change that. On the other hand, if your hardware does support T&L then it's possible that device creation may give you a device with which it's software-emulated, although to be honest I'm finding it difficult to think of a situation in which that may happen.

It's important to realise that much of the D3D9 documentation dates back to 2002 or thereabouts (and a good chunk of even that was recycled from the D3D8 documentation), and the state of hardware was *very* different back then. So the documentation should be read in the context of the hardware that was available at the time it was written; nowadays you can pretty much assume that you have hardware T&L available irrespective ((dis)honourable exception - some older Intels from 2006/2007 or so). In particular, if you're running on D3D10+ class hardware (or Windows Vista+ with Aero enabled), the presence of hardware T&L is absolutely guaranteed.

In general you can just attempt to create a device with hardware T&L; if it fails where to go from there depends on how comfortable you are with the options available to you. One approach may be to treat it as an error condition and just crash out. Another approach may be to attempt creation of a software T&L device, but beware that there are subtle differences between how each class of device handles some things (mostly vertex buffer updates) with things that work on the one failing on the other, so if you're going to do this then be sure that you test fully on both types.
> 3 votes

# Answer
Generally, one would try to create the device with hardware support and if the creation of that device failed, fall back to software.

As long as you handle the failure appropriately, there's no particular danger in "checking" for vertex processing capabilities this way and it is less error prone in weird edge cases than using the `IDirect3D9::GetDeviceCaps` method, for the reasons you outlined.
> 3 votes

---
Tags: c++, directx
---


# Question
Title: Methods of procedural terrain generation that can work using DirectX 9 (SM2.0)?
I'm working on a simple game / fun project that I want to be largely procedurally generated. At first I started by using boxels (Similar to Minecraft, but not textured) for the terrain and it came out looking decent but I realized something.

I don't need, or really want, destructible terrain. Sure it'd be a nice little bonus, but no part of my game design calls for it, and using boxels requires a fair amount of data to be sent to the GPU, so I'm looking for alternatives and that's where I'm stuck...

What are some *alternatives to boxels* that can be used to generate terrain quickly, that looks good (Smooth terrain or otherwise), and can be rendered with XNA (Shader Model 2.0)? At first I thought that **marching cubes** could work, however apparently since XNA still uses DX9 - most of the work is done on the CPU. Then I looked into **dual contouring**, but I can't find much data on it and I'm afraid it suffers the same issues.

Right now **height maps** are looking halfway decent, however I don't want to abandon the idea of overhangs and whatnot completely, so... What else is there? I'd love to keep using *voxels* since they make procedural generation easy (And fun), but, and correct me if I'm wrong, XNA doesn't handle non-boxel rendering of them very well.

*(Even if I'm wrong re: marching cubes, I'd still be interested in seeing worth-while alternatives that can run on low end machines using SM2)*

**Note:** My highlighting of words is to help anyone who, like me, finds this after searching for methods of procedural terrain generation, and wants a quick list of what's available.

**Edit:** Still looking for an answer regarding different methods.

# Answer
> 2 votes
Firstly, from your question, it sounds like you want to generate the polygons and texture coordinates on the fly, for every frame of your game. This is bad. *No, really.* **There is *no algorithm* to take volumetric datasets and quickly turn them into surface/area datasets.** (Read: Take volumes of data and use it to push flat triangles onto the screen.) Realize that what marching cubes, dual contouring, and other algorithms are doing is reducing volumetric data down to surface/area data, which is *an order of magnitude easier to deal with.* Hardware is fast, but not that fast. *Volumetric data is big*, if you've got it detailed enough to make it look good.

Remember that the time required for marching cubes is *O(n * m)*, where n is the number of cubes, and m is the cost of getting the scalar value a corner of a cube. Since you're presumably going to have a large map, you're not going to want to recalculate things which aren't changing. Since your terrain won't be destructible, this means that:

* Your noise function only needs to be called once to get your scalars for marching cubes.
* Your marching cubes function only needs to be used once to get your terrain, with its corresponding image/collision data. (bounding boxes, triangles, texture coordinates, etc)

So, you need to separate the following into discrete steps:

* Noise creation.
* Terrain creation. (i.e. Marching cubes.)
* Terrain culling.
    + i.e. Remove sections of the map which the player would never interact with.
    + e.g. A hollow cave inside a mountain, without an entrance accessible to the player.
* Polygon/texture-coordinate generation.
    + If you're using marching cubes, you'll already have the polygons, but will still need to compute texture coordinates, lighting normals, etc.

After this point, regular optimizations, occlusion-testing, lighting, etcetera are the same as a normal game.

You should read through Shamus Young's programming section on his blog. At minimum, read about his *Project Octant*, which deals with overhangs/cliffs, and is a simple/fun project, like yours. You could also read through his *Terrain Project* and *Project Frontier*, although both of those earlier works use height-maps. His *Pixel City* project also deals a lot with simplifications, and approximations.

# Answer
> 1 votes
Its not really clear what your deliverable are here so its hard to define a "*right*" answer for you:

1. Must the solution be developed on the GPU or CPU?
2. Do you need to be able to stream massive terrains?
3. What kind of procedural landscape? Do you want to simulate mountains, rivers, oceans, caves?

All these questions and more need to be answered before any kind of concrete solution can be presented.

However I may be able to help you with some resources...

**CPU or GPU based generation?**

Most people would quickly tell you that the GPU is by far and away the best tool for procedural generation of terrain and the generation of it into a renderable polygonal surface, and they would be right. However it does add complexity and online resources are slightly less abundant. Secondarily, you sound like you have a requirement for your application to work on older hardware. This will be one more problem you'll have to solve on top of writing the surface generation algorithm on the GPU. All 100% doable. But it adds time and complexity. If you are feeling up to it there is a great article in the GPU Gems 3 website on this very topic.

The CPU is actually perfectly capable of generating a procedural terrain in real-time, and it is extremely well documented. If I were you I'd make my first pass on this project of yours completely CPU-based.

**Procedural Terrains**

Without knowing a little more about what you actually want to simulate I can't really provide much assistance. By far the most simple thing you could possibly do is just run a Perlin Noise function over your entire voxel terrain.

**Surface Extraction**

Once you've generated your terrain you need to display it. There are quite a few algorithms available to perform this function however there are a couple that stand out. The single best resource I have found to date on surface extraction has been by sdfdsf at 0FPS. He recently wrote a somewhat lengthy blog post on the lending real-time algorithms one can use to generate a smooth surface from voxel data. He even provides javascript-based examples. (Surface Nets are awesome!)

To close this off I might also point you in the direction of a great C++ based project called PolyVox. Its a great little library that can quickly get you off the ground with voxels.

# Answer
> 0 votes
Marching cubes is a pretty efficient algorithm. It's just a couple of lookups per cube and it works in O(n) time. You can also run it in parallel very easily using a thread pool, so even if it's constrained to the CPU it's pretty fast.

---
Tags: xna, shaders, procedural-generation, terrain-rendering
---


title: build a server clock in client

text:
# Question
Title: build a server clock in client
Like Warcraft of World, there is a clock to display the time of server rather than local time of the client.

How to do this?

If this can be done by server send only one package to tell client the current timestamp of server, then client based on this timestamp and goes tick on it, what if client have not a "reliable clock" such as Flash(clock will slow down when the FPS slow down)

# Answer
According to Adobe, Flash has a "Date.getTime()" function which returns the current local time, as set on the computer running the Flash application.

This should make it trivial to show the server time, regardless of frame rate or other factors. When you know the server's time, subtract the local time from that in order to know the offset from local time to server time. Then whenever you want to know the server time, you can just add that same offset to the local time. Frame rate doesn't come into it at all.
> 0 votes

# Answer
Ok I don't know about World of Warcraft or their implementation. Taking average network jitter and delays into account you don't get a very accurate reading about time from the server. (That is why NTP is difficult.)

If all you want to display is the server time, you just need to send the server's time and add the current round trip time to get a rough but around 100ms accurate time. From there you use the systems clock. Sure the systems clock drifts, but we are talking a few seconds a day at worst.

If you are thinking about actually using the servers clock for more accurate time reading or logic, I would strongly discourage you from that. You should use the local system clock as time of reference and work with time deltas based on that.

I am not sure what you mean by reliable clock. Everything above 1s is handled by the system clock with is a separate timekeeping IC which runs of of a quartz, like any other clock. Anything below 1s runs of the CPU ticks and they are very reliable, the CPU would not work if it was not the case. We are talking picosecond accuracy. You get reliable time readings down to 1ms easily. Just so I don't get grilled for it, the system clock IC actually runs more acuratly and the CPU uses that to sync up it's tick rate, wich is a multiple of the system clock tick.

So why does the time slow down while low frame rate? Do you mean simulation time as opposed to real (wall) time? In that case you have other problems to handle, like what happens when different clients have different time dilation. But the way I see it is that the server is the only authorative instance and the client only do prediction. The prediction is off by multiple 100ms anyway through network jitter, so time keeping is the least problem. It also helps to make client prediction and effect simulation frame rate independent. Sure it reduces accuracy, but on the client any simulation should be only for a smother experiences.
> 4 votes

# Answer
The packet to update the clock doesn't need to critically match the FPS of the client. Depending on the network protocol, or the packet structure itself, it would be enough to send a tick once every second. In most cases, the timestamp of the packet itself can be used to match the second tick of the server.

So, async or sync packets who have a timestamp, where the part identifying the "second" can be used to inform the client. Even if there are multiple packets sent each second, any of them can be used to extract the timestamp of the server.

There doesn't need to be a specific time update packet from the server each second, is what I'm trying to convey.
> 0 votes

# Answer
Generally the server clock is there for convenince to the user so being out by 30 seconds to a minute is not so bad.

If your building a game with say 1000 users, the last thing you want to be doing is sending 1000 NTP style messages every second or minute (unless you want to be super accurate).

Seeing as every computer has its own clock. When a user logs on, you can send your own time to the user, determine the offset between the server clock and their clock. and then just use thier clock + the offset to show the server clock.

I would not use timezone calculations as a clients computer may be fast or slow or just wrong. however if you calculate an offset, unless they go and change their clock, it will always show the correct time.
> 0 votes

---
Tags: synchronization
---


# Question
Title: Determining a point that reached another point
I have two points, one is moving and one is stationary. I would like to know if the moving point has reached that point or not. I tried to calculate the distance between two vectors and the distance never reaches 0.

# Answer
> 4 votes
You have one of these problems:

* a point doesn't even try to reach another point, and in 3D world it's very unlikely that two points hit each other (just like it's unlikely that one of hundreds of live threating comets will actually hit Earth)
* the point has velocities set to reach another point, but another point also has some velocity, and therefore will always run away (this reminds me of Achilles and turtle paradox)
* the point has velocities set in another point's direction, but it goes through it between checks, and if velocities are updated then, it just starts to oscillate the target point, never reaching it
* float rounding makes point A be 0.00000000001 pixels away from point B, but never exactly 0.

Solution is not to treat points as points, but as physical objects, giving them some size, e.g. spheres. You could assume a point is a sphere of 1 pixel diameter (0.5 px radius), it would mean you need to check if distance is \< .5+.5 that is `if (distance < 1)` not `if (distance == 0)`.

# Answer
> 1 votes
Check if the two points are close enough.

Lets say the speed of point A (moving point) is `speedA` and that the last frame was `delta` milliseconds long.

If A is moving towards B (stationary point) and is currently in a distance smaller than `speedA * delta / 1000.0` it will reach the stationary point in the next frame.

You need to check if the distance between the moving point and the stationary point is less than the size of one step for the moving point.

`distance(A, B) <= speedA * delta / 1000.0`

If that happens the moving point will reach the stationary point in the next frame.

If this never happens, it means that point A is not moving towards point B or that it is moving in a speed so slow that it will not allow it to reach point B in a finite time such (C/n^2) where n is the current frame index and C is a constant.

# Answer
> 1 votes
The reason why this is not working is because of your understanding of the problem. You are considering the two objects to be two points. In games the position of an object in world space is most commonly a vector quantity.

Instead you should consider these two "points" as vectors. Next you can follow a few simple steps to arrive at a solution.

1. You take either vector and subtract the other from it. This creates a vector based at the origin.
2. The magnitude of this vector will then allow you to determine whether the two obejcts are occupying the same space.
3. In order to do this you compare the magnitude to the a value commonly called r. r represents the lee-way that must be considered when performing any calculation on floats. Because we do not have infinite space to hold a float value there will always be rounding errors in calculations with floats.

The pseudocode for this would be as such:

```
float r= 0.0000000001f;   // the lee-way for our program
Vector3 a,                // your first vector
        b,                // your second vector
        c;                // a temporary container for the vector originating
                          //   at the origin
c= a-b;
if (c.Magnitude < r)
{
    // they are occupying the same space
}

```

I hope this helps.

---
Tags: c++, 3d, mathematics, vector
---


# Question
Title: Is it possible to push real-world, real-time data into Unity?
I'm pretty new to this, and I'm having trouble figuring out where to even look. If there's relevant terminology that'll be google-able, that would be a great help.

Suppose I want to have a monitor in-game that displays the output from a camera that's in the same room as the player. Are there libraries for grabbing and rendering that data?

# Answer
> 1 votes
The easiest way would be with render textures, but that is a Pro feature. If you need it for the free version, there might be a good alternative script somewhere. I've been hunting for months and haven't found anything that great. You could try scripting one yourself. If you do, I'm sure many would pay a fair price on the Asset Store so they don't have to buy all of Unity Pro.

# Answer
> 0 votes
What you might want to look at is a method to first capture the output of that camera to a JPEG. This could be a program supplied with your camera, or a freeware application from the internet.

After you have a JPEG image, you can simply use Texture2D.LoadImage http://docs.unity3d.com/Documentation/ScriptReference/Texture2D.LoadImage.html

This will provide a new image to the texture as often as you call the loadimage method. If fast enough, it will appear as video, instead of screen captures.

Then, apply the texture to a gameobject within your game with something like

```
renderer.material.mainTexture = cameraJPEGtexture;

```

---
Tags: unity, graphics-programming
---


title: AndEngine drawing 2D tiled game field

text:
# Question
Title: AndEngine drawing 2D tiled game field
I'm in process of developing simple android puzzle game. I decided to choose `andEngine` as an engine for my game.

In my game I have a `gameField [][]` array, which represents a game field, where each element is a cell of game level and consists of a type of the cell (for ex. `FLOOR` of `WALL`). During the game, state of cell can be changed (for ex. `DOOR_CLOSED` changed to `DOOR_OPENED`), but it happens rarely, almost all the elements of gameField don't change.

I tried to implement that by adding `repaint` method to `updateHandler`, which would paint sprites for each cell every tick. But I wonder wouldn't be that approach a wasting of memory and processor time? What is the best practise for doing that?

# Answer
How about having that multidimensional array of yours filled with, say, an extension of TiledSprites. Something like the following:

```
public class Door extends TiledSprite {

    private boolean isOpen = false;
    private static final int DOOR_CLOSED = 0;
    private static final int DOOR_OPEN = 1;

    public Door() {
        this(0, 0, doorTextureRegion, vertexBufferObjectManager);
        this.setCurrentTileIndex(DOOR_CLOSED);
    }

    public open() {
        this.isOpen = true;
        this.setCurrentTileIndex(DOOR_OPEN);
    }

    public close() {
        this.isOpen = false;
        this.setCurrentTileIndex(DOOR_CLOSE);
    }

}

```

In your scene, you attach all the TiledSprites as children of the scene. Iterate over the array in an initialization method, say. You shouldn't have to constantly poll and redraw--AndEngine takes care of that for you.
> 2 votes

---
Tags: android, andengine
---


title: XNA 2D game fullscreen issue

text:
# Question
Title: XNA 2D game fullscreen issue
I am creating a 2D farming game using XNA - just today I have tried applying full screen to it, and I realized I failed badly with something. It cuts off a bit of the lower part \[item hotbar and a piece of character status area\]

I have just started learning C# and XNA, I just totally rewrote the engine and changing everything with rendering all over again is not an option - honestly I have no idea myself how does it all work anymore \[I'm using some crazy camera class thing with an array of rectangles for displaying tiles / moving them around when the player moves etc\] :-P

In the previous version of the engine I used the default XNA window size and the full screen worked just fine, this time I changed it to something more ... comfortable, and it does not work anymore. Changing the preferred buffer width does nothing at all in full screen, it's still cut off, and still the same height. I have no idea what matrices or viewports are, and everything I seem to find on google refers to them and some crazy complicated stuff

The screen size I am using is 800 x 640

My screen is very long sideways \[whatever the name for such screens was :|\]

Is there a way to fix that without rewritting everything?

# Answer
Without getting into discussions about matrices and viewports etc, it looks more than likely that your sprites and tiles are being drawn just fine, but at positions that are outside of your fullscreen size.

Something like this in your main class should be there first:

```
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 640;
graphics.IsFullScreen = true;

```

Just to be sure you are setting the width and height for the fullscreen mode resolution. Then, you might want to look at reducing the x and y position of the lower hotbar by 1. This should move the hotbar one position towards top left in both axes.

Its hard to tell what else is missing from the lower part of the screenshot.
> 1 votes

---
Tags: xna, rendering, screen
---


# Question
Title: XNA 4.0 - Purple/Pink Tint Over All Sprites After Viewing in FullScreen
I'm a noob to the game dev world and recently finished the 2D XNA tutorial from http://www.pluralsight.com.

Everything was perfect until I decided to try the game in Fullscreen mode. The following code was added to the Game1 constructor.

```
        graphics.PreferredBackBufferWidth = 800;
        graphics.PreferredBackBufferHeight = 480;
        graphics.IsFullScreen = true;

```

As soon as it launched in Fullscreen, I noticed that the entire game was tinted. None of the colours were appearing as they should. That code was removed, the game then launched in the 800x480 window, however the tint remained.

I commented out all my Draw code so that all that was left was

```
        GraphicsDevice.Clear(Color.CornflowerBlue);

        //spriteBatch.Begin();
        //gameState.Draw(spriteBatch, false);
        //spriteBatch.End();

        //spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
        //gameState.Draw(spriteBatch, true);
        //spriteBatch.End();

        base.Draw(gameTime);

```

The result was an empty window that was tinted Purple, not Blue. I changed the `GraphicsDevice.Clear` colour to `Color.White` and the window was tinted Pink. `Color.Transparent` gave a Black window.

Even tried rebooting my PC but the 'tint' still remains. I'm at a loss here.

# Answer
Created a new XNA project and copied all code and content files to the new project. Colours are perfect once again.

---

Now check this out:

I added the fullscreen code back to the Game1 constructor in the new project:

```
    graphics.PreferredBackBufferWidth = 800;
    graphics.PreferredBackBufferHeight = 480;
    graphics.IsFullScreen = true;

```

Game launched in fullscreen, colours were tinted again. However, this time, after switching back to windowed mode, colours are fine.

Then changed to my monitor's native resolution:

```
    graphics.PreferredBackBufferWidth = 1680;
    graphics.PreferredBackBufferHeight = 1050;
    graphics.IsFullScreen = true;

```

Game launched in fullscreen, colours were tinted again and remained tinted when I switched back to windowed mode.

Gotta copy them to another new project now.

Weird...
> 0 votes

# Answer
I encountered the exact same issue, and solved it by disabling nvidia 3D stereoscopic.
> 3 votes

# Answer
The reason might be the way in which the Content Pipeline works. It compiles the various content into xnb files, then loads these back again when you run the game. I think some of these xnb files are caching and arent being recreated when you switch screenmodes.

Try this to see if it helps: go into the Debug/bin or Release/bin folders in your project folder depending on your build configuration, and delete any files. Build and Run again, see if it solves the problem.
> 0 votes

---
Tags: xna
---


title: 3D pathing finding with flying

text:
# Question
Title: 3D pathing finding with flying
How can I enable 3D path finding? Basically something like:

```
CalculateRoute(input_geometry, start_pos, end_pos, variance)

```

I found a good paper on the topic, but I haven't found any solutions via Google or even searching sites like odesk, etc...

I know recast/detour is great for ground navigation, but I can't find anything that involves flying/3D space.

Any suggestions would be great.

# Answer
A\* is the go to for most path finding situations. It's no different with 3D spaces, including flying through the air.

Basically, you'll break your game up into nodes. This is called the navigation mesh. These nodes are typically cubes of various sizes. They don't all have to be the same size, you can make large open areas one big cube and the open areas near terrain smaller to have finer precision.

(unfortunately it appears the site I got this image from originally has gone under. They still have a video up on Youtube showing this in action though)

Implement A\* to use these nodes for path finding. A\* is nice because the node cost can be tailored specifically to your game. You can also give multiple nodes the same cost and randomly choose between them to have variances in flight paths. Once you've found the path, now is when you're going to use the red3d link to implement steering. You'll steer towards each node in your path, until you're "close enough", then start steering to the next node. This will give a smooth flight path between a linear node to node path.
> 7 votes

# Answer
The equivalent to **Navigation Meshes** for 3D spaces is **Navigation Volumes**.

**Havok AI** implements both navigation volumes and a volume pathfinder as shown in their GDC 2011 demonstration.

The principle of A\* in a volume is the same as A\* on a navigation mesh. Since A\* will find a path over any graph it doesn't matter if the graph is represented by a point to multiple points, a polygon to multiple polygons, or a volume to multiple volumes. The algorithm will still find a solution if one exists.

Some slight nuances that are different with paths found on navigation meshes is how you determine path points at the edge of line segments, at the ends, or maybe at the middle?

The same can be true of of navigation volumes, to determine the cost to traverse to the next volume you'll typically have to pick a point within the volume, midpoint/edge/etc.

This all essentially boils down to the heuristic part of the A\* algorithm you must supply yourself, or use a basic Euclidean distance algorithm.

**Path Following is not Pathfinding**

How your AI determines to follow this path is something completely different and is referred to as Path Following. The typical strategy for Path Following is to allow your AI to look ahead of where it's traveling to see if it can short cut the path to make more natural curved movements.

**Havok AI Demo at GDC 2011**

*The scene with numerous flying AI's*

*An inverted view of the navigation volume*
> 6 votes

---
Tags: algorithm, path-finding
---


# Question
Title: How can you implement Lua into your game?
I am trying to implement Lua into my game, but am having trouble. Say I have a weapon class, which is just a hollow shell, lacking real functions. I was thinking of creating an onFire function, which will simply call a pointer to a Lua function that was created for that weapon. Is this the way most people do it? Are there any other ways?

# Answer
You can indeed call Lua functions from C++ code, you'd just need to import a Lua header and compile against Lua libraries

This site offers great examples: Using Lua with C++
> 4 votes

---
Tags: c++, architecture, lua
---


title: High level project workflow

text:
# Question
Title: High level project workflow
We are a small software company trying our hand at our second game. Since our first games' process was a living nightmare (since we used webdevelopment workflow) I have decided to educate myself on how to manage a game project on a high level.

How does your process work, from idea to launch? Preferably in situations where you have a team that needs to cooperate.

I've seen these 2 links, which are useful in a way, but was wondering if there are better/more comprehensive ways to do this?

http://www.goodcontroller.com/blog/?p=136

http://gogogic.wordpress.com/2009/02/09/symbol6-how-we-created-an-iphone-game/

All input would be infinitely appreciated.

# Answer
Take a look at **Beyond Scrum: Lean and Kanban for Game Developers** http://www.gamasutra.com/view/feature/3847/beyond\_scrum\_lean\_and\_kanban\_for\_.php?print=1
> 1 votes

---
Tags: process, management
---


# Question
Title: In 2d game logic, should I use pixels or world coordinates?
Currently in my game I handle the logic (collisions, movement) using pixels but I find it very limiting espiecially when thinking about variable speed.

For example Box2D requires you to use coordinates in metres instead of pixels (for example 50 pixels = 1 metr). Also using normal cartesian coordinates would allow me to use trygonometry etc.

Should I use in my logic code coordinates not bound to pixels (ie metres)? Is it a better approach?

# Answer
This depends on the combination of frameworks you are using. Sometimes a 2D game framework makes it very difficult to work with coordinates that are not bound to pixels because they were designed specifically for designers to think about their game world in pixel units.

However, it's not a requirement. A game I'm currently working on relies on Box2D units being 1 unit in world coordinates, with each 1 unit grid in world coordinates being able to generally contain one tiled sprite, which is 128x128 pixels. This is strictly by our convention though, as you could simply scale the quad on which the sprite is rendered up or down to your desired size in screen and world coordinates.

Regardless of how your sprites are rendered, you should have a matrices for transforming your sprites' world/rendering coordinates to Box2D coordinates and back. Even if 1 meter == 1 world unit, if you make this flexible from the outset (not that difficult), you'll appreciate the flexibility.
> 7 votes

---
Tags: 2d, physics, movement, coordinates, logic
---


# Question
Title: How to calculate collision normal between two AxisAlignedBox's?
I'm writing a physics simulation in Ogre3D and I'm trying to figure out how to calculate the collision normal between two Ogre::AxisAlignedBox's.

I am checking for collisions using the "intersects" function then calculating the collision normals as below, but I am almost certain that this is where I am going wrong as my collisions are very unpredictable:

```
Ogre::AxisAlignedBox intersection = boxA.intersection(boxB);
Vector firstCollisionNorm = boxA.getCenter() - intersection.getCenter();
Vector secondCollisionNorm = boxB.getCenter() - intersection.getCenter();

```

After this, I am normalizing the collision normals, calculating the impulse magnitude using dot product, mass and relative velocity, then I multiply the collision normals by the magnitude to get the final impulse force vector, which is added to my current force vector as "impulseForce / deltaTime" for the next step of euler intergration.

If anyone could help me out I would greatly appreciate it!

Thanks

# Answer
The collision normal should be one of the faces of your boxes. Since you obviously allow some interpenetration you need to pick the closest face:

```
size = intersection.getSize();

float ax = fabs(size.x);
float ay = fabs(size.y);
float az = fabs(size.z);

float sx = boxA.getCenter().x < boxB.getCenter().x ? -1.0f : 1.0f;
float sy = boxA.getCenter().y < boxB.getCenter().y ? -1.0f : 1.0f;
float sz = boxA.getCenter().z < boxB.getCenter().z ? -1.0f : 1.0f;

if (ax <= ay && ax <= az)
    firstCollisionNorm = Vector(sx, 0.0f, 0.0f);
else if (ay <= az)
    firstCollisionNorm = Vector(0.0f, sy, 0.0f);
else
    firstCollisionNorm = Vector(0.0f, 0.0f, sz);

```

Then set `secondCollisionNorm = -firstCollisionNorm`.
> 2 votes

---
Tags: physics, geometry, ogre, collision-resolution, bounding-boxes
---


# Question
Title: Can you dynamically set which texture to use in-shader?
I'm working on a user interface system, and I want to be able to mix textured polies with frag-coloured polies. Here's my shader code, that doesn't work:

```
attribute vec2 vertex_coords;
attribute float texid;
attribute vec4 fragdetails;

varying float usingtex;
varying vec4 v_fragdetails;

void main(){
    gl_Position =  gl_ModelViewProjectionMatrix * vec4(vertex_coords,0.0,1.0);

    usingtex = texid;
    v_fragdetails = fragdetails;
}

```

Fragment:

```
varying float usingtex;
varying vec4 v_fragdetails;

uniform sampler2D thetexture;

void main() {
    if (usingtex != 0.0){
        thetexture = int(usingtex);
        gl_FragColor = texture2D(thetexture, vec2(v_fragdetails[0], v_fragdetails[1]));
    } else {
        thetexture;
        gl_FragColor = v_fragdetails;
    }
}

```

Frag\_details consists of either \[r, g, b, a\] for a coloured poly, with texid set to 0, or \[texture x, texture y, 0, 0\] for a textured one.

However, samplers must be uniform, and uniforms can't be modified. So how on earth would I swap between textures in one draw? Do I have to set them all up as uniforms and then pick from those? I'd have to use an array, and know the length, which isn't really practical for a UI system where buttons will be clicked, tabs changed, and so on.

Is there a way to do this?

# Answer
One way to do this is to make a texture atlas: a single large image that contains all the icons or textures you'd ever want to draw. You'd have some data structure keeping track of where each icon is in the atlas, and set up UVs appropriately when you generate the geometry. Then you can do the whole thing with one texture/sampler and one draw call.

If you include glyphs in the texture atlas as well, you can do all your text rendering using this system too.

To handle solid-colored polygons, you could write the shader to multiply the texture by a vertex color. Include a 1x1 white pixel someplace in the atlas and set up the UVs to use that for polygons that should be solid-colored; similarly, ensure the vertex color is set to white for any textured polygons. This does mean your vertex data has to include both color and UVs for every vertex.

Another possibility is to split things into multiple draw calls. You'd have a solid-color shader and a textured shader, with one draw call for solid colors plus one for each texture. You'd have a vertex buffer for each of these cases and while generating geometry, add each polygon to the appropriate vertex buffer.

One issue with this is that you won't have full control over the draw order. You couldn't have a solid-colored poly over a textured poly over another solid-colored poly, for instance. For UI this is a pretty big issue, so I'd go with the atlasing approach, which will ensure everything gets drawn in the order you specify.
> 4 votes

# Answer
For OpenGL 3.0+, an alternative to a texture atlas is a texture array, using sampler2DArray in GLSL. These are created similarly to 3D textures: `glTexImage3D(GL_TEXTURE_2D_ARRAY...)`, followed by `glTexSubImage3D(GL_TEXTURE_2D_ARRAY...)` to actually fill the texture data. For pre-3.0 openGL, there is at least one extension of similar functionality (EXT\_texture\_array), but I don't know how good it is or on what GPUs it works.

Texture arrays have some advantages over atlases, mainly you don't have to pack them and you don't have interpolation issues at edges of textures. You can use multiple textures in the shader because your texture coordinates become three-dimensional (UV + texture id). A texture array will probably waste more space if your textures aren't of similar size, though.
> 3 votes

# Answer
I came up with the following solution, if you really need access to multiple samplers in a FOR loop. this even works with OpenGL ES 1.0! as you only can define 32 samplers maximum it is feasible i think.

```
uniform sampler2D tex[32];
vec4 c = vec4(0.0,0.0,0.0,1.0);

vec4 getColor(float i, float x, float y) {
    int ii = int(i);
    if(ii==0){c = texture2D(tex[0], vec2(x, y));}
    if(ii==1){c = texture2D(tex[1], vec2(x, y));}
    if(ii==2){c = texture2D(tex[2], vec2(x, y));}
    if(ii==3){c = texture2D(tex[3], vec2(x, y));}
    //...
    return c;
}

//in main in for loop with increment i:
//where as x and y are your coords.
vec4 color = getColor(i,x,y);

```
> 3 votes

---
Tags: opengl, glsl
---


# Question
Title: Where and how to check if game was developed with bought Unity3D licence (not cracked app)?
We hired an external team from Eastern country. They built our mobile game app using Unity3d which we paid a lot of $K. We asked them to only use the software with bought license, not cracked one, and they said they will do it.

Now, we're ready to publish apps to official stores and I read on the net that guys from unity3d can always check if the app was made via bought license or via cracked software. If they discover it's been made with cracked software, they will ban the app and probably prosecute us.

Where can we find such tool to confirm that our software was indeed made by 100% licensed unity3d piece of software?

# Answer
> 11 votes
I don't know if it's true that Unity can validate that a deployment of a game was made with a valid license or not, but it looks like if it is true they haven't released any tools you can use to perform this validation yourself (which is not uncommon, offhand the only company I'm aware of that does make it possible for you to do this yourself is Microsoft with Windows and Office).

Your best bet, then, is likely to

* Get in touch with your developer and ask them to provide some kind of validation or proof that a valid license was used.
* Get in touch with Unity and ask them if they can help resolve your situation.

It's not really, strictly speaking, Unity's problem but they may be willing to help you out if you explain your situation.

# Answer
> 4 votes
As Josh mentioned in his answer, asking for proof is pretty much the only thing you can do -- something like a screenshot of purchase confirmation, or the email they send you when the purchase goes through.

Better yet, next time, you buy it and send them the license key.

Better still, put something in your contract next time if you don't trust them -- some sort of penalty/punishment/contingency. Since it seems like you don't trust them, I would go so far are putting a clause like "you get paid when the app successfully makes it to the app store, and not before." (Of course, you will probably still need some sort of good faith down payment.)

---
Tags: android, 3d, unity, ios
---


title: Powerup Best practices

text:
# Question
Title: Powerup Best practices
In a turn based game each player has a set of properties, e.g attack, defence, speed and these can all be used to work out who should go first and how much damage should be dealt. That all works fine, but the problem I'm having is with edge cases where a player receives a power-up for one turn that lets them move first. How should I handle this? Should I increase the speed value and then somehow remember to reduce it next turn or should I implement some sort of object which holds modifiers that is checked every turn?

I'd also need to be able to scale this to different things like temporary poison etc.

Basically I'm very confused and help would be appreciated!

# Answer
First thing, can the user have more than one boost/powerup at a time? For example, can they have a speed boost and be poisoned at once? If not, you can simply keep an integer 'powerup' lying about, and say for example

```
if (powerup == 1){
  //speed boost
}else if(powerup == 2){
  //poison
}else if(powerup == 3){
  //etc.
}

```

If you can have multiple modifiers at once, you'll need some sort of listing method. I use Java, so ArrayLists are what I would be using, but I think AS3 or JS arrays are similar. It would be easiest to make a powerup class with a few variables like "timeSinceActivated" or "timeLeft", and then increment or decrement them appropriately each turn.

for example:

```
class PowerUp{
  int timeLeft;
  int power; //if you want some poison to be stronger or whatever
  public void update(){
    timeLeft --;
  }
}
class SpeedBoost extends PowerUp{
  timeLeft = 1;
  @override
  public void update(){
    super.update();
    playerspeed = 1000;
  }
}

class Player{
  //stuff
  ArrayList<PowerUp> modifiers;
  //other stuff
  public void updatePlayer(){
    for(int i = modifiers.size() - 1; i >= 0; i --){
      PowerUp p = modifiers.get(i);
      p.update();
      if(p.timeLeft == 0){
        modifiers.remove(i);
      }
   }
}

```

That should be enough to get across my point
> 0 votes

# Answer
> Should I increase the speed value and then somehow remember to reduce it next turn or should I implement some sort of object which holds modifiers that is checked every turn?

This is the heart of your question and you're really asking, "should I use an object oriented approach?" In general, you're likely to find more advocates than critics of the object-oriented approach, although critics exist.

My suspicion is that if you go with option one (the non-OOP approach), you're going to find yourself with an increasingly convoluted and complicated class, whereas checking status effect modifier objects each turn will lead to much cleaner, more extensible code.

Your players should hold a collection of StatusEffects. StatusEffect can be an object you extend or an interface. (I'm calling them StatusEffect rather than Power-Up, because you mentioned you'd use this for poison too, so it feels like a better name.) In your StatusEffect class you're going to want to put anything that would apply to all of them. totalDuration (number of turns it lasts), currentDuration (how many turns it has been in effect), etc.

Then you'll implement particular StatusEffects, speed-up, poison, etc. You might consider having each statuseffect implement comparable() so you can sort the collection held by the player (i.e., does poison take effect before a healing effect?). Give each effect a applyEffect() method of some sort, where the modifications to the player are applied. Also give them an isExpired() method to see if the currentDuration has reached the totalDuration. When you do a turn, you'll iterate through the effects, apply them, and remove them if necessary.
> 2 votes

---
Tags: game-design, architecture, turn-based
---


# Question
Title: A formula for point calculation based on value A's proximity to value B
I am trying to find a formula to use for my rhythm game's scoring. Basically there is a Guide entity and a Live entity. You control the Live entity and have to match it as closely as possible to a Guide entity in position and radius (both entities are circles drawn on HTML5 canvas).

Guide entities appear automatically and are pre-programmed in an array. For example: a beat trigger is at the 30 second mark in the song. A Guide entity is spawned at 30 - 2 seconds. Over the course of the two "buffer" seconds a visual cue lets the player know when to hit the trigger to spawn a Live entity (so there are two spare seconds for the player to orient themselves before the Live should be spawned). The Guide entity then starts to expand (increasing in radius) based on a pre-built `duration` setting. The player needs to hold down the Live entity key to expand their live entity along with the Guide entity, keeping them as close as possible.

Each Live entity has an attribute called `tempPoints`. When the Live circle is created, its `tempPoints` is set to 100 (the maximum, or "perfect" amount). On initialization of the Live entity (triggered by a key press on the user's side), I calculate the position offset from the Live entity to its matching Guide entity. Eg if `guide.pos.x === 100` and `live.pos.x === 110`, `live.pos.x` is 10% off of `guide.pos.x` and `tempPoints = 100 - 10` (same for `pos.y`)

That is done in the `init` function of the Live entity.

Here is where I'm having trouble:

The closer the Live entity's `radius` is to the Guide entity's `radius` as it expands (and then contracts) the more points the player should keep from their `tempPoints`. I think this would need to be done in the `update` function. The issue is that I don't know what formula to use. I originally did something similar with this as with the position points - calculate the percentage offset of the Live entity's radius from the Guide entity's radius and subtract this offset from the player's points. This would run every single frame and points plummeted into the negative within seconds. I then set up a timer to do this same thing but only run it every `x` seconds (eg 1 or 2), but am running into the same problem. It works in some instances, but seems dodgy because when the Live entity `radius` gets just a little too big or too small the offset becomes huge and removes a whole bunch of points. I've even tried dividing the offset by 10, 20, 50 to remove a smaller number of points, but can never get it to feel quite right. The point subtraction actually seems too minor *until* the offset is just a little too large, in which case it starts to look too drastic.

Is there something like an existing formula for this kind of point system? That is, points based on value A's proximity to value B (in this case the radius of your Live entity and the radius of the Guide entity), with both values continuously changing each frame as the guide and live entities expand and contract?

# Answer
> 2 votes
I've never heard of this sort of abstract concept before so it's hard to imagine there would be an existing formula for it.

I would suggest removing the 'tempPoints' concept which makes it very hard to balance, and separating the process into 2 mathematical functions:

1. Measuring how close the player is to the perfect result.
2. Deciding how many points to award for being that closen.

This will let you tweak each of the 2 parts without needing to recalibrate the other significantly.

It looks like you're tracking 2 measures of quality: the initial position matching, and the radius matching over time. I'd be tempted just to treat them as 2 separate sources of scores, awarding between 0.0 and 0.5 for getting the position right and between 0.0 and 0.5 for matching the radiuses over time. In each case you need to decide just how much error a player can be allowed before they score zero points. Then anywhere between that point and perfection gets a score linearly interpolated between the 2 values. The radius one is slightly more complex because you need to track it over time, but really you can just take the average error over the duration of the entity.

Adding these values together will give you a value between 0.0 and 1.0. You then need to scale that up to award the final points to the player. If you wanted the player to get 100 points for a perfect action then you can multiply the value by 100. So a score of 0.25 on the previous system would yield 25 points. If players routinely were getting too few points then you can perform the scaling differently, eg. subtract it from 1, square it, subtract it from 1 again, then multiply by 100. Here, a score of 0.25 would yield 43.7 points.

If you really need the awarded points to be visible to the player and dropping during each action then you can perform the above calculations frame by frame, assuming zero error for each frame in the future. As each frame passes and the actual error is measured, the score awarded will also decrease until the duration expires.

# Answer
> 1 votes
As Kylotan suggests I would also separate distance computations and scoring over time from point manipulations. Having said that: the point manipulation is something that may require some trial and error.

Pseudocode:

```
// tweak c1
totalScore = initialScore = 100 / (1+c1*distance*distance)

// other options
// initialScore = 100 / (1+abs(c1*distance))
// initialScore = 100 / (1+sqrt(c1*distance))
// initialScore = 100 / sqrt(1+c1*distance*distance)

while time is running and currentScore > 0
   // tweak c2
   factor = 1/(1+c2*distance*distance*)
   // choose functions similar to the approach above

   currentScore *= factor;

```

alternatively

```
while time is running and currentScore > 0
   // tweak c2
   intermediateScore = 1/(1+c2*distance*distance)
   // choose functions similar to the approach above

   currentScore = min(runningScore, average(intermediateScore, currentScore)

```

with average any of the typical mean functions like arithmetic, geometric or harmonic (http://en.wikipedia.org/wiki/Average).

Happy hacking :)

# Answer
> 0 votes
(hooo you there ! welcome :-) i deleted this post before because i was unhappy with it by maybe you can make something out of it, so here it is again. )

If i may, there's a fundamental point missing in your analysis : your game is time-dependant, while your formula is not time dependant.
You need to handle time, both for a right scoring, and to enable your game to work on several devices having differents FPS
(the game framework you use rely, like many others, on requestAnimation frame).

That's why, i think, you get your : ' It works in some instances'.
So the tempPoint you mention is should be relative to the guide duration, and, on each update, you should integrate other time, not doing fixed add/substract that will randomly depends on duration/player accuracy.
So, to integrate, you need the 'dt', the duration of your frame (look for \**.system.tick ) How to integrate ? When i see i'm risking a headacke, i normalize : let us say you have, at each moment in time, a normalized measure of accuracy , 'playAcc' : 0 means player is outside, 1.0 means player is fully on target.
you will have :
so do something like :
\- on a new guide you store guide duration into currGuideDuration, and set currGuidePerfectScore to the value you want the player to win for a perfect (always 100 if i got it well). \- in each update, you :
\- compute normalized accuray : playAcc.
\- currGuideScoreDelta = playAcc * dt / currGuideDuration
\- score += currGuideScoreDelta * currGuidePerfectScore i think it is quite easy to see that with a constant accuracy of 1.0 during currGuideDuration, the score increase will be of currGuidePerfectScore.

(Rq : another way of doing which i find more fun, is to have bouncing and growing current score displayed in the Guide, and then score updated only at the death of the guide, the score also bouncing and growing with more or less hapyness depending on score increase : have a 'currGuideScore' that you increase by currGuidePerfectScore\*currGuideScoreDelta each update, and then only at the end you increase the score by that currGuideScore, having the score bounce with more or less hapinness or like. )

But how to compute the normalized accuracy you would ask ? Kylotan suggest a way, i prefer the normalized measure of the area of intersection of the two circles. But since the formula is a headacke (search google, you'll see...), i would compute an approximation :
1) check if circles are away (distance \> radius1 + radius2) : playAcc = 0.
2) if not, then compute nmaiibbobb : the normalized mean of ( the area of intersection of the inner-bounding box) and (the area of intersection of the outer bounding box) of the two circles. Excuse me for not coding this right now... :-)
Just two tips :
a) : the length of the inner bounding square of a circle is radius/sqrt(2)
since sqrt(2) is a constant, compute it once in init().
b) 'normalizing' means, here, dividing by the Guide's bbbox area. So we can easily see that for perfectly matching circles, nmaiibbobb=1.0. If now Live entity is containing the Guide, only the guide'area will count and, yes, we will have 1.0. The player will loose points (=increase less than he could have) later, when its Live becomes smaller than Guide, and nmaiibbobb \<1.0. So the late player will go haaaaaaaa (joy) then hooooo (sadness) when playing.

I wait your game with impatience !!!

# Answer
> 0 votes
I am unsure if you have completely solved your problem spectralbat but in terms of the mathematical calulation for determining the distance you should use the following process.

1. Define a vector facing from your center point to the point where you have dragged your live entity and determine its magnitude.
2. Define a vector from your center point to the point that you are currently using to define your Guide entity and determine its magnitude.

How close the user is from having the correct radius of a circle (and therefore how close they are from the Guide entity) is simply a subtraction of the two magnitudes.

```
 // this is general pseudocode where abs is an absolute value function
 float DistanceBetween= abs(GuideVector.Magnitude- LiveVector.Magnitude)

```

In addition in determining the points value I would suggest that you create a value r which determines the precision that you want to measure. Often time the physical limitation of a screen will mean that the input may look exactly on the point but in reality it is not (depending upon the width of the line used to draw the circle and the size of the pixel on the screen).

You should also be aware that if you are determining you function for score based upon this distance it would be a smart idea to create a scaling of score rather than a function for the score. If you are using a function similar to this:

```
 Score= ScoreMultiplier (1/DistanceBetween)

```

Then your function can in theory go to infinity if you get within a pixel (in addition if the size of a pixel is the limitation then a different score can be determined based uon the resolution of the screen since the pixel size can be different from one screen to the other). In order to keep your score from having this trend a lot of programmers will create a relationship where they either cap the highest score that can be achieved or to create a table look up that says if you are within this set of distances the score will increase at this value per second.

I hope this helps.

---
Tags: mathematics, javascript
---