# Question
Title: VertexColor shader is not working correctly in built application
I want to change the vertex colors of my mesh. The light sources **must not affect** the objects with this shader, its lighting must be determined **only** by its vertices colors, so I turned the `Lighting Off`. I use this simple shader:

```
Shader "VertexColored/Simple" {
Properties {
    _MainTex ("Base (RGB)", 2D) = "white" {}
}

SubShader {
    Pass {
        ColorMaterial AmbientAndDiffuse
        Lighting Off

        SetTexture [_MainTex] {
            Combine texture * primary
        }
    }
}
Fallback "VertexLit"
}

```

And this script:

```
using UnityEngine;
using System.Collections;

public class BehaviourScript : MonoBehaviour {
    void Start() {
        Color[] exclrs = new Color[11]
        {
            new Color32(25, 25, 25, 255),
            new Color32(50, 50, 50, 255),
            new Color32(75, 75, 75, 255),
            new Color32(150, 150, 150, 255),
            new Color32(200, 200, 200, 255),

            new Color32(255, 255, 255, 255),

            new Color32(200, 200, 200, 255),
            new Color32(150, 150, 150, 255),
            new Color32(75, 75, 75, 75),
            new Color32(50, 50, 50, 255),
            new Color32(25, 25, 25, 255),
        };

        Mesh mesh = GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        Vector3[] normals = mesh.normals;

        Color[] colors = mesh.colors;

        for(int i = 0; i < vertices.Length; i++)
        {
            for(int j = 0; j < 11; j++, i++)
            {
                colors[i] = exclrs[j];
            }
            i--;
        }

        mesh.colors = colors;
    }
}

```

When the game is launched, in editor I can see this:

This is **EXACTLY** what I wanted to achieve!

But in built for PC(x86) version I see this:

Why the results from the editor and from the built .exe differs? What should I do to see my effect in built version? Maybe I need to use an another shader?

# Answer
> 1 votes
`Fallback "VertexLit"` might be hiding an issue with the primary shader, although it looks fine to me. You should probably still remove that line until you know your main shader is working correctly.

My other guesses would be that the mesh colors are not being set for some reason. Are you using the `.sharedMesh` instead of `.mesh` accessor?

There's a lot of trial and error that you could do to simplify the problem, I think.

---
Tags: unity, shaders, lighting
---


# Question
Title: Box2DLights - the center of sprites are always 100% unlit (black) unless Xray is on
I'm using a ConeLight at 180 degrees, with this setup:
`pl = new ConeLight(rayHandler, 256, new Color(0.5f, 0.5f, 0.5f, 1f), 280f, 400 - x, 300 - y, 0, 180);`
And the object I'm casting a shadow on (with?) is set up like so:

```
sprite = new Sprite(new Texture(imgP));

BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(x - 392.5f, y - 292.5f);

body = Main.world.createBody(bodyDef);

PolygonShape pushBlock = new PolygonShape();

pushBlock.setAsBox(((float) w / 2), ((float) h / 2));

FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = pushBlock;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.8f;
fixtureDef.restitution = 0f;

Fixture fixture = body.createFixture(fixtureDef);

body.setUserData(sprite);
body.setGravityScale(0);
body.setFixedRotation(true);
body.setLinearDamping(40f);

pushBlock.dispose();

```

The problem is that the light creates the shadows in a sort of glob form in the center of the square (not casting nicely around the corners as I've seen in others' projects), also leaving nearly the whole sprite black. I require the ambient colour to be black, and also require shadows, so Xray is out. I've messed around with filters but haven't been able to achieve what I want - **being able to cast shadows without overshadowing the sprite.**
Is it possible? How might I do this, if possible?

Edit: I took a screenshot.

# Answer
This needs to be done when you create the Box2DLight's Light object.

You can fix this by setting the setSoftnessLength(float) on the Light object.

For example:

```
m_Light = new ConeLight(...);
m_Light.setSoftnessLength(1.5f);

```
> 1 votes

---
Tags: java, libgdx, box2d, lighting
---


# Question
Title: Can't consistently add to TimeSpan for Unity Game
I'm making a game that has a timer showing how long the player has survived from being crushed by pessimism. (Long story) I'm trying to use TimeSpan in Unity to accomplish this but it seems that I'm having trouble finding a way to add time consistently. My output is always 00:00:01. Here is the code I've been working on. Any help would be appreciated.

```
using UnityEngine;
using System.Collections;
using System;

public class TestScript : MonoBehaviour {

static float timer;
TimeSpan t = TimeSpan.FromSeconds(timer);
TimeSpan add = TimeSpan.FromSeconds(1);

// Update is called once per frame
void Update () {

    TimeSpan span3 = t.Add(add);

    Debug.Log(span3);
}
}

```

*UPDATE*

Thanks for your help Jason, here's the code I made in case anybody else wants to know how to do this. The only beef I have is that the milliseconds show 3 characters instead of two, but I'm personally very satisfied with it. Plus, I'm sure that it is something that could be easily fixed.

```
using System.Collections;
using System;

public class TestScript : MonoBehaviour {

static float timer;

// Update is called once per frame
void Update () {
    timer += Time.deltaTime;
    TimeSpan timeSpan = TimeSpan.FromSeconds(timer);
    string output = String.Format("{0}:{1}:{2}",timeSpan.Minutes,timeSpan.Seconds, timeSpan.Milliseconds);
    Debug.Log(output);
}
}

```

# Answer
> My output is always 00:00:01.

Look at how you initialize your values, though:

* `timer` will default to zero
* `t` will initialize from `timer`, and is therefore also zero
* `add` will default to one second

So we have zero, zero, and one.

In each frame, you create a new `TimeSpan` value by adding `t` and `add`. It's important to note that calling `Add` does not modify either input. Zero plus one is *always* one, so your new timespan is always one second.

If you wanted the time to accumulate, you would need to keep the value of that `Add` operation:

```
t = t.Add(add);

```

Althooough, adding one second per frame will probably cause unexpected results. ;)

As mentioned in comments, most Unity games do this by counting seconds outright, usually using some mix of `Time.deltaTime`, `Time.time`, or `Time.realtimeSinceStartup`.
> 2 votes

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


title: When do you give in-game advice?

text:
# Question
Title: When do you give in-game advice?
I'm interested in the process of automatically generating advice when a player is consistently struggling through parts of a game. Suppose I already know what advice I want to generate (e.g., "Press A twice to double-jump across long gaps"). My question is twofold:

1. Has it been shown that this intervention can be useful to gamer experience?
2. Has it been shown that excessive intervention will be ignored or will cause frustration?

References to game design or psychology research papers is a plus!

# Answer
> 2 votes
I am not aware of any social studies about this. But good rule for happy player is do not force them to do what they dont want to.
As for tutorial type help, many games have a checkbox "stop showing tutorial tips" or something similar on the popup window, and option in game menu to re-enable it later. In Trine there was also an option to show puzzle hints after x minutes stuck on the puzzle.

# Answer
> 1 votes
I like exploring what the controls are without the game taking me by the hand for the first twenty minutes. Take your average (gamer) person and put them in front of a computer to play your game. Do they get stuck somewhere because of a lack of knowledge concerning controls? Then place a hint regarding that there.

---
Tags: game-design, user-experience, psychology
---


# Question
Title: Sever Structure for a Turn Based Game (Chess)
I am working on a Turn-based Game (Chess)

I have done the client part and single player mode so AI is no problem here. But the only problem is now I want to make my project multiplayer. I have done the part to setting and retrieving high-scores and other Informations. Now I am stuck on server structure since I got no idea on which server to use:

**My game Multiplayer structure:**

* User logs in
* Can choose between 3 rooms
* each room got 10 levels (rooms) inside
* game will automatically send each player to a curtain room based on their rank
* players will be assigned to each other and start the game
* each player got 30 secs to make a move otherwise they will lose their turn
* At the end scores will be sent to the DB

**Options suggested by friends:**

* SmartFox
* Google App Engine

**Why not using mentioned servers:**

* some many functions which I will not need (Performance)
* MY project is a small project (self study no need ready servers)
* Need to do it by myself for educational purposes

**Program Languages used:**

* Clint-\> C#
* Server -\> php, SQL

**Questions:**

* is HTTP good enough to handle 500-1000 users at a time?
* can handle this kind of games with WWW and WWWFORM in Unity2D?
* if no any options?

Thanks

# Answer
It is possible to achieve this using an HTTP server since the application won't require frequent messaging. However, the problem with the HTTP is that it cannot send messages to the client unless it requests something. Therefore, you need to send regular requests to receive state updates (such as 'is it my turn', 'piece positions changed?' etc.). Also, you should make sure that the server(computer) will be able to handle 1000 simultaneous requests.
> 1 votes

---
Tags: c#, unity, architecture, server, turn-based
---


title: DirectX UV coordinates are flipped

text:
# Question
Title: DirectX UV coordinates are flipped
I'm loading a simple model, which is composed of vertices that have position, normal and UV texture coordinates.

The thing is, displaying that model using DirectX 9 or 10 shows that the UV coordinates are wrong. In fact, if I manually edit the texture using Paint and flip it vertically, the result is ok.

Is something wrong with my loading routines? Using Visual Studio Graphics Debuggers shows that both the model and the texture are correctly loaded.

Do I have to flip the texture vertically when I load it, or just transform the UV coords with:

```
u = u;
v = 1 - v;

```

Also, as far as I know, OpenGL differs from Direct3D for the UV coordinates system. Would those coordinates be ok with OpenGL without any transformation?

# Answer
Transforming uv coordinates should be good enough. You could do it while loading your model, or even in a shader.
Whether the texture is upside-down in memory is irrelevant for performance when sampling the texture.
> 1 votes

---
Tags: textures, directx
---


title: XNA Texture2D storage question

text:
# Question
Title: XNA Texture2D storage question
Are Texture2D objects stored on the graphics card or on system memory? I am thinking that the backbuffer is located on the graphics card (by default) and that the textures are on the system memory. I am using a spritebatch class that writes the textures to the backbuffer which are then rendered when the Present() function is called. Is this how XNA does it or am I completetly off?

# Answer
Texture2D objects are allocated on system memory, but the actual textures loaded from image files are, on the other hand, loaded on the graphics card's memory.

You are not completely off with your assumption, but here is how it goes when you want to load and render a simple texture:

1. You load the texture into the graphics card's memory.
2. You bind the texture to the current texture unit with glBind / using SpriteBatch.Begin().
3. You render a quad on the back buffer and the graphics card fills the quad's pixels with the texture in the texture unit.
4. When all rendering is done, you swap the back and front buffer. This is done automatically in most high level engines, but you still need to do it in SDL and XNA (Using GraphicsDevice.Present()).

To answer your questions and clarify your misunderstandings:

* Texture are allocated on the memory of the graphics card.
* The back buffer is located on the graphics card too.
* When you call SpriteBatch.Begin(), you don't write the texture to the back buffer, you bind them to the GL\_TEXTURE\_2D texture unit.
* When you draw the texture, it will write to the back buffer.
* The back buffer is completely invisible, so in order to see what you rendered, you need to swap it with the front buffer (the one visible on screen).
> 4 votes

---
Tags: xna-4.0
---


title: Additive blending problems

text:
# Question
Title: Additive blending problems
I'm trying to get the blend of two images to work without luck.

I have a render target on which I have an object, then I want to render again the same object in same position but with different light condition. My goal is to add the result of this two render so I tried to do something like:

```
glEnable(GL_BLEND);
glBlendFunc (GL_ONE , GL_ONE);

....
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
render on render target A
change light condition
do not clear now
render on render target A again with new light condition
glDisable(GL_BLEND);
display render target A

```

I am surely missing something because not only just the first image shows, but the object is transparent.

I am extremely sorry if the question is stupid but I'm very new to such things. Thank you.

**edit** Following the answer of @Sam Johnston I've edited my code but, although I solved the transparency, the results are not added (to make sure of this I render one with a completely red light and one with a green light) together, but I get just the first render as result:

```
glEnable(GL_BLEND);
glBlendFunc (GL_ONE , GL_ZERO);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
render on render target A
change light condition
glBlendFunc (GL_ONE , GL_ONE);
do not clear now
render on render target A again with new light condition
glDisable(GL_BLEND);
display render target A

```

Have I misunderstood the answer?

Juan

# Answer
> 2 votes
On your first pass, you're additively blending your object into the stuff that's already in the render target. Since your object is presumably opaque, you want to make sure the stuff that's in the render target beneath your object is occluded. You could do this by setting your blend mode to glBlendFunc(GL\_ONE, GL\_ZERO) and rendering the object completely black, then proceeding with what you've already written. This will cost an extra rendering pass, and is non ideal.

A better solution, I think, is to render the first lighting pass with glBlendFunc(GL\_ONE, GL\_ZERO) and then all subsequent lighting passes with glBlendFunc(GL\_ONE, GL\_ONE). That way the first lighting pass will stomp anything already in the render target (effectively occluding what's behind the object) and the remaining lighting passes will add their light contribution onto the object the way you expect.

**EDIT:** Regarding the OPs update about only seeing the first rendering pass: make sure you set the depth compare function to something that will allow multiple fragments at the same depth to pass. You must use GL\_LEQUAL or GL\_EQUAL for each pass after the first (assuming your depth buffer is such that 1.0f represents the far plane and 0.0f represents the near plane).

---
Tags: opengl, blending, rendertargets
---


title: Unity - OnDestroy - When is it called?

text:
# Question
Title: Unity - OnDestroy - When is it called?
I was wondering about the method called OnDestroy in Unity (4.5.2f1) on Windows 8.1 Update 1. I know garbage collection in C# in non-deterministic, so I was wondering if game objects had OnDestroy called the moment I called Destroy on them, or when the garbage collector was invoked?

If this is not the case, what are my alternatives? I could of course just call a method inside of the object to be destroyed just before I invoke destroy, but there may be a more elegant solution available that I don't know about.

Note: I did try checking this myself, but being non-deterministic I may not be able to rely on that behavior occurring every time.

# Answer
> 4 votes
`Destroy();` is an explicit command to remove the object from the game scene immediately\* or after a set time increment. As soon as you call it - the item is destroyed in context of the scene.

Garbage collection will take it as soon as there are no more  when it is ready assuming there are no more hard references to that item. However, this is not controllable in Unity without calling the GC system object.

Unity3D - Object.Destroy()

*** clarification - immediately meaning in that frame. After the Update loop the item is destroyed, it will always be done before rendering**

# Answer
> 2 votes
Some clarifications.

**Only memory allocated by scripts** is managed and can be garbage collected. So if you destroy a GameObject the attached script can be eventually collected, but the life time of resources allocated from the C++ side of the engine is managed in a different way.

**You can force a garbage collection** explicitely call GC.Collect. If you don't force it, it's up to garbage collector decide when free the memory with zero ref count.

For what concern GameObject.DestroyImmediate I cite the doc:

> This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead. Destroy is always delayed (but executed within the same frame).

I think the main reasons for that are 2:

1. Other objects may try to access the deleted object within the same frame, so it's better to let it leave until all Update functions have been called.
2. From a memory management point of view it could be convenient to handle allocations/deallocations in specific moment.

**Despite you destroy or destroy immediate an object, the used resources aren't necessary unallocated immediately.**

Just an example, suppose your destroyed `GameObject` has a `Material` referencing a `Texture`, even if that resource is used only by the destroyed object, it's still up to unity decides when deallocate the relative memory. If you want to force the release of unused resources you can have a look at Resources.UnloadUnusedAssets.

---

EDIT

As DarioOO pointed out, Unity overrides the comparison operator, in such a way that when an object has been destroyed all C# references to it are null (even if the related resources aren't still been released).

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


title: Move an object up while touch is active

text:
# Question
Title: Move an object up while touch is active
I'm trying to move an object towards the top of the screen while the touch is active. This is my current code. When I am touching the screen, the object I'm trying to move just keeps it's place (and the gravity seems to be disabled from this point). I'd be glad if someone could help me in this case. Thanks in advance!

```
public class PlayerScript : MonoBehaviour
{

public Vector2 jumpForce = new Vector2(0, 12);
public int speed = 3;

void Update()
{
    for (int i = 0; i < Input.touchCount; i++) {
                    Touch touch = Input.GetTouch (i);
                    while(touch.phase == TouchPhase.Began) {
                            // Touch are screens location. Convert to world
                                rigidbody2D.velocity = new Vector2(0, speed);
                                rigidbody2D.AddForce(jumpForce);
                    }

            }
     }
 }

```

# Answer
The code you've posted is only checking for touches that began on this frame. If all you want is to verify that any touch is present, you can just check if `Input.touchCount` is greater than zero.
> 1 votes

---
Tags: 2d, unity, android, mobile
---


# Question
Title: XAudio2: how to convert seconds to samples
in the Xaudio2 API you can specify the start and endposition only in samples.

but i require them to be set by seconds.

now i am looking for a way to convert seconds into samples but havent found much information on how to do that so far.

any help on this is highly appreciated!

# Answer
When you created your mastering voice, you set the input sample rate. This number is the amount of samples per second.

Multiply the time you want to seek to by the sample rate, and you get the sample you want to seek to.

For example, if the sample rate is 44100, and you want to seek to second 20.4, the sample you want to seek to is

```
44100 * 20.4 = 899640

```

Check the reference for CreateMasteringVoice for more information

There's also some more information regarding Sample Rate Conversions in XAudio2.
> 2 votes

# Answer
Here's a function that converts samples to milliseconds (which avoids the need to use floating point)

```
size_t SoundEffect::GetSampleDurationMS() const
{
    if ( !pImpl->mWaveFormat || !pImpl->mWaveFormat->nSamplesPerSec )
        return 0;

    uint64_t samples = GetSampleDuration();
    return static_cast<size_t>( ( samples * 1000 ) / pImpl->mWaveFormat->nSamplesPerSec );
}

```

Here `pImpl->mWaveFormat` is a `const WAVEFORMATEX*`

`GetSampleDuration()` returns the duration of a wave in samples, which is actually a little tricky for formats other than PCM:

```
size_t SoundEffect::GetSampleDuration() const
{
    if ( !pImpl->mWaveFormat || !pImpl->mWaveFormat->nChannels )
        return 0;

    switch( GetFormatTag( pImpl->mWaveFormat ) )
    {
    case WAVE_FORMAT_ADPCM:
        {
            auto adpcmFmt = reinterpret_cast<const ADPCMWAVEFORMAT*>( pImpl->mWaveFormat );

            uint64_t duration = uint64_t( pImpl->mAudioBytes / adpcmFmt->wfx.nBlockAlign ) * adpcmFmt->wSamplesPerBlock;
            int partial = pImpl->mAudioBytes % adpcmFmt->wfx.nBlockAlign;
            if ( partial )
            {
                if ( partial >= ( 7 * adpcmFmt->wfx.nChannels ) )
                    duration += ( partial * 2 / adpcmFmt->wfx.nChannels - 12 );
            }
            return static_cast<size_t>( duration );
        }

#if defined(_XBOX_ONE) || (_WIN32_WINNT < _WIN32_WINNT_WIN8)

    case WAVE_FORMAT_WMAUDIO2:
    case WAVE_FORMAT_WMAUDIO3:
        if ( pImpl->mSeekTable && pImpl->mSeekCount > 0 )
        {
            return pImpl->mSeekTable[ pImpl->mSeekCount - 1 ] / uint32_t( 2 * pImpl->mWaveFormat->nChannels );
        }
        break;

#endif

#if defined(_XBOX_ONE) && defined(_TITLE)

    case WAVE_FORMAT_XMA2:
        return reinterpret_cast<const XMA2WAVEFORMATEX*>( pImpl->mWaveFormat )->SamplesEncoded;

#endif

    default:
        if ( pImpl->mWaveFormat->wBitsPerSample > 0 )
        {
            return static_cast<size_t>( ( uint64_t( pImpl->mAudioBytes ) * 8 )
                                        / uint64_t( pImpl->mWaveFormat->wBitsPerSample * pImpl->mWaveFormat->nChannels ) );
        }
    }

    return 0;
}

```

`GetFormatTag()` is a helper that handles both WAVEFORMATEX and WAVEFORMATEXTENSIBLE formats.

```
inline uint32_t GetFormatTag( const WAVEFORMATEX* wfx )
{
    if ( wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE )
    {
        if ( wfx->cbSize < ( sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) ) )
            return 0;

        static const GUID s_wfexBase = {0x00000000, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71};

        auto wfex = reinterpret_cast<const WAVEFORMATEXTENSIBLE*>( wfx );

        if ( memcmp( reinterpret_cast<const BYTE*>(&wfex->SubFormat) + sizeof(DWORD),
                     reinterpret_cast<const BYTE*>(&s_wfexBase) + sizeof(DWORD), sizeof(GUID) - sizeof(DWORD) ) != 0 )
        {
            return 0;
        }

        return wfex->SubFormat.Data1;
    }
    else
    {
        return wfx->wFormatTag;
    }
}

```

All code snippets are from DirectXTK for Audio.
> 0 votes

---
Tags: xaudio2
---


title: Stats for testing a renderer

text:
# Question
Title: Stats for testing a renderer
I've been writing an OpenGL renderer as a learning process for the past few weeks. Now I wanted to test my renderer against some known numbers, for instance:

* How many vertices/tris should it be able to render at 60 fps (rough estimate?)
* How many draw calls before it is expected to drops the fps?
* etc?

This is all assuming simple shaders (one that outputs a single texture) and a reasonable video card (3~4 yrs old).

# Answer
Following wondra's advice, I decided to check some engines, this is what I found:

**Unity 3D** (http://docs.unity3d.com/Manual/OptimizingGraphicsPerformance.html)

* Draw Calls: "several thousand" (PC) and "several hundred" (Mobile)
* Vertices: "not more than a 100 thousand" (Mobile) and "not more than several million" (PC)

**jMonkeyEngine** (http://hub.jmonkeyengine.org/forum/topic/a-polygon-limit/)

* Vertices (Developer answer): " if you want \[...\] to run on low hardwares \[...\] shouldn’t have more that 100k polygons" (PC), "30k poly" (Android)
* Triangles (User): Renders 5m triangles at 200 fps

**Torque 3D** (http://www.garagegames.com/community/forums/viewthread/134244)

* Vertices: Around 3 million.

---

To be honest it was a bit hard to find even this information, I couldn't find anything for Ogre3D or UDK. Even what I found is always surounded by "it depends". So I guess the final answer really is "it depends" but 5m vertices/500 draw calls sound like reasonable numbers to aim for.

I'm leaving the question open because someone else might have better input than this.
> 1 votes

---
Tags: metrics
---


# Question
Title: Resources for designing (not programming) 2D platformer mechanics
I've been making a 2D platformer in Unity and it's been going great. I have the fundamentals down (and as an experienced programmer, I know how to get the results I want; this is not a programming question.)

I've been floundering, though, because I realize that I lack vision in terms of a game direction. I originally wanted to make a Metroidvania-style game, but decided to scale back as I thought that would be too ambitious (and take too long) for my first game. As such, I've decided to create a platformer/run-and-gun type game.

I've played enough platformers to know and intrinsically understand basic mechanics, but I also realize that the best games have a core mechanic that defines the game. Megaman's core mechanic, for instance, is obtaining and using boss weapons and abilities; boss battles and levels are built around this. Metal Slug revolves around weapon pickups and its tank gameplay.

I guess I'm at the point where I have a code demo....but it's not a game; it has no soul. I've basically just proven to myself that I can write a platformer game in Unity.

I want to know of any good resources on aspects of video game mechanic design not centered around programming - book recommendations would be amazing, but online resources or other types of resources would be great as well. (Worth noting that I'm not looking for guides on designing levels, but lower-level mechanics, like jump height, hp limits, core mechanics to define a game, etc.)

# Answer
> 2 votes
One of the best resources for mechanical design is pen and paper. Everything that happens on a computer happens one step at a time, which means you *can* prototype just about any part of your game using paper.

As for what's best (you mentioned jump height), it's really a question of what's best for your game, so the best way to figure it out is to play with it. That's where paper helps, as you can reiterate quickly and not worry about implementation. Aside from paper, you could set mechanic-specific variables (such as jump height) as public, as long as they are implemented this allows quick iteration by changing the variable in Unity's inspector.

When you're thinking about a hook mechanic for your game, remember it can be pretty much anything, as long as you actually include it in the game! Think of Mario - personally I'd say the main mechanic there is jumping:

* Enemies are defeated by jumping
* Levels are traversed by jumping
* Puzzles are solved by jumping
* Power-ups affect jumping (even the fireball cuts down enemies so you can focus on jumping)
* ... Jumping

You could however design pretty much any type of game around any mechanic (that doesn't mean it's going to be a killer game). How about a platformer based around acrobatics? Strip out the combat and that's pretty much Prince of Persia. Or a platformer based around environmental manipulation (Gravity Guy is a great example of that). Say you wanted to do Gravity Guy, you could still keep run-'n'-gun, just like Mario has Goombas but the main thing you're doing to get around a level would be flipping.

Finally, one of the best books I could ever recommend on game design is David Perry on Game Design as I find it's pretty much just a massive toolbox.

---
Tags: game-design, game-mechanics
---


title: How to show a float with no decimals

text:
# Question
Title: How to show a float with no decimals
I want to show the current health and stamina of the player using GUI.Label. All is working fine however it shows the values with decimals to the millionth (example: http://gfycat.com/SkeletalSinfulKouprey). How would I go about showing only the whole number?

My code:

```
 var cur_stamina : float;
    var cur_health : float;

    var staminaRegenRate : float = 5;
    var healthRegenRate : float = 1;

    //regen
    if(cur_stamina < max_stamina){
        cur_stamina += staminaRegenRate * Time.deltaTime;
    }
    if(cur_health < max_health){
        cur_health += healthRegenRate * Time.deltaTime;
    }

    function OnGUI(){
        GUI.Label(Rect(1,1,100,20), "Health: " +cur_health);
        GUI.Label(Rect(1,15,1000,20), "Stamina: " +cur_stamina);
        GUI.Label(Rect(1,30,100,20), "Ammo: " +cur_ammo);
    }

```

# Answer
> 6 votes
Don't forget that every object in .NET has a `ToString()` method. Many of the built-in value types accept an optional formatting argument; numeric types in particular are easy to format with standard formatting or custom formatting.

For example, instead of just passing `cur_health`, you could pass `cur_health.ToString("n0")`.

For the specific question, you could also truncate using Mathf.FloorToInt.

# Answer
> 0 votes
You could use a bitwise OR to just truncate:

```
GUI.Label(Rect(1,1,100,20), "Health: " +cur_health | 0);

```

Or, if you care about accuracy, you can use Unity's API to round it:

```
GUI.Label(Rect(1,1,100,20), "Health: " Mathf.Round(+cur_health));

```

---
Tags: unity, javascript, gui
---


# Question
Title: Tweaking incentives for lottery with a twist
I have been developing a game which is a lottery where your chance of winning is proportional to the square of your bet.

To prevent people from overbetting the pot (optimal strategy shouldn't just be to bet as much as possible, I think), and to make subsequent jackpots appealing, I've made it so the winner gets (current round bets + past round leftovers) / 2. 48% of the jackpot goes forward, and 2% of the jackpot goes to the house.

This is generally working, but when there are not many people on the site, one person will sit there and drain the pot every round with the minimum bet.

Though I think the concept is pretty cool, I have the feeling that some small tweaks could make a big difference.

Any ideas how to get the pot to grow as big as possible?

Apologies if this is not the right place to post.

# Answer
> 1 votes
I feel this question is more marketing related instead dev. You seem to have figured out a nice setup but are lacking players.

get your community growing, and dont allow games with to few people i guess.

# Answer
> 0 votes
1. Set a minimum number of players

The more players in any game, the bigger the prize for that and subsequent games
2. Raise the minimum stakes

That one should speak for itself (you wanted a bigger jackpot)

---
Tags: game-design
---


# Question
Title: Fullscreen triangle SV_POSITION and deferred shading
So I'm trying deferred shading in DirectX11.

I am using the following method (used in the FXAA shader and described here: http://www.altdev.co/2011/08/08/interesting-vertex-shader-trick/) to render a fullscreen triangle for my deferred shading pass.

```
FullscreenTriangleVSOut main(uint VertexID: SV_VertexID)
{
    FullscreenTriangleVSOut output;

    output.mTexcoord = float2((VertexID << 1) & 2, VertexID & 2);
    output.mPosition = float4(output.mTexcoord * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);

    return output;
}

```

And then in the pixel shader, I want a proper texture coordinate to sample my diffuse, normal, position textures from the GBuffer.

In GLSL, I simply do:

```
ivec2 texcoord = ivec2(textureSize(unifDiffuseTexture) * (gl_FragCoord.xy / UnifAmbientPass.mScreenSize));

```

But for some reason, in HLSL my SV\_POSITION is always (0.5, 0.5). I looked in visual studio 2013 and debugged the pixel shader at various pixels, and yes at all places the SV\_POSITION is (0.5, 0.5). Why is this?

# Answer
You can't use SV\_Position for this in hlsl, you should get the position from an other output slot without the SV\_Position semantic instead.

```
output.mPosition = float4(output.mTexcoord * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);
output.mNewPos = output.mPosition; //use mNewPos in the pixel shader

```

SV\_Position is just for the rasterizer.
> 0 votes

---
Tags: directx, hlsl, directx11
---


# Question
Title: Still award achievements/badges on failing level?
I've got a simulation game where the player works through a series of missions/levels.

The player also earns in-level badges as he works through.

But, if the player fails a mission (and has to restart it), should the badges still be awarded? Or should badges only be retained on successfully completing the parent mission?

Your thoughts are welcome.

# Answer
I have been trying to find any source online that states it explicitly with no luck. If you award players with achievements as soon as the criteria is unlocked, then you can play around with the actual criteria to make for more or less flexible achievements.

For instance, is not the same "Burn 10 enemies to death" to "Complete the level burning 10 enemies to death". Also other achievements, in nature, require players to complete the whole mission, such as "Complete the level without getting hit".

In any case bear in mind that achievement hunters will take the most efficient way to get an achievement. For the burning enemies example, in the first case they will leave the level as soon as they meet their objective, which of course is much less challenging that having to complete the entire level, but at the same time is less frustrating.

Just to give you an idea, here are two examples that work different ways.

I have played some platformer and FPS games where secrets which are scattered through levels are awarded as soon as found, independently of finishing the level or not. This is pretty handy as you can play the entire level just once for completion, and then replay it several times to find the hidden secrets. This makes less boring and frustrating having to play the same missions again and again, as you only explore parts of the level you didn't before.

On the other hand, Starcraft II has level specific achievements that always require you to complete the level. This makes the system more challenging as you need to complete the level AND meet a certain criteria for the achievement, but is also more rewarding as probably it would be too easy otherwise.

In any case I recommend you to read this achievement guide by Greg from Kongregate, and decide which model suits better your game (replaying levels again and again will be fun or will feel like a dull chore?).
> 3 votes

# Answer
Sometimes players only rerun a mission because of the achievements, even if they just do a suicide mission.

You could just award them, in real-time, even if the mission is not completed in the end.

Or you could, for the first run, need to complete the mission first, and only after repeating the mission you could win the achievements without needing to complete it.
> 0 votes

---
Tags: levels, achievements
---


# Question
Title: Looking for a full featured C/C++ UV Mesh Unwrapper
My first question! Is there an open source C++/C piece of code easy to integrate to solve the UV Unwrapping of arbitrary meshes out there ? I would like to use it to build a light mapper or similar stuff. Of course i'm looking for non-naive solutions but something that solves the issue with maximum exploiting of texture surface and so on..

Thank you guys in advance.

# Answer
Well, i'd probably start by taking a look at the blender unwrapping code, since blender is some open souce flavor; it appears to start here:

https://developer.blender.org/diffusion/B/browse/master/source/blender/editors/uvedit/uvedit\_unwrap\_ops.c

I know the have a "pack lightmaps" command in their uv unwrap menu, but I wasn't able to locate it in unknown code in a short time on my phone :3

Good luck.
> 1 votes

---
Tags: c++, textures, 3d-meshes, uv-mapping
---


# Question
Title: What parts of a GPL game engine must be released?
I'm hoping I can clarify this issue.

Note, a similar question has been asked here, but it doesn't really give a specific enough answer that I can comprehend at this point! :- How does one escape the GPL?

I plan to use a game engine that has been released under GPL to develop a MMOG, and I plan to distribute the client for free. I'm concerned that when it comes time to release my game, I'm going to have to release the entire source code under GPL, which opens my game to risk of abuse, where someone can learn how to potentially hack my game client and give them an unfair advantage etc.

If I understand GPL, I only need to distribute code that I've edited directly. In the case of Java, I can extend the available classes, do to what I need them to do, rather than go back and make edits in the classes themselves. If i'm using the original code in this way, do I just need to point out that the code is available from the engine developers

Does extending a class constitute 'editing the source?'

# Answer
> 3 votes
jMonkeyEngine is licensed under the **3-clause BSD** license, **not** under the GPL. The BSD license explicitly allows closed-source modifications, as long as you just include the BSD license text somewhere where the end-user can read it. That means what you want to do is no problem at all.

However, when the engine *were* licensed under GPL, your new client would be a derivate work of the GPL code which means that it would have to be released under the same license terms. That's why the GPL is rarely used for game engines. It's far more common to see the LGPL in this case, which allows to use the LGPL-based work as an open-sourced library in a closed-source project.

---
Tags: java, licensing
---


title: Android Game Slows Down

text:
# Question
Title: Android Game Slows Down
I had been developing a **Maze Game** which is dragging a bitmap down on the maze going on the finish line. on first my game response quickly on my onTouch and dragging and after couples of **adding toast message, generate random mazes, changing character from drawCircle into a bitmap and a background from a solid color into a customize PNG file** my game seems to **Slows Down**.

Can anyone explain why could this happen?

And what should I do to make my game to response more quickly?

Tnx for the help and godbless.

**UPDATE**: I found out that it all started when i change my solid color background to a bitmap background.

here's my code:

From this:

```
protected void onDraw(Canvas canvas)
canvas.drawRect(0, 0, width, height, background);

```

To this:

```
protected void onDraw(Canvas canvas) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.menu_bg);
//Set Rectangle Size and Coordinates
RectF rect = new RectF(0,0,width,height);
//Maze with Background
canvas.drawBitmap(bitmap, null, rect, null);

```

# Answer
On of the major reason your code is slow is because you load your bitmap every time you render your game. Try putting this line in an initialization function:

```
...
Bitmap bitmap;

protected void init() {
    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.menu_bg);
}

...

protected void onDraw() {
    //Set Rectangle Size and Coordinates
    RectF rect = new RectF(0,0,width,height);
    //Maze with Background
    canvas.drawBitmap(bitmap, null, rect, null);
}

```

If you could post your entire code, I could tell you exactly where to put this line, but your engine should have something like a constructor or an init() function.
> 2 votes

---
Tags: android, graphics, eclipse
---


title: Find world matrix

text:
# Question
Title: Find world matrix
I'm making my first 3D-game with XNA (MonoGame) and have come to a point where I wish to add a crosshair for the player. To do this I need the on-screen coordinates of the location where my fighter would actually fire. However, I've run into some problems with this, mainly in finding my world matrix...

When drawing, I use the following snippet:

```
foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();

                effect.World = transforms[mesh.ParentBone.Index]
                     * Matrix.CreateRotationX(angle.X)
                     * Matrix.CreateRotationY(angle.Y)
                     * Matrix.CreateRotationZ(angle.Z)
                     * Matrix.CreateTranslation(Position);

                effect.View = camera.ViewMatrix;

                effect.Projection = camera.Projection;
            }
            mesh.Draw();
        }

```

My understanding is that to be able to get my 2D screen coordinates, I need to use something like this:

```
//Yes, this currently returns a Vector3 and probably looks horrible on line 2 but I have not yet had any ouput to test this with
Vector3 temp = Game1.game.GraphicsDevice.Viewport.Unproject(Fighter.player.Position + Fighter.player.Forward * 50, Camera3D.camera.Projection, Camera3D.camera.ViewMatrix, Matrix.Identity);
Position = new Vector2(temp.X, temp.Y);

```

Which requires the world transform as the final argument. Since my effect.world changes with each BasicEffect (7 of them) I can't really get a hold on what my World Matrix is.

Any help?

**EDIT**

In my case I was able to use the code I used above with the only change that instead of Viewport.Unproject I used Viewport.Project.

I'm still not sure how to get the world matrix when it's set with variables that can vary (such as transforms\[mesh.ParentBone.Index\]) and am still intrested in this. My specific problem however was solvable by simply using Matrix.Identity as world matrix.

# Answer
> 0 votes
To get 2d screen coordinates from a 3d world space location, you would use `Viewport.Project`, not `Viewport.Unproject`.

The world matrix to put in the `Project` method would be the same one you use to set the `effect.World` property for rendering.

---
Tags: c#, 3d, xna-4.0, matrix, monogame
---


title: AI shooting through walls

text:
# Question
Title: AI shooting through walls
I made a AI shooting script for my new game but the problem is that the AI ignores the walls and shoots through walls. This is my ai script :

```
#pragma strict

public var rocketPrefab : Transform;
public var barrelEnd : Transform;
var canShoot : boolean = true;
var shootRate : float;
var gun : Transform;
var soundEffect : AudioClip;
var player : Transform;
var enemy : Transform;
var minShoot : float = 2;
var maxShoot : float = 4;

function Start ()
{

    e();
    canShoot = true;
}

function Update ()
{
    transform.LookAt(player);
    if(canShoot==true)
    {
        Shoot();
    }
}

function e()
{
    canShoot=false;
    yield WaitForSeconds(Random.Range(1, 2));
    canShoot=true;
}

function w()
{
    canShoot=false;
    yield WaitForSeconds(Random.Range(minShoot,maxShoot));
    canShoot=true;
}

function Shoot ()
{
        var rocketInstance : Transform;
        rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation);
        w();
        audio.PlayOneShot(soundEffect);
}

```

Some help would be awsome! Thank you for your time.

# Answer
> 1 votes
You should write a method that checks the visibility.

It follows the definition:

http://en.wikipedia.org/wiki/Visibility\_%28geometry%29

There are a lot of techniques to do that. Therefore, I reccomend you searching on the web which approach would fit best in your problem.

# Answer
> 1 votes
You should use raycasting to check for visibility. Each raycast is expensive, so stagger the visibility checks for different enemies (they don't all have to see the player on the same frame)

---
Tags: unity, collision-detection, ai, raycasting, unityscript
---


# Question
Title: Best way to read expandable voxel world (hashmap) such as in Minecraft
I'm building a 3D multiplayer Roguelike-style engine (tile and turn-based) and I'd like to make the worlds virtually "infinite", similar to what you would see in Minecraft.

I'm storing data in a manner I'm assuming to be pretty similar to Minecraft based on what I've read so far. Chunks of 16x16x16, stored in arrays that are X amount high based on world height. These arrays are stored in a hashmap indexed as integers based on a z-order / morton curve implementation (to flatten them from 2d for easier storage.)

Everything is working well so far, but I've been coding everything assuming the active world will all fit into one square (based on view distance or something along those lines) instead of multiple areas (difference illustrated here).

But once I start assuming different areas will be loaded and active in the world, it brings a huge performance issue: **in order to check individual cubes I'd have to see if it's parent chunk is active and loaded in order to avoid some kind of null pointer exception.**

Aside from trying to somehow do pathfinding / world interaction in batches within individual chunks (which would be really hard to think around and I'm trying to just grab individual cubes from the "world" object that handles navigating the hash map) I can't think of any way around the issue except doing a hashMap.containsKey(int) for every single world read operation. So, in other words, if 8 players are on the server in entirely different active areas in the world, every block read would require checking if the Morton Code of the chunk the requested block is in falls into the currently loaded area of Players * Active Area, so 8\*(8\*8) individual chunks in this example.

So I'm curious if my Hashmap-based setup is incorrect for solving this problem, or if there is any other way around this issue.

# Answer
You can use a "default" chunk. Wrap your hash map accessor so if if `getReadOnlyChunk` is called on a key that doesn't exist then instead of returning null it returns the cached instance of `DefaultChunk`, which is either empty or full of a special "impassible mist" block or whatever you deem to be best for your game. The `getWritableChunk` method should instantiate a chunk with whatever generation algorithm you use. Or have a single `getChunk` that returns a "read-only view" of a chunk which can be converted writable. Or just check if you have the `DefaultChunk` before writing.

Short version: don't return null, return a place-holder.
> 2 votes

# Answer
I've got three comments:

* Pathfinding, etc, should be tree-aware
* Checking to see if a block is loaded is cake
* The client and server will handle unloaded data differently

## Tree Aware

You've mentioned that you're storing data in 16x16x16 chunks. Pathfinding and world interaction should operate on those chunks (in addition to their contained blocks). For example, pathfinding starts with "hey world, gimme the chunk that this block is in" but, from there, should proceed along the lines of "does the path terminate in this chunk? If not, what's the next chunk?" You should only go to the hashmap for chunks, not for individual blocks. Once you have a chunk, you should be able to operate within it without having to go back to the hashmap.

You mention this sort of solution in your post. Yes, it's hard. The alternative is, yes, hitting the world hashmap for *every single block read*. (Note that a chunk *already* provides locality of data.)

## Is this block loaded?

Converting a block's coordinates into its Morton index should be a trivial computation. Then, checking to see if that chunk is in the currently-loaded hashmap is, generally

```
bool hashmap::contains_key(T& key)

```

or some similar computation of typically trivial order, O(1) or O(log n). There's no reason to iterate over all of the loaded areas and to check to see if the chunk is in any of those areas; just ask the hashmap. They're very fast at that sort of test.

If your pathfinding (etc) code works on chunks, then you don't need to keep doing the "is this block loaded?" test for every single block. Do it once for the chunk, pathfind through the chunk, then do the test for the next chunk.

## Handling Unloaded Data

Pathfinding (for e.g. AI) should probably only attempt to run within loaded areas; that is, it should be clipped to the currently-loaded regions that you mention in your Question. Sometimes mobs will be confused; the alternative is loading more data. You'll have to choose where this tradeoff happens. Hence, pathfinding itself should never run into this null exception error.

All active areas of your would should be in memory at any given time. This is more dependent on the number of players in the game and how large of an active area each player induces than it is on the size of the world. When your server needs to process "the player is attempting to move North by one tile", you don't want to go "oh, oops, I completely forgot to load that." Plus there's no reason to even check to see if the chunk is loaded if the player isn't moving out of the current chunk.

The server should always have data available. If the player is teleported to a new region of the map, many AAA titles will lag the player until the server is done loading the new player-local region. In other words, a player steps into the portal and then sees a loading or waiting screen until the server has caught up; on the server side, it's waiting for IO to complete loading new chunks.

On the client side, sadly, sometimes network traffic happens. The player wants to do something which would cause client-side computation with blocks in a chunk that the server hasn't yet told the client about. The basic solutions here: (1) lag the player, ie prevent them from moving until relevant data is loaded; (2) fake it, perhaps by adding in "impassible mist" as Sean suggested; or (3) discard the player request. Again, you'll have to decide which solution best fits your game.
> 1 votes

---
Tags: java, minecraft-modding, voxels
---


# Question
Title: How was/is playback of music handled on consoles such as the NES, Master System, Gameboy, etc?
So, I deliberately left out the SNES because AFAIK the music subsystem is basically entirely self-contained. However, on systems like the NES and Gameboy, while there are sound chips, there isn't any sort of dedicated sound CPU.

My question is how one reliably plays back music without putting too much of a burden on the CPU? Timing is clearly very critical: music won't sound right if the notes aren't played at exact intervals. Naively, one might just continually update the registers of the sound chip. However, this leaves no time for programming game logic! You could plan to update the registers every cycle in the main loop, but then any interrupts triggered would throw everything off.

I haven't been able to find any information on this, despite there seeming to be a clear conceptual gap! So basically, how does a game like say, Super Mario Bros on the NES manage to play back music consistently and reliably, regardless of what is happening on screen?

# Answer
> 0 votes
Oh, I got you. But then that made you think that CPU alone is not enough to handle sound? It's rather primitive, well, it's definetely not a PC-speaker, but not too far from it. 22 mapped register WORDs is a *complete* configuration of a NES APU. It also includes basic caps for cycles and frequency generation, so it's not all on CPU every cycle.

But generally, I guess, this was just a hardware limit which was unawoidable for developers, they have no other options but to reserve CPU power for sound processing.

---
Tags: software-engineering, music
---


# Question
Title: How is shot synchronization implemented in multiplayer FPS?
I'm building a 2D multiplayer shooter game. I have singleplayer working and started working on multiplayer part (server code,...) and there is one thing I just can't get my head around.

When player shoots someone, who is moving, and he has high latency (\>200ms or something like that) how to synchronize it with the other client? I thought that the shot vector could be sent relatively to targeted player (so when he would recieve the info about the shot, he could animate the shot hitting him).

Problem is, shots can destroy enviroment or hit other players. So when I shoot a target and there aren't any obstacles, he gets hit and the packet about shot hitting him gets sent. 200ms (+ other player latency) later, other player recieves the packet, but in that time, he moved behind an obstacle.

Problem rises:

a) If the obstacle is destroyable by the shot, clients will have different map (shooting player will have map with obstacle, while the other player will have the obstacle destroyed)

b) If the obstacle can't be destroyed, other player will either complain, because he got shot through impenetrable obstacle or the shot will be shot, so shooter will think that target got hit and target won't see any hit.

I just can't find a better way to solve this. Any ideas or examples how other games did it?

# Answer
When dealing with different frames of reference interacting with each other instantaneously, you have to compromise somewhere, you cannot have everything consistent everywhere; that's a fact of life. The scenario you have outlined is basically this: **the shooter** thinks she has hit her target, but **the target** thinks she has successfully hidden behind an obstacle.

Who is right? That's for you to decide, but I'd argue that games that emphasise shooting - with fast projectiles - should favour the shooter, whereas games that emphasise moving and evading - with slow projectiles - should favour the target. (You could of course do both in one game depending on factors such as the speed of projectiles.)

* If you **favour the shooter**, then you can give instant feedback to the shooter on whether she has hit or missed, but the target's feedback on whether she was hit or not will be delayed.
* If you **favour the target**, then the reverse is true.

In practice this tends to end up in the shooter's favour, as most FPS games have fast projectile weapons that require instant feedback for shooters, but keep in mind that anything you decide will be a compromise. Also, contrary to many gamers' complaints, it is the *sum of latencies* between shooter and target that determines the severity of the compromise, and in one-on-one encounters there is no inherent advantage to either player - both players experience the same degraded gameplay, irrespective of their individual latencies to the server.

Here are some general strategies and examples (the Gaffer on games article expands on some of these concepts):

**Server authority** (listed in the article as *Client/Server*): this is where the server is the ultimate authoritative frame of reference for everything, including whether one player has hit another. This was common in the early days of internet FPS games, when titles like Quake were most popular. This disadvantaged all players for the sake of the game, and disadvantaged high-latency players more, as no action begins until the server hears about it. For twitch-shooters such as Quake this was acceptable, as one needed a low latency to get the best experience anyway. The downside was that even modest amounts of latency - 100-150ms - was noticeable for human players, and they had to compensate by aiming ahead and so on.

**Client-side Prediction**: often goes hand-in-hand with latency compensation, this is where the client is the authoritative frame of reference (either the shooter or the target, as I mentioned), and the server maintains a buffer of previous state in order to validate the client's prediction. Games using this architecture became common in the early 2000's, especially for "realistic" shooters using fast projectile weapons such as Counter Strike.

**Latency caps**: to mitigate the harmful effects introduced with client-side prediction, many games and server admins chose to disallow high-latency players from playing. This ensures that the experience is consistent for the low-latency players. Although this seems harsh, with the spread of broadband internet and matchmaking services, the pain can be reduced.

**Latency-capped client-side prediction**: this is the same as client-side prediction, but where the compensation is limited up to a maximum latency. Any players above this threshold will only have their latency compensated up to that threshold, no more. This threshold should suit the nature of the game, but 200ms sounds like a good compromise. This means that for players with latencies below the 200ms, it's identical to normal client-side prediction, except it feels like no one has a latency any greater than 200ms. For players with latencies above the threshold however, it feels like a server authority game where everyone else has a latency of 0 but they have a latency of X - 200ms. I'm not aware of any games that do this but I'd be surprised if this has never been attempted before.
> 8 votes

---
Tags: multiplayer, first-person-shooter
---


# Question
Title: why am I being unable to access public array of a class inside other class?
I know this question has been asked before but my case is different(or i could not gather any kind of help from those)

I am facing "NullReferenceException: Object reference not set to an instance of an object" Error

in Class 1 I tried to make an array of a Class2 type and that class2 had two arrays of type "int"

but when i am filling up values in those arrays of Class2, by making object of Class2. it seems to be null.

well right now its not a problem but when i will use those value in other place it will create one. so i would really like to solve this right now.

PS:- At first I used to fill those value by inspector plane in unity. but now i want to fill them up by programatically at runtime

**Class1 Code**

```
public class LevelStructure : MonoBehaviour
{
public static LevelStructure instance;

public int numberOfColumns=5;
public int numberOfRows=5;
internal ColumnStructure[] columnStructures;

int[] tilemap = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] jellymap = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
void Awake()
{
    instance = this;
    //numberOfColumns = transform.GetChildCount();
    //columnStructures = transform.GetComponentsInChildren<ColumnStructure>();

    // I added the below code to put values at runtime programatically.
    // before that i used to put those from unity inspector plane.
    for (int i = 0; i<numberOfColumns; i++)
    {

        ColumnStructure cs = new ColumnStructure();

        for(int j = 0; j<numberOfRows; j++)
        {

            if(cs==null)
            {
                Debug.Log("CS is null");

            }
            else
            {
                Debug.Log("CS is not null "+j);
                cs.itemAvailability[j] = (int)tilemap[i*numberOfColumns+j]; //This line is getting null reference exception
                cs.jelly[j] = (int)jellymap[i*numberOfColumns+j];

            }

        }
        columnStructures[i] = cs;

    }

}

}

```

**Class2 Code :-**

```
public class ColumnStructure
{

public int[] itemAvailability;
public int[] jelly;

}

```

**Console Log :-**

```
CS is not null 0
UnityEngine.Debug:Log(Object)
LevelStructure:Awake() (at Assets/CM3/Scripts/Game Scripts/LevelStructure.cs:35)

NullReferenceException: Object reference not set to an instance of an object
LevelStructure.Awake () (at Assets/CM3/Scripts/Game Scripts/LevelStructure.cs:36)

```

ANSWER :-

Thanks to Petr Abdulin, I modified Class2 Code like this.

```
public class ColumnStructure
{

public int[] itemAvailability = {1,1,1,1,1,1,1,1};
public int[] jelly = {1,1,1,1,1,1,1,1};
void Awake()
{

}
}

```

# Answer
> 2 votes
Well, from you code I see that in line:

```
cs.itemAvailability[j] = (int)tilemap[i*numberOfColumns+j];

```

`cs.itemAvailability` is definitely `null`. You declare an array variable but it's never initialized.

You need something like

```
cs.itemAvailability = new int[size_of_array];

```

if you want it to be an initialized array.

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


# Question
Title: XNA graphics.PreferredBackBufferWidth's new value doesn't immediately change window size
I set the width and height of the window in my game constructor, and then pass the graphics manager to a class to check the value. In the game's initialize function, it doesn't seem to recognize the new width and height values, so it uses the default.

Here's relevant code:

**Game1.cs Constructor:**

```
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1600;
graphics.PreferredBackBufferHeight = 900;
Content.RootDirectory = "Content";
World = new TestWorld(Content, graphics);

```

**Game1.cs Initialize**

```
World.Initialize();

```

**TestWorld Initialize**

```
Debug.WriteLine(Graphics.GraphicsDevice.Viewport.Width);

```

The TestWorld Initialize outputs the default (800).

I have tried graphics.ApplyChanges(), but it does not resolve the issue.

# Answer
Please take a look at this old answer of mine that explains the process in detail.

Basically: The members on `GraphicsDeviceManager` are settings that are only actually applied when `ApplyChanges` ***or*** `CreateDevice` is called. Note that `CreateDevice` will get called for you if you are using the built-in `Game` class.

---

Regarding additional questions asked in comments: The graphics device (and so `GraphicsDevice.Viewport`) is not guaranteed to be available until `LoadContent` gets called (ref).

Although you can usually get away with using it in `Initialize`, that is not strictly correct (it does not play nice if the graphics device gets reset).

---

The correct way to get the window/viewport size is described in detail in this answer.

I think you might need to restructure your code so that things get set up in the right order.
> 2 votes

# Answer
You need to call `graphics.ApplyChanges();` in order to apply your updated settings.
> 0 votes

---
Tags: xna, c#, graphics, viewport
---


# Question
Title: UE4: Apply texture on landscape based on angle
I am creating a material for my landscape. I know that one could for example use the landscapes heightmap as a mask to apply textures at certain heights, but I want to apply textures at certain angles. For example, applying a cliff texture if the angle at that point in the landscape is larger than 45 degrees.

Thanks in advance!

# Answer
> 2 votes
To apply different textures based on height the general method is to, in a pixel shader;

1. Find the height of the geometry at the current pixel position.
    * Perform a texture lookup on the heightmap that defines the geometry or just find the position of the current geometry as you would for lighting and find the y component.
2. Supply your shader with some kind of look up table matching a threshold height to a texture.
3. Index the table using your height.
4. Optional - take the colour from two textures and average them using a weight when crossing a texture transition zone. This blends the transition and prevents hard edges.

Ok so that's a pretty straight forward method, but how do you apply this based on angle. Well I think the simplest way is to do exactly the above but replace height with "magnitude of the y component of the surface normal."

If you take the normal of a surface, which needs to be a unit vector (so normalise if appropriate), then the flatter the surface the greater the contribution in the y component.

* A perfectly flat surface pointing up would have the normal (0, 1, 0).
* A surface on it's size will have the normal (X, 0, Z).
* A surface pointing down will have the normal (0, -1, 0).

So make a lookup table based on that Y. You can take it a step further as well and use both the geometry position and normal Y component to do a 2 dimensional lookup. i.e. In low terrain use grass for level geometry and rock face for vertical geometry. Higher up use rocks for level geometry and frozen rocks for cliff faces.

---
Tags: textures, unreal, heightmap, materials
---


title: Implementing Mouse Lasso

text:
# Question
Title: Implementing Mouse Lasso
I am toying around with a Boogaloopers clone (http://www.youtube.com/watch?v=zuaRi\_fhdlQ).

I have a small problem with the lassoing.

Here's my current naive algorithm. The problem with this is that the player can swipe a U-shaped pattern with the mouse, and it is detected as a polygon, since the `isPointInPolygon`-method connects the first and last points together. I wonder if there's a simple way to fix this?

```
private void collisionDetection() {

    Player p = Player.getPlayer();

    Array<Beam> beams = p.getBeams();

    if (beams.size < 3)
        return;

    for (int i = 0; i < beams.size; i++) {

        Beam b1 = beams.get(i);

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

            Beam b2 = beams.get(k);

            // Don't do collision detection with adjacent beams
            if (p.areConnected(b1, b2))
                continue;

                if (Intersector.intersectSegments(b1.getStart(), b1.getEnd(), b2.getStart(), b2.getEnd(), null)) {

                Array<Vector2> path = p.getPath();
                if (path.size < 3)
                    continue;

                boolean destroyed = false;

                // Destroy any monsters inside the polygon
                for (int j = 0; j < entities.size; j++) {
                    Entity e = entities.get(j);

                    if (e instanceof Player)
                        continue;

                    if (Intersector.isPointInPolygon(path, e.getPosition())) {
                        destroyed = true;
                        e.destroy();
                    }
                }

                if (destroyed) {
                    SFX.play("sfx-destroy");
                }

                return;
            }
        }
    }
}

```

# Answer
The problem is you need to close the loop, to make sure the lasso is complete (based on the behavior of the video).

You do that by testing if one of the segments intersect with another segment, thus closing the loop.

It might look something like this (note I don't use libgdx, so this is untested):

```
Array<Vector2> path = p.getPath();
// Look for an intersection point
for (int i=0; i<path.size-1; ++i)
{
    for (int j=i+2; j<path.size-1; ++j)
    {
        Vector intersection;
        if (Intersection.intersectSegments(path[i], path[i+1], path[j], path[j+1], intersection))
        {
            Array<Vector2> loop = new Array<Vector2>();
            loop.add(intersection);
            loop.addAll(path, i+1, j-i);

            // Destroy any monsters inside the polygon
            for (int j = 0; j < entities.size; j++)
            // ....

            // exit loop, restart path
        }
    }
}

```

What's happening there is we start at the beginning, and test each segment with subsequent segments in the path (note j starts at i+2). If there is an intersection, we've found a loop, so we use the returned intersection point and test for containment.

If you find that the intersection criteria is too restrictive, you can extend the first and last segment, so the loop doesn't have to be closed exactly. You can add an extra "fake" point at the beginning and other at the end, following the same direction of the segment at a configurable distance (see picture).
> 5 votes

# Answer
If performance isnt a problem for you and you want simple solution, just draw a thick line and check color under your cursor. If at any point the color was equal to the line color, you know the polygon was closed.
This can be even improved by checking color of all pixels between last and current mouse position.
Other option would be to perform MANY line segment intersections.
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: How do I run a physics simulation in the background, to determine possible future outcomes?
I'm designing a physics-heavy game, in 3D. The core mechanic of this game is that the user gets to choose his actions based on probable future outcomes. For example, the player has a choice whether to try option A, B, or C. When the option comes up, I want to copy the game state and world into three separate simulations, and then run the three options in super high speed to determine probable outcome. The game will then present the probable outcome for each player choice. This needs to happen instantaneously, in terms of user experience.

It doesn't have to be an exact copy of the game state; a simplified simulation can also work, as long as the current world physics state can be duplicated and simulated. How would I go about making this? I know Unity, for example, only exposes one instance of a physics world at a time.

# Answer
In most game engines, physics objects live in their own world, and are connected to game objects through some special logic, responsible, for instance, for copying transformations and notifying about events like collisions.

Your case sounds like it requires multiple physics worlds. Most physics engines will allow you to do that, as they are designed in a modular way to be added to any game engine. For instance, in Bullet you'd create multiple instances of btDiscreteDynamicsWorld.

As long as the physics engine is *deterministic*, you should be able to maintain a "real" physics world, plus a bunch of "simulation" ones. In order to predict the outcome you'll need to:

* Step the physics world as far as required. You need to do it by calling the step/update function multiple times with small time deltas. Otherwise the results won't be stable. 60 fps is ideal, but can be expensive. It depends on whether you can afford a hitch while you predict the result.
* Once you have the results, you can connect the physics world with your game world to display them. You'll have to write some special glue code so you can walk through all the objects in your game and connect them with the appropriate physics object (probably based on name), and then transfer the transform and any other info required.
* Finally, once the player chooses an option, you simulate it using the "real" physics, in real time.
* For the next choice, you'll have to destroy the simulation physics worlds and create new ones, up to date.

Unfortunately, I'm not sure how you'd do this directly in Unity. Engines tend to be optimized for the common cases, and having multiple physics worlds is unusual. The advantage is physics engines tend to be written in a modular way, so this should make it easier.

One thing to keep in mind is that if the final outcome depends on how objects react after collisions (e.g. exploding), then you may need to duplicate your whole game world. The only alternative to this would be implementing undo functionality, so you can rewind your world.
> 3 votes

---
Tags: physics-engine, simulations
---


title: FBO result not drawing to screen

text:
# Question
Title: FBO result not drawing to screen
I recently added framebuffer rendering to my game and rendering to the FBO works (verified with glGetTexImage), but when I go to render a quad to show the result nothing is drawn to the screen. I'm using OpenGL 3.3 Core, so I'm drawing using vertex buffers for the quad and I have two simple pass-through shaders to display the quad. I apologize for the amount of code that follows, but I felt it was all necessary for anyone who ends up looking at this.

Quad generation:

```
// create vertices
// Vertex(position, normal, tex coord)
quadVertices.Add( Vertex( Vector3( -1.0f,  1.0f, 0.0f ), Vector3(), Vector2( 0.0f, 1.0f ) ) );
quadVertices.Add( Vertex( Vector3( -1.0f, -1.0f, 0.0f ), Vector3(), Vector2( 0.0f, 0.0f ) ) );
quadVertices.Add( Vertex( Vector3(  1.0f, -1.0f, 0.0f ), Vector3(), Vector2( 1.0f, 0.0f ) ) );
quadVertices.Add( Vertex( Vector3(  1.0f,  1.0f, 0.0f ), Vector3(), Vector2( 1.0f, 1.0f ) ) );
quadVertices.SendData(); // gl*Buffer* methods wrapper

// create indices (quadIndices is a buffer of 16-bit integers)
quadIndices.Add( 0 );
quadIndices.Add( 1 );
quadIndices.Add( 2 );
quadIndices.Add( 0 );
quadIndices.Add( 2 );
quadIndices.Add( 3 );
quadIndices.SendData();

```

Quad rendering:

```
glDisable( GL_DEPTH_TEST );
glDisable( GL_CULL_FACE );

// bind the texture
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, framebuffer.GetColorHandle() );
_shader.Seti( "texture0", 0 );

 // projection matrix is glm::ortho( -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f );
_shader.Set( "proj", _projection );

// get attributes
int vertex   = _shader.GetAttribLoc( "vertex" );
int texCoord = _shader.GetAttribLoc( "texCoordV" );

// bind buffers
quadVertices.Bind();
quadIndices.Bind();

// enable arrays and point to data
glEnableVertexAttribArray( vertex );
glVertexAttribPointer    ( vertex,   3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (void*)( 0 ) );
glEnableVertexAttribArray( texCoord );
glVertexAttribPointer    ( texCoord, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (void*)( sizeof( Vector3 ) * 2 ) );

// draw!
glDrawElements( GL_TRIANGLES, quadIndices.Size(), GL_UNSIGNED_SHORT, 0 );

// disable arrays
glDisableVertexAttribArray( vertex   );
glDisableVertexAttribArray( texCoord );

// unbind everything
quadVertices.Unbind();
quadIndices.Unbind();
glBindTexture( GL_TEXTURE_2D, 0 );

glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );

```

Vertex shader:

```
#version 330 core

in  vec3 vertex;
in  vec2 texCoordV;
out vec2 texCoordF;

uniform mat4 proj;

void main()
{
    texCoordF = texCoordV;
    gl_Position = proj * vec4( vertex, 1.0 );
}

```

Fragment shader:

```
#version 330 core

layout(location=0) out vec4 fragColor;

in vec2 texCoordF;

uniform sampler2D texture0;

void main()
{
    fragColor = texture( texture0, texCoordF );
}

```

# Answer
Maybe the projection matrix is wrong, but that should not matter. When rendering a fullscreen quad, you can discard the projection entirely.

Basically your vertex shader should be:

```
#version 330 core

in  vec3 vertex;
in  vec2 texCoordV;
out vec2 texCoordF;

void main()
{
    texCoordF   = texCoordV;
    gl_Position = vec4(vertex, 1.0);
}

```

The important bit is that you submit the vertexes in device coordinates (from \[-1,-1\] to \[1,1\]) but you are doing that already.
> 0 votes

---
Tags: opengl
---


# Question
Title: Box2d pathfinding using raytracing / predicted collisions
I have a Box2d/Cocos2d iOS game with enemies that attempt to follow the player (to attack). I'm working on improving the pathfinding logic so that the enemies won't crash into objects in the world.

Using raytracing, I know when there's an obstacle between an enemy and the player. I know when the enemy can't see the player.

I'm attempting to find a good way for the enemy to navigate around the obstacle, no matter what direction it's facing.

Right now, I start with the angle between the enemy and the obstacle. I gradually increment the angle, looking for any on-obstructed path that will allow the enemy to travel further than the obstacle's distance. This seems to work well so far, but it doesn't take into account the size of the enemy.

For example, if I have a 32px-squared enemy, the raytrace may find a clear path that would involve the edges of the ship hitting an obstacle.

Is there a way I can run a raytrace, predict collisions for something with a known width? Or is there a better way for my enemies to navigate around an obstacle.

# Answer
> 1 votes
What you're describing sounds like Obstacle Avoidance (as pointed out by @nathan).

The easiest way to implement it is modeling both the characters and the obstacles as circles. In order to avoid the obstacle, we increase its radius by the radius of the character, so we can treat the character as a point. The angle θ to both sides of the obstacle can be calculated as `theta = asin((R+r)/d)`.

With the angle you can calculate the vectors to avoid the obstacle to the right and to the left, using a rotation matrix to rotate the vector going from the character to the obstacle (the green line). Then you can see which side of the obstacle requires less steering, by calculating the sign of the z coordinate of the cross product of the movement direction and the vector to the obstacle.

If your objects have a different shape, you might still be able to use circles by making them large enough to include the object. The advantage of circles is that they make expanding the obstacle to turn the character into a point very easy. Other shapes require more complicated geometry.

Keep in mind this approach will only work if the world is sparse enough that steering to avoid an object won't push you into another one. If that's the case, you'll have to resort to more sophisticated approaches, possibly including pathfinding.

---
Tags: box2d, path-finding
---


# Question
Title: How to prevent a circular dependency between an entity and its state?
I've read this question, and I think it has some good answers and discussion, but it appears to focus primarily on rendering.

I have a different problem in the management of a game entity's state. What I end up with is this:

Game -\> Player -\> FSM -\> State -\> Player

Upon entry into a state a pointer to Player must be passed through, but no matter what I do in C++ it has trouble resolving this relationship hierarchy.

A good deal of how I'm designing my FSM is like this article. However, that is a psuedo implementation, and does not use headers. Without moving completely over to behavior trees is there another design pattern that will eliminate this circular dependency?

# Answer
> 4 votes
you can use a forward declaration of the class that are in circular dependency.

Here an explanation

```
class firstClass; //Here the forward declaration
class secondClass
{
  public:
  private:
};

```

Then in the cpp of the second class you can include the firstClass header file.

---
Tags: c++, state, game-state
---


# Question
Title: SpriteKit - How to jump to specific position?
I'm would like to achieve something like Object A will jump to position A in parabolic way. For example:

I am able to make the object jump but i do not know how to calculate to make the object jump to the precise location.

# Answer
> 2 votes
SpriteKit uses `SKAction` objects to accomplish most of its functionality. What you're seeking is `SKAction's` `followPath:duration:` action.

The following accomplishes this:

```
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointZero];
    [path addQuadCurveToPoint:CGPointMake(deltaX/2, desiredHeight) controlPoint:CGPointMake(0, desiredHeight)];
    [path addQuadCurveToPoint:CGPointMake(deltaX, deltaY) controlPoint:CGPointMake(deltaX, desiredHeight)];
    CGPathRef pathref = path.CGPath;

    [jumpingNode runAction:[SKAction followPath:pathref duration:desiredDuration]];

```

This allows the Node to move along the specified path. It looks very uniform, but you can always add easing (related StackOverflow question) to give a more natural look

---
Tags: physics, ios, spritekit
---


title: Clipping text in algorithm

text:
# Question
Title: Clipping text in algorithm
I'm looking for an algorithm that can clip a text ( GUI Mesh text ) when it's length is over 20 characters. The problem is I have one background image(textured plane) (orthographic), where I want to put a Gui mesh text on it, it happens that sometimes the text is larger in length than the supposed background image, and it gets out of the background mesh boundary.

Is it possible to fit that gui mesh into the boundary of the background plane mesh ?

# Answer
Now I am no unity expert (I opened it once two years ago), but I hope this helps.

First you would want to find the width of the string (in pixels). Something along these lines:

```
var textDimensions = GUI.skin.label.CalcSize(new GUIContent("text"));
//textDimensions.x contains the width in pixels.

```

Now you are going to want to see if that fits. If it doesn't then we are going to have to truncate the input string. (pseudo C++/C# mix)

```
var textDimensions = GUI.skin.label.CalcSize(new GUIContent(thestring));

while (textDimensions.x > somesize) {
    cut off one character
    textDimensions = GUI.skin.label.CalcSize(new GUIContent(truncated string));
}

```
> 0 votes

---
Tags: unity, textures, text, mesh
---


# Question
Title: OpenGL strange rendering problem when buffers have different sizes
I have encountered a very odd error in my program, "odd" in the sense that everything the API says suggests that the error should not occur.

I have a bunch of 2D un-indexed vertex data, and I want to render it as lines. So far, so good. Then, I wanted to make each vertex have its own (RGB) color, so I generate a color for each vertex. For simplicity, I chose red. Works fine, except now only 2/3 of the points are being rendered! The problem arises from the fact that each vertex's position data consists of only 2 numbers, whereas the color data consists of 3 numbers. So, the "position" buffer has 2 elements per vertex while the "color" one has 3 elements per vertex. I thought that using glVertexAttribPointer to tell this information to OpenGL would be enough, but turns out it's not. In fact, if I say that the color data has only 2 elements per vertex, using

```
glVertexAttribPointer(vertexColorID2,2,GL_DOUBLE,GL_FALSE,0,(void*)0);

```

(as opposed to 3), it renders all the points - except now I can only specify two numbers for the RGB color, so I can't get the right color. The full code of the issue is below:

```
    glUseProgram(programID2); //draw the graph
    graph_data = graphData();
    std::vector<double> graphcolordata(graph_data.size()/2*3); for (int i = 0; i < graph_data.size(); i += 3) graphcolordata[i] = 1;
    glEnableVertexAttribArray(vertexPosition_modelspaceID2);
    glBindBuffer(GL_ARRAY_BUFFER, graphbuffer);
    glBufferData(GL_ARRAY_BUFFER, graph_data.size()*sizeof(GLdouble), &graph_data[0], GL_STREAM_DRAW);
    glVertexAttribPointer(vertexPosition_modelspaceID2,2,GL_DOUBLE,GL_FALSE,0,(void*)0);
    glEnableVertexAttribArray(vertexColorID2);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer2);
    glBufferData(GL_ARRAY_BUFFER, graphcolordata.size()*sizeof(GLdouble), &graphcolordata[0], GL_STREAM_DRAW);
    glVertexAttribPointer(vertexColorID2,3,GL_DOUBLE,GL_FALSE,0,(void*)0);
    glDrawArrays(GL_LINES, 0, graph_data.size()/2);
    glDisableVertexAttribArray(vertexPosition_modelspaceID2);
    glDisableVertexAttribArray(vertexColorID2);

```

Note: programID2 is my basic shader program, and the following variable definitions were previously used:

```
GLuint vertexPosition_modelspaceID2 = glGetAttribLocation(programID2, "vertexPosition_modelspace");
GLuint vertexColorID2 = glGetAttribLocation(programID2, "vertexColor");

```

Edit: Incredibly stupid error, figured it out immediately after posting when it had previously stumped me for half an hour.

```
    std::vector<double> graphcolordata(graph_data.size()/2*3); for (int i = 0; i < graph_data.size(); i += 3) graphcolordata[i] = 1;

```

should be std::vector graphcolordata(graph\_data.size()/2\*3); for (int i = 0; i \< graphcolordata.size(); i += 3) graphcolordata\[i\] = 1;

When this initialization is fixed, it works fine. I would delete this, but I do not see how.

# Answer
Solved:

Incredibly stupid error, figured it out immediately after posting when it had previously stumped me for half an hour.

```
    std::vector<double> graphcolordata(graph_data.size()/2*3); for (int i = 0; i < graph_data.size(); i += 3) graphcolordata[i] = 1;

```

should be std::vector graphcolordata(graph\_data.size()/2\*3); for (int i = 0; i \< graphcolordata.size(); i += 3) graphcolordata\[i\] = 1;

When this initialization is fixed, it works fine. I would delete this question, but I'm not sure how.

Sorry about that.
> 0 votes

---
Tags: opengl, rendering, color, shading
---


# Question
Title: What is the appropriate way to implement wobble/balance mechanics in Unity 3D?
We are trying to implement a minigame where the player character sits on a bouncing ball, and needs to a) hit forward to move forward and b) hit left/right to adjust against the the ball's natural wobble (in other words, if the ball leans left, you must hit right).

We have tried implementing this by setting the bounciness and weight on the ball so that it bounces naturally when the player is not on it, then fixing the player model to the ball (in other words, treating them as a single unit), then having the CharacterController control the unit while it continues bouncing.

However, no matter how we tune the various factors (bounciness, weight, input multiplier, gravity), the ball remains quite sensitive and eventually spirals out of control. We would particularly like to allow the player *some* opportunity to regain control.

I have played a number of games that require some kind of reflex-based wobble/balance mechanic. Is there a general approach here that we are missing?

This question is for a small academic project, so we're wondering if there's a specific component we need, or part of the Physics engine we've missed, or technique we should look up - but please don't post code. There are no project requirements here except using Unity 3D (e.g. the assignment is not "implement a bouncing ball minigame").

# Answer
What you seem to have is a double pendulum which is inverted.

Here, m2 is the player's center of mass. In order to remain in balance, L2 cannot be tangent to the ball (they would slip off) and m2 must remain nearly above f (otherwise they'd fall over). Obviously this would be complicated to manage in a game where you can't feel how you're balancing.

A simpler method is use a single leg pendulum and imagine where the player needs to direct their center of mass in order to move in that direction. To go forward, they need to shift their weight forward to stay on the ball. To stop going forward, they need to shift their weight back, otherwise their center of mass will keep going that way until they slip off.

I've used forward/backward momentum here since it's easier to describe, but the same principle applies to lateral movement and turning. In order to turn, they need to shift their weight counter to the direction of the turn while moving forward or backward.
> 1 votes

---
Tags: unity, physics, game-mechanics
---


# Question
Title: What is "ping pong" in the context of graphics rendering?
I have to render a scene, once per light, and blend the result of the various passes. I heard and read that one way to increase performances and render targets to use would be *ping pong*.

I'm new to this context. What does this mean in terms of render targets + blending?

# Answer
"Ping pong is a technique to alternately use the output of a given rendering pass as input in the next one."

(Example: http://www.seas.upenn.edu/~cis565/fbo.htm)
> 1 votes

---
Tags: opengl, rendering, blending, rendertargets, multiple-render-targets
---


# Question
Title: Multiplayer FPS Gameplay: How to encourage players to dispense ammo?
In the *Battlefield: Hardline* beta, players can now obtain health and ammo *directly* from other players, without having to ask for it via the command rose.

Here's two examples of how asking for health and/or ammo differed between most *Battlefield* games and *Battlefield: Hardline*. We'll have two players in these scenarios: A and B. **Player A**, who is not a Support-class player, is running low on ammunition. **Player B**, being a Support-class player, has ammo that he can give to Player A.

* **Example 1** \- up to *Battlefield 4*: Player A tells Player B, "I need some ammo!" Player B will either…
    + respond by dispensing ammo for Player A; or
    + *not* respond, for whatever reasons. Player A has to either keep telling Player B that he needs ammo, or get his attention first.
* **Example 2** \- *Battlefield: Hardline*: instead of bothering to tell Player B that he needs ammo, Player A walks up to Player B and presses a button. Player A's ammo is replenished.

From looking at each scenario's differences, Example 2 is the most efficient choice. Compared to Example 1, there's no uncertainty about getting the ammo at all. On the other hand, Example 2 costs both players the benefit of team communication (at least with getting health and ammo).

Should there be some sort of penalty for Example 2-esque scenarios, that will encourage players to dispense ammo for their teammates? One possible route can be to take away from a player's EXP for letting other players take ammo from them, directly (and too often).

# Answer
I'd like to examine two multiplayer class-based FPS games with support classes as case studies: Wolfenstein: Enemy Territory and Team Fortress 2. Both have separate classes that give health and ammo, and I think it's helpful to consider both types of support.

**Enemy Territory** has three support functions - *healing*, *reviving* and *ammo* \- given by two classes - *medic* and *field op*. Healing and giving ammo are similar: the medic or field op uses up "charge" - a limited, regenerating meter - and throws down a pack of health or ammo not far in front, which can be picked up by any other player. Medics could also revive dead teammates by using a close-range "needle" on the body, and in practice medics rarely ran out of needles.

The game also rewarded support actions in the form of "xp"; gaining xp would eventually make the player gain ranks, improve or even gain new abilities. This provided an extrinsic reward to supporting teammates.

In practice, there was an abundance of revives and a shortage of ammo giving. Revives were common because of two factors: it was obvious who needed reviving, and it used up practically no resources. Ammo giving was rare for the opposite reasons; in addition to using up "charge", the field op was a peculiar class in that it can also call in powerful AOE attacks, but at the cost of charge, so there was resource contention.

Then there's **Team Fortress 2** which hopefully needs no introduction. I feel that the *medic* was designed very well, whereas the *engineer's* *dispenser* ability is flawed. Whilst medics can be rewarded by earning *assists* when healing teammates that produce kills, the dispenser does not reward the engineer when being used. In practice (and echoing Thijser's observation on dispensers), medics were abundant but dispensers were often placed at inconvenient places.

To encourage players to give ammo (and support each other more in general), I offer the following tips:

* **Make it easy**: this almost goes without saying; but it can be achieved in two ways: *make it easy to know who needs supporting*, and *make it easy to support*. The medic class in TF2 does this well: not only is the medic gun easy to heal with, even on moving teammates, teammates also have a "call medic" button. Revives in ET also do this well as bodies show up prominently in the medic's GUI. The TF2 dispenser is somewhat good in this regard; once placed the dispenser passively supports, which makes it very easy on the engineer.
* **Make it easy to say "thanks"**: the lack of support isn't a problem when it's a group of friends playing, but it is when it's strangers in a fast-paced game - there's very little time and incentive to show appreciation, which makes supporting a lonely and thankless job. TF2 has an interesting take on this: characters will automatically say "thanks" when being supported, but I feel this is impersonal; it should still require human input, but as easy as possible. Maybe a context-sensitive keypress that says "thanks" to whoever is helping you right now? In any case, don't underestimate the value of even simple human interactions, as they profoundly shape the tone of the game.
* **Reward the supporter**: supporting, by definition, benefits the recipient rather than the supporter. In practice, the supporter is often punished because they have to risk themselves in order to reach those that need support the most. To encourage more support, turn some rewards back onto the supporter. ET does this well with the xp system; TF2's medic also has the powerful "UberCharge" ability which needs to be charged by healing teammates.
* **Reward supporters for good gameplay**: even better than simply rewarding support actions, reward those that directly contribute to the main objectives. As Thijser noted, blindly rewarding all support actions can lead to bad gameplay, as support players are encouraged to spam support actions, even if they don't help the team. Instead you can reward the actions that do actually help. TF2 gives assists to medics who are healing the teammate that made the kill, for example. I think this is a good space for new ideas; how about (as Joe mentioned) tracking who gave you ammo, and giving assists for kills made using that ammo? I think there are many ideas in sport - where the "assist" concept came from - that can be used too; many of the stats tracked in team sports can be considered support actions, the most useful of which do often contribute to the team's success. Think about rebounds and blocks in basketball, for example, which are highly valued for their indirect effect on the game.
> 3 votes

# Answer
There are a few better ways to get players to share ammo, however your your example mechanisms wouldn't work that well, example 1 has the weakness of not really giving any reason towards player B has no reason the disperse ammo and therefor might not decide to share him ammo at all, example 2 can either be used for some really annoying grieving and could easily discourage the usage of the support classes.

for example how about instead of punishing a player who does not share ammo reward a player who does? What if you keep track the source of all ammo and give some kind of assist bonus to the player whose ammo was used to get a kill?

Related to this you could set up some kind of group bonus where players are also rewarded for the kills of those nearby, this encourages them to help the players who are close as doing so will net them a better score as well (as long as kill stealing doesn't become to much of a problem).

Or you could try and get your player to care more about winning as a team rather then individual achievements. What if most rewards come not from scoring kill or other such actions but from actually winning games (don't forget to use some mechanism to prevent players from jumping ship the moment their are in a bad position).

Finally the dispenser in Team fortress has an interesting methode, in team fortress the engineer needs a large amount of ammo (in his case called metal) and can build a building that disperses ammo and health (the dispenser). As this building also resupplies him most engineers will quickly building this ammo close to where they will be staying. This means that going towards an engineer will probably result in getting more ammo.

I would not advice directly giving experience/money towards those that disperse ammo as that would be to easy to exploit.
> 3 votes

---
Tags: game-design, multiplayer, game-mechanics, first-person-shooter, teamwork
---