# Question
Title: Glow with forward rendering without two passes/MRT?
I am trying to implement controllable bloom. By controllable I mean bloom that can be requested even for non-bright pixels by adding the bloom value into a model's texture channel. To do this I need to somehow pass this value (the strength of the bloom for the current pixel) into the bloom post-processor. The most obvious choice would be storing it in the alpha channel, but I use alphablending for every model I draw so for me this is not an option. A quick and dirty solution is to use MRT, render to two textures and then recombine them into one which is a huge waste of memory and speed. Another solution could be to render the scene twice: once for the color and alpha components and second for the bloom components - that is the by-the-book method I find on every internet page. Even when rendering into a smaller RT this is still an overkill.

Another thing I thought about was using YCbCr encoding and then simply increasing Y to order bloom, but I always get a green-ish image after decoding (even if I encode-decode in the very same shader, line after line). Here is the encode-decode operations I did:

```
inline float3 RGBtoYCbCr(float3 color)
{
    float3 YCbCr;
    YCbCr.r = color.r*0.299f + color.g*0.587f + color.b*0.114f;
    YCbCr.g = 0.5f + (-color.r*0.168f - color.g*0.331f + color.b*0.5f);
    YCbCr.b = 0.5f + (color.r*0.5f - color.g*418 - color.b*0.081f);

    return YCbCr;
}

inline float3 YCbCrtoRGB(float3 color)
{
    float3 RGB;
    RGB.r = color.r+1.402*(color.b-0.5f);
    RGB.g = color.r-0.344*(color.g-0.5f)-0.714*(color.b-0.5f);
    RGB.b = color.r+1.772*(color.g-0.5f);

    return RGB;
}

float4 MainShader(...)
{
    ...
    output.COLOR.rgb = saturate(output.COLOR.rgb);

    output.COLOR.rgb = RGBtoYCbCr(output.COLOR.rgb);
    output.COLOR.rgb = YCbCrtoRGB(output.COLOR.rgb);
}

```

So I wanted to ask if anyone knows a way to do it in one pass without MRT and (if possible) by still rendering an HDR image?

# Answer
> 0 votes
I have actually found a way to do it.

The thing is, alpha values are blended separately from colors and you can specify a different function for their blending. So what you can do, is set the blending function for alphas as BlendFunction.Max and only allow the highest alphas through. This will allow you to "mark" pixels for the glow pass with alphas equal to "1".The latter will obviously work for opaque objects, but in order for it to work for the translucent objects, you need to limit their output alpha values to the range 0 - 0.99f (or (0 - 254)/256 for RGBA32).

Translucent objects use their output alpha channels to specify the how much of their color must be blended with the underlying destination color. The maximum of 0.99f is pretty close to opaque, so you will be able to blend your bushes and smokes just like before, but, at the same time, if you will need to mark the pixel for the bloom pass - you will always be able to set output alpha to "1".

Now for the glow power. There is actually a way to control how much the pixel will glow when blurred by simply tweaking it's color. If you want it to shimmer white - make it gray, if you want it to be bright yellow - make it medium yellow! If you want to be even more creative - use FP16 textures and specify the glow power as a number between 1 and 2.

In the end of the day the only limitation I see in this approach is the fact that only fully opaque pixels will be able to glow, but if you think about it, it's not that big of a limitation :)

I've just checked it in the NSight profiler - rendering a huge polygon with translucent 2d ship with lots of opaque areas and some translucent pixels is no different GPU-time-vise for standard blending or MAX blending with alpha = min (alpha, 0.98f) and visually the colors behind the ship are visible only if you force yourself to see them.

---
Tags: hlsl, glow
---


# Question
Title: How do I bind a display from XCB to EGL with eglGetDisplay
I have been trying to set up an EGL session with a window that I created using XCB. I am not having much success. I keep getting the error: An EGLDisplay argument does not name a valid EGL display connection

Is it even possible to use XCB with EGL/GLES2? I was using XLib before but i was not a big fan of their error handling.

```
void pretty_print_egl_check(int do_assert_on_failure = 1, const char *message = "");

void create_display()
{
EGLint numConfigs;

EGLint configAttribList[] =
{
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
    EGL_RED_SIZE,       8,
    EGL_GREEN_SIZE,     8,
    EGL_BLUE_SIZE,      8,
    EGL_ALPHA_SIZE,     8,
    EGL_DEPTH_SIZE,     24,

    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
    EGL_NONE, EGL_NONE
};

EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};

// Initialize X Windows
_display = xcb_connect(NULL,NULL);

if(xcb_connection_has_error(_display))
{
    xcb_disconnect(_display);
    printf("Could not connect to X11 display.\n");

}

assert(NULL != _display);

_eglDisplay = eglGetDisplay ((Display *)_display);
pretty_print_egl_check(true,"eglGetDisplay call");

// Initialize EGL.
eglInitialize( _eglDisplay, NULL, NULL );
pretty_print_egl_check(true,"eglInitialize call");
}

void pretty_print_egl_check(int do_assert_on_failure = 1, const char *message = "")
{
    int error = eglGetError();
    const char *egl_success_string                  = "The last function succeeded without error." ;
    const char *egl_not_initialized_string          = "EGL is not initialized, or could not be initialized, for the specified EGL display connection. " ;
    const char *egl_bad_access_string               = "EGL cannot access a requested resource (for example a context is bound in another thread). " ;
    const char *egl_bad_alloc_string                = "EGL failed to allocate resources for the requested operation.";
    const char *egl_bad_attribute_string            = "An unrecognized attribute or attribute value was passed in the attribute list. ";
    const char *egl_bad_context_string              = "An EGLContext argument does not name a valid EGL rendering context. ";
    const char *egl_bad_config_string               = "An EGLConfig argument does not name a valid EGL frame buffer configuration. ";
    const char *egl_bad_current_surface_string      = "The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid. " ;
    const char *egl_bad_display_string              = "An EGLDisplay argument does not name a valid EGL display connection.";
    const char *egl_bad_surface_string              = "An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering. ";
    const char *egl_bad_match_string                = "Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface). ";
    const char *egl_bad_parameter_string            = "One or more argument values are invalid.";
    const char *egl_bad_native_pixmap_string        = "A NativePixmapType argument does not refer to a valid native pixmap. ";
    const char *egl_bad_native_window_string        = "A NativeWindowType argument does not refer to a valid native window.";
    const char *egl_context_lost_string     = "A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering. ";

    switch (error)
    {

            case EGL_SUCCESS:
                    printf("%s:%s",message,egl_success_string);
                    break;
            case EGL_NOT_INITIALIZED:
                    printf("%s:%s",message,egl_not_initialized_string);
                    break;
            case EGL_BAD_ACCESS:
                    printf("%s:%s",message,egl_bad_access_string);
                    break;
            case EGL_BAD_ALLOC:
                    printf("%s:%s",message,egl_bad_alloc_string);
                    break;
            case EGL_BAD_ATTRIBUTE:
                    printf("%s:%s",message,egl_bad_attribute_string);
                    break;
            case EGL_BAD_CONTEXT:
                    printf("%s:%s",message,egl_bad_context_string);
                    break;
            case EGL_BAD_CONFIG:
                    printf("%s:%s",message,egl_bad_config_string);
                    break;
            case EGL_BAD_CURRENT_SURFACE:
                    printf("%s:%s",message,egl_bad_current_surface_string);
                    break;
            case EGL_BAD_DISPLAY:
                    printf("%s:%s",message,egl_bad_display_string);
                    break;
            case EGL_BAD_SURFACE:
                    printf("%s:%s",message,egl_bad_surface_string);
                    break;
            case EGL_BAD_MATCH:
                    printf("%s:%s",message,egl_bad_match_string);
                    break;
            case EGL_BAD_PARAMETER:
                    printf("%s:%s",message,egl_bad_parameter_string);
                    break;
            case EGL_BAD_NATIVE_PIXMAP:
                    printf("%s:%s",message,egl_bad_native_pixmap_string);
                    break;
            case EGL_BAD_NATIVE_WINDOW:
                    printf("%s:%s",message,egl_bad_native_window_string);
                    break;
            case EGL_CONTEXT_LOST:
                    printf("%s:%s",message,egl_context_lost_string);
                    break;
            default:
                    printf("%s:%s",message,"Unknown EGL error");
                    break;
    }
    printf("\n");
    if (do_assert_on_failure)
    {
            assert(error == EGL_SUCCESS);
    }
}

```

# Answer
I do not know why, but this works for me:

\_eglDisplay = eglGetDisplay ((EGLNativeDisplayType)NULL);

I found it by chance, and everything works fine except that eglQueryString() return EGL\_BAD\_DISPLAY.

I hope this helps.

Anyone know more about this?
> 1 votes

# Answer
I'm not sure how to get a specific xcb\_connection\_t, but eglGetDisplay(EGL\_DEFAULT\_DISPLAY) works to get the "default one". Since I generally just have one, that works for me.
> 0 votes

---
Tags: linux, egl
---


# Question
Title: Do I need a company name to publish on Google Play?
I'm going to upload my Android mobile game on Google Play. But it seems like all games are developed by companies(such as Zynga, and King) and I don't see individual's names as developers. Do I need to register a company name officially? I think it costs a few hundred dollars... If I have to, how and where do I register? or instead of registering a company for a few hundred dollars, if I make a domain website that is named as my company name, would it provide me some protections? Also, do I need to trademark my game's title as well? Thanks!

# Answer
You can put what you want under developer name. Just make sure its not a trademark being used or registered trademark. Or just use your real name. It doesn't matter too much.

If you make up a name and brand yourself as it, its a trademark. A website would help prove you used it first.
> 5 votes

---
Tags: android, game-design
---


# Question
Title: How to clear out a drawn texture from the screen in libGDX
I am trying to clear out the drawn texture from the screen.

Lets take a classic game example - in many games when the character goes through the coins the coins clears out from the screen and displays a sweet animation like fade in and fade out the points collected from that coin(+10) and show the coin exploding animation on that position.

I want to do something similar to that.
I am using `SpriteBatch` to draw the texture region like below.

**Setting texture Region:**

```
(...)
 public Texture texture;
    public TextureRegion coin;
    texture = new Texture(Gdx.files.internal("data/texture.png"));
    texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
    coin = new TextureRegion(texture, 0, 336, 65, 73);
 (...)

```

**Drawing the texture into screen :**

```
 public SpriteBatch batcher;
 batcher = new SpriteBatch();
 batcher.setProjectionMatrix(cam.combined);
  batcher.begin();
    batcher.enableBlending();
    batcher.draw(coin, x, y, 65,73);
    (...)
    (...)
  batcher.end();

```

The game character is also drawn using the same logic shown above.
Now when the game character will collide with the coin that I have drawn,the coin must be cleared(vanished) and some animation or big font like +50 must fadein and fadeout in that position.I tried but didn't find anything that would do this.
So how to do that ?

# Answer
> 1 votes
Why don't you create a **class** for your coin object, and then collect all the coins in an array (`Sprite[] coin`), so whenever a collision occurs (player-coin), you call `coins[i].destroy`, where you can properly dispose all the referenced resources, or reset position for the next coin ?

For drawing :

```
 for (int i = 0; i <= quantity of coins; i++) {
          coin[i].draw(spriteBatch);
    }

```

For detecting collision :

```
 for (int i = 0; i <= quantity of coins; i++) {
         if (player.collide(coin[i])) {
             coin[i].applyFadeOut();
             score += 10;
             coin[i].destroy();
    }

```

---
Tags: java, libgdx
---


# Question
Title: (LWJGL) Pixel Unpack Buffer Object is Disabled? (glTextImage2D)
I am trying to create a render target for my game so that I can re-render at a different screen size. But I am receiving the following error:

```
Exception in thread "main" org.lwjgl.opengl.OpenGLException: Cannot use offsets when Pixel Unpack Buffer Object is disabled

```

Here is the source code for my Render method:

```
    // clear screen
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

    // Start FBO Rendering Code
    // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer.
    int FramebufferName = GL30.glGenFramebuffers();
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, FramebufferName);

    // The texture we're going to render to
    int renderedTexture = glGenTextures();

    // "Bind" the newly created texture : all future texture functions will modify this texture
    glBindTexture(GL_TEXTURE_2D, renderedTexture);

    // Give an empty image to OpenGL ( the last "0" )
    glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, 1024, 768, 0,GL_RGB, GL_UNSIGNED_BYTE, 0);

    // Poor filtering. Needed !
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    // Set "renderedTexture" as our colour attachement #0
    GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, renderedTexture, 0);

    // Set the list of draw buffers.
    IntBuffer drawBuffer = BufferUtils.createIntBuffer(20 * 20);
    GL20.glDrawBuffers(drawBuffer);

    // Always check that our framebuffer is ok
    if(GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER) != GL30.GL_FRAMEBUFFER_COMPLETE){
        System.out.println("Framebuffer was not created successfully! Exiting!");
        return;
    }

    // Resets the current viewport
    GL11.glViewport(0, 0, scaleWidth*scale, scaleHeight*scale);

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glLoadIdentity();

    // let subsystem paint
    if (callback != null) {
        callback.frameRendering();
    }

    // update window contents
    Display.update();

```

It is crashing on this line:

```
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, 1024, 768, 0,GL_RGB, GL_UNSIGNED_BYTE, 0);

```

I am not really sure why it is crashing and looking around I have not been able to find out why. Any help or insight would be greatly welcome.

# Answer
The last input in the function is the problem. If you look at the lwjgl source code you can see that it uses it as an offset (used with PBOs). To actually pass no data use a 'null' instead.
> 3 votes

---
Tags: opengl, lwjgl, frame-buffer
---


title: Height and width of a Farseer body?

text:
# Question
Title: Height and width of a Farseer body?
I have a body named PersonA. If PersonA collides with another body, the width and height of that body should be saved. I tried it like this but I always get error messages that "Width" and "Height" don't exist.

```
bool PersonA_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
{
//How tall and broad is the body that collided with PersonA
float Width = fixtureB.Body.Width;
float Height = fixtureB.Body.Height;

return true;
}

```

How can I get the width and height of another body? What should I change?

# Answer
Bodies in Farseer have no "shape" of their own. The Body defines the position, velocity, mass, etc (basically a point-mass). Fixtures give that body a "shape" that can collide with things.

You can get the AABB (axis-aligned bounding-box) of a Fixture with `Fixture.Shape.ComputeAABB(...)`. Don't use `Fixture.GetAABB`, which is a "loose" AABB used by Farseer for collision detection.

(Note that the `LoopShape` can have multiple child shapes, see `Fixture.Shape.ChildCount`. For other shapes just use `childIndex = 0`.)

Depending on your needs, you might want to get the AABB of the transformed Fixture. For example, to get the AABB in world space, use the transform from `Body.GetTransform(...)`. Otherwise use:

```
Transform t = new Transform();
t.R.SetIdentity();

```

Note that a Body can have multiple Fixtures (`Body.FixtureList`). If this is the case, you will want to combine the AABBs of each Fixture using `AABB.Combine(...)`.

---

If you want to guarantee that the resulting width and height are equal to something you set-up at object-creation time, you may want to just use the `Body.UserData` field to store that information.
> 0 votes

---
Tags: xna, c#, farseer-physics-engine
---


# Question
Title: How can I draw a shadow under my character?
I created a 2D tile-based jump and run game for Windows Phone and I want to draw a shadow under the character. How can I do that? The shadow must also be drawn on the tiles if the character jumps. The character and the tiles are rectangles.

How can I draw a shadow under my character?

The shadow should look similar to the shadows in this picture:

**UPDATE:** I tried to solve the problem like described in Gamefreak0's answer, but it's not working. I created a ShadowChecker object and I check in a foreach-loop if it collides with a platform. If it collides, the variable ShadowPosition gets changed. But it's not working correctly. I made a picture, and in this picture you see that the shadow isn't on a platform. Why is the shadow not getting drawn on the pink platform?

The character(black rectangle) is above the pink platform, so the shadow should be on the pink platform.

I update the shadow's position with this code:

```
 protected override void Update(GameTime gameTime)
    {
        Rectangle CollisionRect = new Rectangle(-1000, -1000, 0, 0);
        ShadowChecker = CharacterRect;

        //FloorRect is the brown rectangle at the bottom. There is no other platform under the FloorRect.
        while ((CollisionRect.Height == 0) && (ShadowChecker.Bottom <= (FloorRect.Y + FloorRect.Height / 2)))
        {
            ShadowChecker.Y += 1;
            foreach (Rectangle r in PlatformRectangles)
            {
                if (ShadowChecker.Intersects(r))
                {
                    CollisionRect = r;
                    break;
                }
            }
        }
        if (CollisionRect.Height != 0)
        {
            // Draw the shadow on this position
            ShadowPosition = new Vector2(CharacterRect.X, CollisionRect.Y - CollisionRect.Height / 2);
        }

        base.Update(gameTime);
    }

```

# Answer
> -2 votes
Try this approach:
Spawn a `shadow` object on the X and Y position of the player, then apply a very strong gravity force, and check for collisions (just like you do with the real player)
Then on the next frame update the coordinates of the shadow object with the new X and Y cooordinates of the player (I.E. place it on the same coordinates of the player) Then apply again gravity, etc.
It is important that you set a strong enough gravity, so that you're sure that your shadow does not float mid-air.

# Answer
> 8 votes
Draw a shadow sprite like you draw your character before the character (to make it appear behind him). Make sure its X position is updated according to the character, but the Y position stays on the tile. You have got a shadow.

# Answer
> 1 votes
It may not be the best answer but,

Make an object called ShadowChecker that constantly draws a rectangle/line below the player. Use collision detection to adjust the height of the rectangle/line until it's not colliding with any object besides the player AND there is a platform just below the collision box. Then check the Y position just below the ShadowChecker, if there is a platform there, that's where you draw the shadow, if there isn't, don't draw the shadow. (the ShadowChecker's collision box is probably still updating if this happens)

This probably isn't the best answer but it'll give you some results.

EDIT: Method 2: Expanding on Predicting Collision Detection

Since the first method didn't work you'll have to create a method that does something similar to Collision Prediction. Here's a good article on it. Your method just needs to look only at the player's Y coordinate and always be looking down. Once you've figured out when the collision happens you know where it happens so you can draw the shadow there. If this doesn't work I would suggest Riccardo Vailati's answer.

# Answer
> 0 votes
Alright, so an easyish change to your algorithm will make it both neater and probably work better:

1. You use ShadowChecker as Character rect that you move downwards. Instead, expand it's height to either infinity or the bottom of the screen (*FloorRect.Y*).
2. After expanding it, loop through the platforms:

```
    float currentHighestY = ShadowChecker.Y;
    foreach (Rectangle r in PlatformRectangles)
    {
        if (ShadowChecker.Intersects(r) && r.Y < currentHighestY)
        {
            currentHighestY = r.Y;
            CollisionRect = r;
            break;
        }
    }

```
3. i.e. You're picking the "highest" intersecting platform and you're only looping through the platforms once.
4. Next step after that is to limit the amount of platforms you check with, but I think that's probably out of the scope.

Another point that will help you more than anything ever has is: you should use debugger to figure these things out. While you're running your app in debug mode, put a break point at the start of the loop by pressing F9. After that, go step by step with F10 until you figure out what the problem is.

In this case, you might specifically want to put a break point on the

```
if (ShadowChecker.Intersects(r))

```

And see what the values of *ShadowChecker* and *r* are at the moment and why this returns true. This should take you closer to the root cause of your problem.

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: What is the difference between GetComponent() and Find() in Unity?
I'm just learning to develop in Unity. One simple thing I'd like to do is change the colors of objects programmatically. I have a compound asteroid prefab object, in which the meshrenderer and material is inside the child component asteroid\_prop\_01.

After reading the Unity docs and previous programming posts, I was able to do this successfully with `GameObject.transform.Find()`, but I don't understand why `GameObject.Find()`, `GameObject.transform.Find()` and `GameObject.GetComponent()` are not equivalent.

I'd really appreciate an understanding of the difference. E.g. all these methods are based on the particular GameObject instance assigned to clone, so why aren't they all returning the same specific instance of clone.prop\_asteroid\_01.renderer.material.color?

```
eGameObject clone = (GameObject) Instantiate (hazard, spawnPosition, spawnRotation);
// This works
clone.transform.Find("prop_asteroid_01").renderer.material.color = Color.blue;
// This fails at compile time: "Static member `UnityEngine.GameObject.Find(string)' cannot be accessed with an instance reference, qualify it with a type name instead"
clone.Find("prop_asteroid_01").renderer.material.color = Color.blue;
// Fails with runtime error "Object reference not set to an instance of an object"
clone.GetComponent("prop_asteroid_01").renderer.material.color = Color.blue;

```

Thanks for your help.

# Answer
So `GameObject.Find()` and `Transform.Find()` are used to find an **active** game object, or child, within your scene(and in that respective order). Before we go any further, recognize the difference between a GameObject, Component, and the relationship between parents and children when using Unity.

# **Getting our Definitions Straight**

Think of a GameObject as an empty container. You can fill this container with whatever you want. Let's say a MeshFilter and MeshRenderer. These are components. They are components of the object. Scripts? Those are components too(they are referred to as behavior components)! You can also attach other GameObjects to this game object creating a parent - child relationship and thus creating a hierarchy.

## I kinda get it

Let me attempt to make this explanation a bit more easier to visualize:

Hierarchy:

```
Parent Object (Character)
       [   Transform     ] (Component)
       [   Mesh Renderer ] (Component)
       [   Mesh Filter   ] (Component)
       [ Movement Script ] (Behavior Component)
                          .../RHand (GameObject/Child/Prefab)
                          .../LHand (GameObject/Child/Prefab)
                          .../Eye   (GameObject/Child/Prefab)
                          .../RLeg  (GameObject/Child/Prefab)
                          .../LLeg  (GameObject/Child/Prefab)

```

So you have a GameObject. A container to store the children(GameObjects or Prefabs), the components(provided out of the box by Unity) and the behavior components that you make. The GameObject at the highest level is considered the parent and the objects that fall in line below are, you guessed it, child objects! Pretty simple concept to grasp, right?

### OK, OK, but why doesn't that code run!?

Finding out why your code doesn't work is the first step to a solid understanding, besides having correct definitions of course! I'll start from the top.

You do:

```
GameObject clone = (GameObject) Instantiate (hazard, spawnPosition, spawnRotation);

```

You probably know why this works. You have a variable, clone, which is of type GameObject and you are "cloning" or "duplicating" the GameObject hazard into the clone variable. That's what Instantiate does. It makes a copy.

```
    // This fails at compile time: "Static member `UnityEngine.GameObject.Find(string)'
    // cannot be accessed with an instance reference, qualify it with a
    // type name instead"
    clone.Find("prop_asteroid_01").renderer.material.color = Color.blue;

```

Now would be a great time to talk about instance methods, and static methods. Static Methods can be accessed without having an initialized instance of said type. You just need the type name, and the correct function name and it will allow you to use it without error. What you're doing in this line is attempting to use a non-existent instance function. GameObject.Find is a static function, not an instance function! gameObject is an instance of GameObject. "GameObject" alone is the type, and can be used to access those static methods! Not only that - but this is the incorrect use of `GameObject.Find`. This particular function does not concern itself with child object. That is the job of transform.Find

```
// Fails with runtime error "Object reference not set to an instance of an object"
clone.GetComponent("prop_asteroid_01").renderer.material.color = Color.blue;

```

Remember those definitions? Is a component a gameObject(of course this varies from engine to engine, but we are talking about Unity). **No!** So what would you use to find the child of the parent object(clone)?? I told you in the paragraph above. Use transform.Find. This is not a static method, so it requires an instance of type Transform!
> 6 votes

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


# Question
Title: How I get the value from different class
i get error , i cant get the value from different class..

```
public class First1 : MonoBehaviour {
    private List<IFirstListener> listeners = new List<IFirstListener>();
    public int watt;
    void OnTriggerEnter2D(Collider2D theCollider)
    {
        try {
            CharacterA characterA = theCollider.GetComponent<CharacterA>();
            this.watt += characterA.watt;
            for (int i = 0; i < listeners.Count; i++) {
                listeners[i].OnBaterryPluggedIn(this, characterA, characterA.watt);
            }
        }
        catch { /*On error do nothing*/ }
    }

    void OnTriggerExit2D(Collider2D theCollider) {
        try {
            CharacterA characterA = theCollider.GetComponent<CharacterA>();
            this.watt -= characterA.watt;
            if (characterA != null) {
                for (int i = 0; i < listeners.Count; i++) {
                }
                    listeners[i].OnBaterryPluggedOut(this, characterA, characterA.watt);
            }
        }
        catch { /*On error do nothing*/ }
    }

```

i want to get the value var watt and assign to tott.. (tott = watt)

```
public class Second2 : MonoBehaviour {
    private List<ISecondListener> listeners = new List<ISecondListener>();
    public int tott;

    public void cek (){
        tott = watt; /* <--- how i can get the value from var watt at class First() to var tott?? */
    }

```

# Answer
`watt` is an **instance variable** of class `First1`.

class `First1` is a `Monobehavior` so every "instance" of it must me attached to a `GameObject`.

The step in the order are:

1. Get a reference to the `GameObject` the specific instance you need of `First1` is attached to.
2. Get a reference to the `First1` component attached to the `GameObject`
3. Access the public field `watt`

It depends on how your scene is organized, a simple way of doing something like that:

```
GameObject go = GameObject.Find("name of the GO where First1 component is attached");
First1 comp = go.GetComponent<First1>();
tott = comp.watt;

```
> 0 votes

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


# Question
Title: What's the name of the "Candy Crush" style of game?
I'm currently creating an engine trying to auto-play games with a chess board, and I'm writing a report about it now.

However, I found it hard to properly describe it -- for the games like Candy Crush, which has a game board, filled with "candies," and a few rules.. is there a formal classification for it?

Is "board-game" a proper name? What about "rectangle-tile game", or "chessboard-based game?"

# Answer
> 7 votes
Games like Candy Crush are called "Match-three" games, and generally, it and games like it are tile-based games, or board games, or even tile-based board games.

---
Tags: game-design
---


# Question
Title: How can I determine the contact point of a collision?
I have two Farseer bodies. A static rectangle and a dynamic ball that is flying around. I want to determine where the ball touched the rectangle. I need the exact coordinates of the contact point.

How can I do that? Is there a way to determine the contact point?

```
 bool BlueRectangle_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
   {
       if (fixtureB.Body == RedBall)
       {
          Vector2 normal;
          FixedArray2<Vector2> worldPoints;
          contact.GetWorldManifold(out normal, out worldPoints);

          if(contact.Manifold.PointCount >= 1)
          {
            Vector2 contactPoint = worldPoints[0];
          }
        }

        return true;
    }

```

It works with the following code.

# Answer
> 1 votes
Get the list of contacts for each body by walking the contact list (a linked list). Note that a Contact might not actually be touching, it might *almost* be touching. A contact can also be disabled.

```
ContactEdge ce = body.ContactList;
while(ce != null)
{
    Contact contact = ce.Contact;
    if(contact.IsTouching() && contact.Enabled)
    {
        /* ... do stuff with "contact" ... */
    }
    ce = ce.Next;
}

```

You can also get contacts in some of the event handlers, like so:

```
bool MyOnCollisionHandler(Fixture fixtureA, Fixture fixtureB, Contact contact)
{
    /* ... do stuff with "contact" ... */
    return true;
}

```

Note that an event handler can disable a contact if it returns false. Also note that the `OnContact` event triggers when touching first becomes true (so there's no need to check it). See the Farseer source code for `Contact.Update` to see exactly how this works.

A contact can be touching at a single point (as in your example, or a point resting on a line). Or it can be touching along a line between two points (eg: two lines on top of each other). Get these points like so:

```
Vector2 normal;
FixedArray2<Vector2> worldPoints;
contact.GetWorldManifold(out normal, out worldPoints);

```

This gives you a list of contact points (in world space), containing between 0 and 2 points (with the count stored in `contact.Manifold.PointCount`), and the normal (direction) of the contact.

If you strictly need a single point, you can do this:

```
if(contact.Manifold.PointCount >= 1)
{
    Vector2 contactPoint = worldPoints[0];
}

```

Otherwise, use a loop to get either zero, one or both points.

# Answer
> -1 votes
I had the same problem and used the following pixel collission which I found on the net (sorry i dont know who made that, sorry for no credits :D) and modified it a little.

The 2 Gameobjects checking first, whether they are allowed to collide and then it itereates about the overlaying pixels of object something and target.

```
private bool PixelCollisionDetection(GameObject something, GameObject target)
    {
        // Find the bounds of the rectangle intersection
        int top = Math.Max(something.Rectangle.Top, target.Rectangle.Top);
        int bottom = Math.Min(something.Rectangle.Bottom, target.Rectangle.Bottom);
        int left = Math.Max(something.Rectangle.Left, target.Rectangle.Left);
        int right = Math.Min(something.Rectangle.Right, target.Rectangle.Right);

        if (!target.DoesCollideWith(something.GetType()) && !something.DoesCollideWith(target.GetType()))
        {
            return false;
        }

        if (!something.Rectangle.Intersects(target.Rectangle))
        {
            return false;
        }

        // Check every point within the intersection bounds
        for (int y = top; y < bottom; y++)
        {
            for (int x = left; x < right; x++)
            {
                // Get the color of both pixels at this point
                Color colorA = something.SpriteData[(x - something.Rectangle.Left) +
                                     (y - something.Rectangle.Top) * something.Rectangle.Width];
                Color colorB = target.SpriteData[(x - target.Rectangle.Left) +
                                     (y - target.Rectangle.Top) * target.Rectangle.Width];

                // If both pixels are not completely transparent and attackColors match...
                if (colorA.A != 0 && colorB.A != 0)
                {
                    target.CollisionWith(something, new Vector2(x, y));
                    something.CollisionWith(target, new Vector2(x, y));
                    return true;
                }
            }
        }
        // No intersection found
        return false;
    }

```

The method CollissionWith(... part is interesting for you, since there I get the exact point of collission, or at least the first, if there are more than one :D

---
Tags: xna, c#, farseer-physics-engine
---


title: How to get all points within a box?

text:
# Question
Title: How to get all points within a box?
What is the fastest way to get all of the points within a bounding box? If I had an `ArrayList<Point>`, and they weren't mapped to coordinates, would I have to loop through every point to see if it is in those bounds? Is there a faster way?

# Answer
This really depends on two things.

One - Is your box axially aligned? (ie. Is there a face pointing up, down, left, right, forward and back, or is it rotated ?)

Two - Are your points at all sorted?

If you are using an axially aligned box, you can skip this first step. Work out a Quaternion which defines the rotation of the box. From now on, when I refer to a point, I am talking about the point after being rotated by this Quaternion. If you have any difficulties with this step, google it, Quaternions are a big topic which I'd rather not go into unless you need more info.

Next it's pretty straight forward. Loop through the items and work out if their x is more than the box.minX and less than box.maxX (as with Y and Z). If this is true, then it is within the box.

There are a few ways you could speed these up, if your points are sorted in such a way that allows you to conclude at some point, that no more of them will be within the box, you can skip out. For example, if the box is at the origin (0, 0, 0) and your points are sorted in distance from the origin, it will reach a stage where you can conclude that all points left in the list are too far to even both doing checks, and therefore can break out of the loop.

Really there's no extremely fast ways of solving this problem when the points are stored in simply a List.

**TLDR;** minx \<= x \<= maxX && miny \<= y \<= maxY && minz \<= z \<= maxZ. Google Matricies and Quaternions, possibly Octrees too.
> 1 votes

# Answer
I read the answer by @Randomman159 and am not going to repeat what is written there.

Two important tools for processing a large quantities of data in parallel are SIMD and the computation shader. These allow you to perform a lot of computation in parallel. Another tool used to improve performance with tasks that can be parallelized is multithreaded programming. You need to try them out and check the results before making a choice. Sometimes (for instance) writing to the graphics card memory is more time consuming than the benefit from using a computation shader.
> 0 votes

---
Tags: java, bounding-boxes
---


# Question
Title: Adding 'xna content project' reference to monogame project(visual studio 2013 pro)?
I want to add reference to an xna content project. Which should be like the content project reference we have in an xna windows game. I am on visual studio 2013. I got the xna extensions to work by following this method. http://jaquadro.com/2013/11/migrating-monogame-projects-to-vs2013-and-windows-8-1/

But i dont see an option to add content reference in visual studio 2013. I searched everywhere and couldnt find an answer. Is this even possible? Or am i running in the wrong direction?

# Answer
Normally XNA only works in VS2010, but you've already linked the solution to that problem.

Only certain project types can have content project references. So what you need to do is create an empty "XNA Game Library" project - just for building the content project.

Then either reference that empty project or manually modify the underlying `.csproj` file (or both) to just get the XNB files that you want.

See also this answer. The command-line MSBuild solution described there *may* even be able to be made to work without hacking around with Visual Studio.
> 1 votes

# Answer
I have the same setup like you.

Considering you have your Monogame Windows Project (or whatever plattform you are targeting) then simply follow:

1. Add new project

--\> MonoGame

--\> Monogame Content Project

--\> Rename it whatever you like to

Then you can add your content to the content project. Build it (this should create xnb files). Add reference to the content project in your game project. Now you can access your content with the Game.ContentManager.
> 1 votes

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


# Question
Title: Is it legal to allow users to install replacement game data containing real-world personalities?
I'm thinking of developing a game for iOS which will ship with fake sports personality data. So, for argument sake, let's say fake football player names.

On OS X and Windows games like this often allow for users to install fan-made databases - which essentially overwrites the game's default data with (fan-made) "real word" data, thus circumventing intellectual property / likeness usage issues for the developer(s).

Is this legal?

# Answer
For a definitive answer to this question, you should consult a lawyer that deals in intellectual property issues. He or she can advise you on the specific legal issues and the options you have to help protect yourself.

So, with the caveat that I am *not* a lawyer and this *is not* legal advice:

While it may *appear* that this is okay, given the wide variety of user-created mods you can find for various games that incorporate the likenesses of famous people or characters from popular games, et cetera, this is generally still considered a violation of one or more intellectual property laws (depending on what one is actually doing, the legal jurisdiction involved, and so on).

By supplying only the tools to potentially commit infringement, and allowing users to generate the infringing content yourself, you might not be directly culpable for the infringement. That said, in many jurisdictions (such as the US) you can be sued for just about anything. If somebody found this post and traced it back to your game, for which somebody had made an infringing mod for, they could in theory file suit against you or include you in a lawsuit for being complacent or for intentionally facilitating the IP infringement.

If you look, in fact, you'll find that many of the "big name" games that support modding include clauses in their license agreements requiring you, the user, not to make content that infringes upon somebody else's intellectual property rights. For example, the Skyrim Creation Kit EULA includes this passage in section 1 ("Restrictions on Use"):

> You shall not create any New Materials that infringe upon the rights of others, or that are libelous, defamatory, harassing, or threatening, and You shall comply with all applicable laws in connection with the New Materials.

Thus, you should consult a lawyer to discuss your options and whatever necessary verbiage you should add to your own EULA to help protect yourself.
> 2 votes

---
Tags: ios, copyright
---


title: How to make loss of control acceptable?

text:
# Question
Title: How to make loss of control acceptable?
Let's say the game we're talking about is some kind of platformer. With all the puzzles, mini-challenges and mechanics aspects it is very, very important to have good control over the character. A single mistake can lead to character death or some other unwanted result.

In some scenes complete control is the key to the victory. Quickly the player becomes involved in the process and every lag or mistake in input processing brings negative experience.

But what if loss of control is needed as a 'feature', it is intended? How can I prevent the players from raging about 'broken gamepad' or 'stupid buggy game'? I want the player to not only understand that it's intended, but also be somewhat happy with it, but can't find a way to show it the right way.

In other games I've seen two types of control loss so far:

1. Character is unable to do anything, unless animation sequence ends
2. Character executes some moves without player intervention (like cutscenes or end of stage, when character goes out the screen and you can't stop this).

# Answer
Make sure that there is a visual cue that the player is currently not in control.

When it is a non-interactive cutscene, you could remove the GUI during the cutscene and bring it back as soon as the player is in control again.

When the users control is impaired (but not completely disabled) during normal gameplay, for example because their character is poisoned or hallucinating, you should also accompany this with a visual cue. In a game where you see the player-character you could, for example, have some stars circling around their characters head. In a first person game, you could blur or distort the users vision.
> 8 votes

---
Tags: game-design, platformer, control, user-experience
---


# Question
Title: Carve river beds into existing 3d procedural generated terrain
Ok, I've read many threads around about procedural terrain generation with rivers and roads but they suggest approaches from zero to result.

I'd like to know if exists an algorithm to apply to an existing vertex structure which models it by adding rivers beds like cuts through the slope of a mountain for instance.

This approach should:

* not work on heightmaps, since my terrain is not generated with heightmaps
* modify the surface with randomness
* according to the heights (river sources should be higher and the flow should descend)
* be as realistic as possible (like not too many circular paths)

I have no needs for speedy algorithms. would be enought to have a separated algorithm to modify the surface so that I am not forced to do all the work during the creation of the terrain.

I tagged this question with c# because this project is written in c# using xna4.0 and in the case that someone knows any algorithms in different languages, c# is preferred (ye, this is optimism)

By the way, I'm looking forward to see if someone knows anything that could fit these needs

# Answer
Your question is quite broad and underspecified, so in this answer I'll focus on finding river flows.

Within the field of computational geometry there is quite a bit of research on the topic of drainage networks on a terrain. An overview can be found in section 3.5 of this article: Digital Elevation Models: overview and selected algorithms.

A useful starting point about drainage networks on triangulated irregular networks (TINs) - which sound like your existing vertex structure - is Yu et al., Drainage queries in TINs: from local to global and back again.

I should note that the methods used in that article only provide you with realistic drainage or waterflow networks. Subsequent effects of erosion of the terrain is not covered.
> 2 votes

# Answer
May I suggest that any reasonable 3d terrain can have a (set of) 2d heightfields draped over it. This was required for my project to form NPC path maps, unfortunately, I have found no references to the procedure - possibly because it amounts to

* identify all top surfaces
* group them into continuous meshes
* store connectivity between them.

For the additional part of erosion by rain, every cliff edge must be mapped to the location where it falls (in a different sheet of the surface).

Then one can run the 2d algorithms on the heightmaps so produced. The art lies in linking them together so sheet borders do not produce artifacts, and adding impact erosion at the base of each temporary waterfall.

As for the perceived requirement to be "during world generation", that is a multi-step process which most games do not want the player to see happening (unless one is doing a SimEarth style), your use of a pre-gen 3d terrain instead of a generated 2.5d heightmap adds only the complication of allowing underfolds.
> 0 votes

# Answer
Here is an algorithm off the top of my head. It requires a graph structure for the terrain mesh vertices that allows speedy access to the neighbors of a given vertex, i.e. all vertices in the same triangle as a given vertex. You should be able to create such a structure easily from the mesh data itself.

Then, 1) Find an appropriate starting vertex. You could pick this one randomly, but it probably needs to fulfill some restriction, being above water level and/or within a mountain range. Depending on what you know about your terrain, you can make a better guess.

2) Find all neighboring vertices connected to the current one. From the set of neighbors, choose the one with lowest elevation. Save the "steepest descent vector" from the current vertex to this one.

3) Apply a valley modification function to the positions of the nearest neighbors such that the current vertex is the one being shifted downwards most strongly, whereas vertices left and right to the current one are shifted less and those ahead and behind are not affected. Can be done by some vector projections / dot and cross products.

4) Pick the next vertex for the algorithm based on a mix of the steepest descent vector (this will make the valley follow the gradient of the terrain) and the previous descent vector (I'm calling this flow vector now). This introduces a bit of inertia since it means the river will have a tendency to stick to it's flow direction. The amount of mixing will control the curvature of the resulting river.

Now proceed with 2) - 4) again until some stopping criteria is met (having reached the ocean or something similar).
> 0 votes

# Answer
I would recommend considering a technique inspired by seam carving. Look for the least expansive path through the terrain from any side to the opposite side (for instance north to south). The way you'll calculate price in this case is by the `y` value of the vertices you pass through (their height). Once you have a list of these vertices, lower them slightly deeper by `N` units. Pick a `W` that will be the width of your new river in units and now find all vertices that are less than `W/2` units away from the path you found. Now using their distance `d` from the path, lower each of these vertices by:

```
N * sqrt((W - d) / W)

```

You can use any `foo` you like instead of sqrt. You may want to use the original `y - W` as a base value to calculate the height of the vertices in the river. In that case it would be:

```
base = y - N; //Done for each vertex on the path.
              //Nearby vertices will use the weighted average
              // of the two closes vertices on the path.
vertex.y = base + N * (1 - sqrt((W - d) / W));

```
> 0 votes

---
Tags: c#, 3d, algorithm, procedural-generation
---


# Question
Title: Distorted LookAt When Looking Up or Down?
I have a weird problem and I have no idea what's going on with it.

Recently started doing some OpenGL programming, going pretty well, hit some rough spots but worked my way through them and otherwise pretty happy! But I've hit a roadblock with something that has me confused as hell.

I'm doing an OpenGL 4 based rendering system, it's early days and I've got some basic stuff like 3D model importer happening, but I've been having some problem with the maths involved in creating my own "LookAt" function like present in OpenGL 2. I've created my own Matrix & Vector class, I think most of the functions are right but the LookAt does something weird when looking at different angles.

For a simple test to show what happens, I created a slowly moving focus point for the lookat that starts off a few units ahead of the camera, then slowly moves closer and closer till it's 1 unit below the camera. As the focus point comes closer to the point of looking straight down, for some reason it's like the field of view is narrowing?

It eventually zooms in so close that all you can see is one solid colour covering the entire screen, whatever pixel just happens to be on the ground directly below the camera as it zooms in with a field of view of basically 0 degrees.

It may be nothing to do with field of view at all but I don't know and hence why I'm here. Here is some related code to the problem, forgive me if these implementations are not perfect, again I'm just starting out and I don't know the best methods yet, still learning:

My function for calculating a lookAt:

```
public static Transformation lookAt(Vector position, Vector target, Vector updirection) {
        Transformation lookAt = new Transformation();

        Vector vz = position.clone();
        vz.subtract(target);
        vz.normalise();

        Vector vx = Vector.xProduct(updirection, vz);
        vx.normalise();

        Vector vy = Vector.xProduct(vz, vx);

        lookAt.m[0] = vx.x; lookAt.m[1] = vy.x; lookAt.m[2] = vz.x; lookAt.m[3] = position.x;
        lookAt.m[4] = vx.y; lookAt.m[5] = vy.y; lookAt.m[6] = vz.y; lookAt.m[7] = position.y;
        lookAt.m[8] = vx.z; lookAt.m[9] = vy.z; lookAt.m[10] = vz.z; lookAt.m[11] = position.z;
        lookAt.m[12] = 0; lookAt.m[13] = 0; lookAt.m[14] = 0; lookAt.m[15] = 1;

        return lookAt.inverse();
    }

```

My function for calculating perspective:

```
public static Transformation perspective(double FoV, double aspectRatio, double nearClip, double farClip) {
    Transformation proj = new Transformation();
    double FoVR = Math.toRadians(FoV);
    proj.m[0] = FoVR/aspectRatio;
    proj.m[5] = FoVR;
    proj.m[10] = (farClip + nearClip)/(nearClip - farClip);
    proj.m[11] = 2*(farClip*nearClip)/(nearClip-farClip);
    proj.m[14] = -1;
    proj.m[15] = 0;
    return proj;
}

```

I use the function later on when generating a matrix to apply to the 3D letter G in the scene, like so:

```
Transformation MVP = new Transformation();

Transformation proj = Transformation.perspective(FoV, (double)canvas.getWidth()/(double)canvas.getHeight(), near, far);
MVP.multiply(proj);

Transformation view = Transformation.lookAt(cameraPosition, cameraFocus, cameraUp);
MVP.multiply(view);

Transformation model = Transformation.scaleRotateTranslate(objectScale, objectRotation, objectTranslation);
MVP.multiply(model);

```

And the MVP is simply sent to the shader and used as you'd expect to multiple against all the verticies/normals.

What do you think I'm doing wrong? What should I check first? Is there a better way of doing what I'm trying to do? Any help/answers at all is greatly appreciated, I just don't know what to go after first. The perspective/lookAt seems like it's almost working but something must be broken?

# Answer
I got help in another part of this website on a similar question which answered this one. As such I'm going to answer my own question here and supply the answer I was given just to close this.

So what I really needed was a working LookAt function, I'm still not sure what exactly was causing the problem I had before with the weird distortion other than simply using the wrong method. But my new LookAt function DOES work and make more sense so I'll supply the code.

I received my answer in this question, the info I was given was very helpful and worth checking out:

3D Camera Rotation

New "lookAt" function:

```
public static Mat4 lookAt(Vec4 position, Vec4 target, Vec4 updirection) {
    Vec4 zaxis = position.minus(target).normalise();
    Vec4 xaxis = Vec4.crossProduct(updirection, zaxis).normalise();
    Vec4 yaxis = Vec4.crossProduct(zaxis, xaxis);

    Mat4 orientation = new Mat4(new float[] {
        xaxis.x, xaxis.y, xaxis.z, 0,
        yaxis.x, yaxis.y, yaxis.z, 0,
        zaxis.x, zaxis.y, zaxis.z, 0,
        0,      0,      0,      1
    });

    Mat4 translation = Mat4.translation(-position.x, -position.y, -position.z);

    return orientation.multiply(translation);
}

```

**Disclaimer:** But before you use that code, do check the other link, as this seems to work but for all I know it may have a hidden problem in it, so check the other info first!
> 0 votes

---
Tags: opengl, java, matrix, perspective, jogl
---


title: Preload in cocos2d v3

text:
# Question
Title: Preload in cocos2d v3
I'm trying to create a preload, but i don't know how to implement the code of this topic in cocos2d iphone v3. Since CCTextureCache has changed to CCTexture, and doesn't have sharedTextureCache property anymore.

```
@interface TextureHelper : NSObject
+ (void) preloadTextures;
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName;
@end

@implementation TextureHelper
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName {
    return [[CCTextureCache sharedTextureCache] textureForKey:imageName];
}

+ (void) preloadTextures {
    // or could read from a directory...
    NSArray *imageNames = @[
    @"myImage1.png",
    @"myImage2.png"
    ];

    for (NSString *imageName in imageNames)
        [[CCTextureCache sharedTextureCache] addImage:imageName];
}
@end

```

# Answer
Well, one way is to load the textures and keep a reference to them ourself. You could reimplement your code to something like:

```
@interface TextureHelper : NSObject
- (void) preloadTextures;
- (CCTexture2D *) textureForImageNamed:(NSString *) imageName;
@end

@implementation TextureHelper
{
    NSArray * loadedTextures;
}

- (CCTexture *) textureForImageNamed:(NSString *) imageName
{
    // TODO: Lookup loadedTextures and find the requested one.
    // Return a pointer to it. Probably use a NSDictionary...
}

- (CCSprite *) spriteForImageNamed:(NSString *) imageName
{
    // Create a sprite using the whole contents of the texture:
    CCTexture * tex = [self textureForImageNamed:imageName];
    if (!tex)
    {
        // TODO: Handle failure
    }

    CCSpriteFrame * frame = [tex createSpriteFrame];
    CCSprite * sprite = [CCSprite spriteWithSpriteFrame:frame];
    return sprite;
}

- (void) preloadTextures
{
    NSArray *imageNames = @[
        @"myImage1.png",
        @"myImage2.png"
        // your textures here ...
    ];

    for (NSString *imageName in imageNames)
    {
        CCTexture * tex = [CCTexture textureWithFile:imageName];
        [loadedTextures addObject:tex];
    }
}

@end

```

You'll probably want to use a dictionary to store the textures and index them by name, but you can get the ideia from the code above. CCSprite also has *spriteWithTexture / initWithTexture* that you can use in conjunction.
> 1 votes

---
Tags: cocos2d-iphone, cocos2d, objective-c, assets
---


# Question
Title: Transparency in opengl - texture with alpha, color from background
I have to draw texture with transparent areas on square. But I don't want this transparencies to take color from this polygon, but from the background. Do you have any good tutorial to achieve it?

--EDIT--

```
   glColor4f(1,0,0,1);

  glBegin(GL_QUADS);

  glTexCoord2f(0,0); glVertex3f(-0.5, -0.5, -1);
         glTexCoord2f(1,0); glVertex3f(1, -1, -1);
         glTexCoord2f(1,1); glVertex3f(0.5, 0.5, -1);
         glTexCoord2f(0,1); glVertex3f(-0.5, 0.5, -1);

  glEnd();

```

I just takes color from polygon. How to make this polygon transparent.

# Answer
OpenGL provides blending function.

```
glEnable(GL_BLEND);// you enable blending function
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// then you will set flags to achieve desired blending effect.

```

For further different usage, read http://www.opengl.org/sdk/docs/man/html/glBlendFunc.xhtml

However for your particular case, the desired effect, applying transparency, I believe you want...

"...Examples Transparency is best implemented using **blend function (GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA)** with primitives sorted from farthest to nearest. Note that this transparency calculation does not require the presence of alpha bitplanes in the frame buffer."
> 1 votes

---
Tags: opengl, textures, transparency
---


# Question
Title: How to remove line between two Points XNA 4.0?
I'm new to XNA and wondering if it is possible to remove a line (that lies between two vectors) when the mouse clicks on that line. I've searched everywhere but I can't seem to find anything.

My extension method in class `CreateLine`:

```
public static class CreateLine
{
    public static void DrawLine(this SpriteBatch spriteBatch, Texture2D texture, Vector2 startVector, Vector2 endVector, Color color)
    {
float length = Vector2.Distance(startVector, endVector);
        float angle = (float)(Math.Atan2(startVector.Y - endVector.Y, startVector.X - endVector.X));
     spriteBatch.Draw(texture, new Rectangle((int)startVector.X, (int)startVector.Y, length, 3),
              null, color, angle, new Vector2(0, 0), SpriteEffects.None, 0);
    }
}

Texture2D boxSprite;
Vector2 sVector1 = new Vector2(100, 200);
Vector2 eVector1 = new Vector2(100, 400);
Vector2 sVector2 = new Vector2(240, 300);
Vector2 eVector2 = new Vector2(350, 300);
Vector2 sVector3 = new Vector2(200, 100);
Vector2 eVector3 = new Vector2(200, 150);
Vector2 sVector4 = new Vector2(500, 90);
Vector2 eVector4 = new Vector2(390, 90);
MouseState previousMouseState;
MouseState currentMouseState = Mouse.GetState();

```

In the `LoadContent()` method:

```
protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    boxSprite = Content.Load<Texture2D>("boxSprite"); //// this is a 1x1 white box
 }

```

In the `Draw()` method

```
protected override void Draw(GameTime gameTime)
{
    spriteBatch.Begin();
    spriteBatch.DrawLine(boxSprite, sVector1, eVector1, Color.Yellow);
    spriteBatch.DrawLine(boxSprite, sVector2, eVector2, Color.Orange);
    spriteBatch.DrawLine(boxSprite, sVector3, eVector3, Color.Green);
    spriteBatch.DrawLine(boxSprite, sVector4, eVector4, Color.Pink);
    spriteBatch.End();
    base.Draw(gameTime);
}

```

Now I am currently trying to remove each line if I click on it using the mouse.

```
protected override void Update(GameTime gameTime)
{
    mouseState = Mouse.GetState();
    Rectangle sV1Rectangle = new Rectangle(sVector1.X, sVector1.Y, boxSprite.Width, boxSprite.Height);`

```

The rectangle is supposed to contain this line in the draw method \>\>\>\> `spriteBatch.DrawLine(boxSprite, sVector1, eVector1, Color.Yellow);`

```
if (mouseState.LeftButton == ButtonState.Pressed && prevMouseState.LeftButton == ButtonState.Released)
{  if (sV1Rectangle.Contains(mouseState.X, mouseState.Y)
  {
     // HOW DO I REMOVE THE LINE I JUST CLICKED ON???
     // HOW DO I REFER TO THIS LINE >>>> spriteBatch.DrawLine(boxSprite, sVector1, eVector1, Color.Yellow); OR ANY OTHER LINE I CLICK ON?????
  }
}

    previousMouseState == currentMouseState;
    base.Update(gameTime);
}

```

I was going to use the `list.remove/removeAt()` method remove the sprite(s), but I couldn't because I am using `vector2`s to draw the line(s).

Can someone give me advice?

# Answer
I am not sure if you are trying to draw sprites (images) or points, but for sprites you should use the spriteBatch.Draw(,,); function, where the first parameter points to a Texture2D object, the second to a Vector2 and the third to a color for further effects. The color can be taken from the Colors item, which is built into the XNA, normally you would put Colors.White for no effect on the sprite. You should be able to find all the documentation in the XNA 2D tutorial in MSDN: http://msdn.microsoft.com/en-us/library/bb203893.aspx
Drawing single pixels turns out to be harder than it seems, as you can see on this thread: http://social.msdn.microsoft.com/Forums/en-US/dd40c33d-c617-4eef-85ad-9d9eaca4e86a/drawing-just-one-pixel
However you could create a 1x1 sprite and then draw that, maybe a white one so you could reuse it for every occasion by changing the color parameter of the Draw method.
Now, if you are trying to remove an already existing line, I am pretty sure that it is being redrawn in every frame, so maybe you just have to put a condition in the code that will just not draw it? I really can't guess what you have in mind so maybe if you could tell us what's the nature of this part of your project someone could give you an exact answer.
> 0 votes

---
Tags: xna, vector, lines
---


title: How to predict physics movement

text:
# Question
Title: How to predict physics movement
How to predict the movement of the body when a force is applied on it like in the https://play.google.com/store/apps/details?id=com.game.basketballshoot

I have attached screen shot as reference.

# Answer
> 2 votes
The simplest way to find out how a physics-based sequence would turn out is to simulate it. Sample the positions as you go and draw indicators on suitably spaced places.

This works regardless of the model you're using, may it be an actual simulation or some simplified model like "follow this parabolic path".

---
Tags: physics
---


# Question
Title: Navigating Libgdx Menu with arrow keys or controller
I'm attempting to make my menu navigable with the arrow keys or via the d-pad on a controller. So Far I've had no luck.

**The question is**: *Can someone walk me through how to make my current menu or any libgdx menu keyboard accessible?*

I'm a bit noobish with some stuff and I come from a Javascript background.

Here's an example of what I'm trying to do:

http://dl.dropboxusercontent.com/u/39448/webgl/qb/qb.html

For a simple menu that you can just add a few buttons to and it run out of the box use this:

http://www.sadafnoor.com/blog/how-to-create-simple-menu-in-libgdx/

Or you can use my code but I use a lot of custom styles.

And here's an example of my code:

```
import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenManager;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.project.game.tween.ActorAccessor;

public class MainMenu implements Screen {

 private SpriteBatch batch;
 private Sprite menuBG;
 private Stage stage;
 private TextureAtlas atlas;
 private Skin skin;
 private Table table;
 private TweenManager tweenManager;

 @Override
 public void render(float delta) {
  Gdx.gl.glClearColor(0, 0, 0, 1);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

  batch.begin();
     menuBG.draw(batch);
  batch.end();

  //table.debug();

  stage.act(delta);
  stage.draw();
  //Table.drawDebug(stage);

  tweenManager.update(delta);
}

@Override
public void resize(int width, int height) {
  menuBG.setSize(width,  height);
  stage.setViewport(width, height, false);
  table.invalidateHierarchy();
}

@Override
public void resume() {

}

@Override
public void show() {

  stage = new Stage();

  Gdx.input.setInputProcessor(stage);

  batch = new SpriteBatch();

  atlas = new TextureAtlas("ui/atlas.pack");
  skin = new Skin(Gdx.files.internal("ui/menuSkin.json"), atlas);

  table = new Table(skin);
  table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

  // Set Background
  Texture menuBackgroundTexture = new Texture("images/mainMenuBackground.png");
  menuBG = new Sprite(menuBackgroundTexture);
  menuBG.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

  // Create Main Menu Buttons

  // Button Play
  TextButton buttonPlay = new TextButton("START", skin, "inactive");
  buttonPlay.addListener(new ClickListener() {
     @Override
     public void clicked(InputEvent event, float x, float y) {
        ((Game) Gdx.app.getApplicationListener()).setScreen(new LevelMenu());
     }
  });

  buttonPlay.addListener(new InputListener() {
       public boolean keyDown (InputEvent event, int keycode) {
               System.out.println("down");
               return true;
       }
  });

  buttonPlay.padBottom(12);
  buttonPlay.padLeft(20);
  buttonPlay.getLabel().setAlignment(Align.left);

  // Button EXTRAS
     TextButton buttonExtras = new TextButton("EXTRAS", skin, "inactive");
    buttonExtras.addListener(new ClickListener() {
         @Override
         public void clicked(InputEvent event, float x, float y) {
             ((Game) Gdx.app.getApplicationListener()).setScreen(new ExtrasMenu());
         }

    });
    buttonExtras.padBottom(12);
    buttonExtras.padLeft(20);
    buttonExtras.getLabel().setAlignment(Align.left);

    // Button Credits
     TextButton buttonCredits = new TextButton("CREDITS", skin, "inactive");
    buttonCredits.addListener(new ClickListener() {
         @Override
         public void clicked(InputEvent event, float x, float y) {
           ((Game) Gdx.app.getApplicationListener()).setScreen(new Credits());
         }

    });
    buttonCredits.padBottom(12);
    buttonCredits.padLeft(20);
    buttonCredits.getLabel().setAlignment(Align.left);

    // Button Settings
    TextButton buttonSettings = new TextButton("SETTINGS", skin, "inactive");
    buttonSettings.addListener(new ClickListener() {
         @Override
         public void clicked(InputEvent event, float x, float y) {
           ((Game) Gdx.app.getApplicationListener()).setScreen(new Settings());
         }

    });
    buttonSettings.padBottom(12);
    buttonSettings.padLeft(20);
    buttonSettings.getLabel().setAlignment(Align.left);

  // Button Exit
    TextButton buttonExit = new TextButton("EXIT", skin, "inactive");
  buttonExit.addListener(new ClickListener() {
     @Override
     public void clicked(InputEvent event, float x, float y) {
        Gdx.app.exit();
     }
  });
  buttonExit.padBottom(12);
  buttonExit.padLeft(20);
  buttonExit.getLabel().setAlignment(Align.left);

  // Adding Heading-Buttons to the cue
  table.add().width(190);
  table.add().width((table.getWidth() / 10) * 3);
  table.add().width((table.getWidth() / 10) * 5).height(140).spaceBottom(50);
  table.add().width(190).row();

  table.add().width(190);
  table.add(buttonPlay).spaceBottom(20).width(460).height(110);
  table.add().row();

  table.add().width(190);
  table.add(buttonExtras).spaceBottom(20).width(460).height(110);
  table.add().row();

  table.add().width(190);
  table.add(buttonCredits).spaceBottom(20).width(460).height(110);
  table.add().row();

  table.add().width(190);
  table.add(buttonSettings).spaceBottom(20).width(460).height(110);
  table.add().row();

  table.add().width(190);
  table.add(buttonExit).width(460).height(110);
  table.add().row();
  stage.addActor(table);

  // Animation Settings
  tweenManager = new TweenManager();
  Tween.registerAccessor(Actor.class, new ActorAccessor());

  // Heading and Buttons Fade In
  Timeline.createSequence().beginSequence()
     .push(Tween.set(buttonPlay, ActorAccessor.ALPHA).target(0))
     .push(Tween.set(buttonExtras, ActorAccessor.ALPHA).target(0))
     .push(Tween.set(buttonCredits, ActorAccessor.ALPHA).target(0))
     .push(Tween.set(buttonSettings, ActorAccessor.ALPHA).target(0))
     .push(Tween.set(buttonExit, ActorAccessor.ALPHA).target(0))

     .push(Tween.to(buttonPlay, ActorAccessor.ALPHA, .5f).target(1))
     .push(Tween.to(buttonExtras, ActorAccessor.ALPHA, .5f).target(1))
     .push(Tween.to(buttonCredits, ActorAccessor.ALPHA, .5f).target(1))
     .push(Tween.to(buttonSettings, ActorAccessor.ALPHA, .5f).target(1))
     .push(Tween.to(buttonExit, ActorAccessor.ALPHA, .5f).target(1))
     .end().start(tweenManager);

  tweenManager.update(Gdx.graphics.getDeltaTime());

}

public static Vector2 getStageLocation(Actor actor) {
   return actor.localToStageCoordinates(new Vector2(0, 0));
}

@Override
public void dispose() {
  stage.dispose();
  atlas.dispose();
  skin.dispose();
  menuBG.getTexture().dispose();
}

@Override
public void hide() {
  dispose();
}

@Override
public void pause() {

}

}

```

# Answer
> 1 votes
Unsure if you found an answer, but for anyone else who came here looking for one: Setting `Gdx.input.setInputProcessor(stage)` basically means the stage is getting all input signals. So to get your events to fire, you need to change

```
buttonPlay.addListener(new InputListener()

```

to

```
stage.addListener(new InputListener()

```

and do that for the rest of your buttons.

---
Tags: java, libgdx, menu
---


# Question
Title: Synchronizing mob states in online multiplayer game
I'm developing an exploration-based platform game in which from the start there were plans about including local multiplayer support, but recently I've been considering an online multiplayer mode, mainly because in local multiplayer, because I think it'd make players loose too much visibility to be worth it, I don't want to split the screen between players. It'd be akin to Spelunky.

But I really want for players to be able to explore rooms independently just as much as cooperatively (in the style of Kirby & the Amazing Mirror, for GBA), and online multiplayer would solve this problem of local multiplayer, but I've been wondering what exactly I could do about synchronizing the states of mob between the clients whenever the players are in different rooms. For example, what do I do when a player enters a room in which players were already meddling with the monsters and the evironment, how do I update him with everyone's states?

This question and its answers suggest that I keep a host which is constantly updating the various rooms with players and from them I can provide each client with only the significant data, but what significant data do I need to send my players? Before multiple rooms all that I needed to send was input and random numbers (not much, my game has fixed timesteps), but now I need to send *the whole data* of entities? After all, each creature has plenty of variables that influence in its AI and physics, as I'm dealing with a platformer.

What are the alternatives?

# Answer
When you have a multiplayer game, you have to be aware that the players are able to cheat with everything that is computed locally. When you want the game to be fair, you have no other option than to move all game mechanics (movement, mob AI, collision detection, damage calculation, ..., ... ) to a central server.

But let's assume that the community around your game is 100% free of cheaters and trolls, so no hacker feels like developing cheats (this assumption is likely very wrong when the community around your game grows beyond 100 people).

Under this assumption you could let each player play on their own and as soon as one or more players get near each other, the clients automatically elect a host. It should be the one of them with the lowest average latency to all other players who is not behind a NAT firewall. The host calculates all game mechanics and sends the results to the client(s). Note that when all clients are behind NAT, no multiplayer is possible without a centralized server.

The host doesn't need to inform the clients about the internal state of objects. It only needs to send the external state: What's the object, where is it and what is it doing right now. "Objects" in this context are everything that has a visible state: mobs, interactive objects and player-characters. Sometimes, though, it might be useful to keep clients informed about certain details of internal states, when these details are useful for client-sided prediction of actions to make the game appear less laggy (when clients know a certain mob will turn around as soon as it reaches a certain point, they can do that before receiving that information from the server).
> 1 votes

# Answer
You will send the entire state of the given simulation to any player who joins. That does not mean you need to send the entire representation of the host/server representations, but you do need enough that the client can accurately render and interact within the simulation. This might include things like:

* Sprites
* Names
* Position
* Velocity
* Bounding sizes
* Statistics (useful if you want to show information on a mobile)

Some information is not as useful to a client, such as:

* Damage computations and formulas (the server can do most of these)
* State that is only used on the server side

That being said, once you have sent the states you will continue to need to send deltas. That is, send changes that have occurred to your mobile from list 1 so that the clients may stay accurate.
> 0 votes

---
Tags: c++, multiplayer, sfml, state, online
---


# Question
Title: Viewing one of multiple worlds in a component entity system?
I've been working on a space simulation game. The player can control a ship and fly through wormholes to get from one solar system to another. I would like the player to be able to switch the camera view between the different solar systems they own something in (world, factories, defenses, etc).

If am using just one component entity world then how do I tell the rendering system that looks for sprite components to only draw the sprite components of one solar system?

I could add a "solar system id" field to each sprite component and have the rendering system check each component before rendering to make sure it's in the "active" solar system. It doesn't seem like a good idea though. Mostly because I'd be adding another if case before processing every single sprite, at the very least (other components may need similar checks).

I could have the rendering system maintain an internal map of which solar system contains which entities, but then I have to write entity systems that keep track of all the entities, which is my entity system framework's job (Artemis for Java).

Currently I am planning on making all of the solar systems separate from each other. They wouldn't exist in the same coordinate system. I suppose I could instead put everything on the same coordinate system and just move the camera around based on which solar system the player wanted to view at that time. The problem with that would be that my sprite rendering system would still be looping through all the sprites in the game, instead of just the ones at the active solar system.

So, for lack of better options, I'm leaning toward using multiple component entity worlds. So each solar system would get its own set of systems (including the rendering system), and I'd set which one was active to enable the rendering systems for that solar system.

I didn't want to take this approach for two reasons. First, it adds another layer of complexity on top of everything. Second, it seems like it might lessen some of the performance benefits (caching) of looping through all the same types of components and running the same entity system algorithm. Instead of doing a breadth-first loop through all the components it would be more of a depth-first loop through all the systems' components.

So what is the best way to handle this?

# Answer
That depends, like you pretty much said yourself, on how much change you are willing to make to your code base. I'll give you one suggestion I've used before and have liked. Some pseudocode:

```
class Sprite { ... };

// You can have several instances of this one
class World {

    SpriteList renderQueue;

    void DrawSprite(Sprite s)
    {
        renderQueue.Push(s);
    }
};

// This one can be a singleton
class Renderer {

    void DrawWorld(World w)
    {
        for each sprite in w.renderQueue
        {
            // Perform draw calls to your rendering API. I.e.: OpenGL/D3D
        }
    }
};

// Then in the game code:

currentWorld.DrawSprite(playerShip);
currentWorld.DrawSprite(alienShip);
currentWorld.DrawSprite(asteroid);
// etc...

Renderer.DrawWorld(currentWorld);

```

One nice side effect is that you get a render queue for free, which can be used to sort your sprites/geometry according to some criteria before actually drawing. Better still, if you take some care, you can multithread your rendering by adding the sprites to the worlds in parallel, if the worlds are unaware of each other. Then you serialize when issuing the Renderer.DrawWorld() calls.
> 1 votes

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


# Question
Title: Disable depth testing for only some faces
I have some meshes and I need to be able to draw some part of them without depth test. Is it possible to turn off depth testing from within shader, wo that some parts will be rendered no matter what depth is in z-buffer ?

Or transform Z, W somehow to fake this ?

# Answer
The most robust way to do this is probably to split your geometry into two separate draw calls, one with depth testing and one without.

That said, if you want to do it in one batch...

1) If the depth override is set on a per-vertex level, you can do something like this in your vertex shader:

```
output.position = mul(worldViewProjectionMatrix, vertex.position);
if(vertex.forceDraw)
{
   output.position /= output.position.w;
   output.position.z = 0.0f;
   // might need to be -1.0f? I can't recall where the near plane maps to...
}

```

This should take the vertices that are supposed to render in front of everything and snap them to the near plane, without affecting their projected position on-screen. You'll still benefit from early depth testing this way. If you have polygons that include some always-drawn vertices and some regular ones, then that polygon may get cut partway along by other geometry.

2) If the depth-overriding is decided per-fragment, you can set the fragment depth in the fragment shader. Something like...

(Disclaimer: It's been a while since I messed with fragment depth, so think of this as a rough guide, not a copy-and-paste-ready sample. Always check what's appropriate for your language/environment of choice)

```
void frag(vertOutput input, out float4 color : COLOR, out float depth : DEPTH)
{
   fragOutput output;
   color = input.color;
   if(shouldIOverrideDepth(input))
   {
      depth = 0.0f;
      // might need to be -1.0f?
   }
   else
   {
      depth = input.position.z/input.position.w;
      // You may need to convert this to a different range.
   }
}

```

This will pass-through the expected depth for regular fragments, but replace it with the nearest depth for selected fragments.

This will disable early-z testing on everything drawn with this shader, which is bad for performance. So, consider splitting your geometry so that this shader is only used where absolutely necessary.

---

Note that both of these approaches will write super-near depths into the depth buffer for the affected fragments, if depth writes are enabled. If this is undesirable, you can disable depth writes for this shader, at the risk of later draw calls drawing over this content incorrectly.

(Both these approaches can work branch-free, but I've shown them with branches so it's clearer what's happening)
> 2 votes

---
Tags: shaders, depth-buffer
---


# Question
Title: How do I handle window resizing in SlimDX?
I'm considering the use of SlimDX in a managed Windows Forms Application. Available with DirectX is DXUT. I use DXUT to handle events such as window resizing and 'lost devices.'

How well does SlimDX account for these occurrences? If I were to use SlimDX, how would I account for the functionality of DXUT in managed code?

# Answer
> 0 votes
SlimDX is a lightweight wrapper around DirectX APIs, and DXUT isn't a core DirectX API. Thus, SlimDX doesn't wrap it.

If you want to deal with window management, resizing, et cetera, you have to do that yourself using the Windows Forms API. When your form handles a resize event, you may need to deal with resizing your back buffer or viewport, depending on your specific needs.

Note that "lost device" scenarios are *not* something core to DXUT, they are an aspect of Direct3D 9 and are perfectly supported by SlimDX in basically exactly the same way you'd handle them natively.

---
Tags: c#, directx9, slimdx, windows-forms
---


# Question
Title: Count number of CCNodes of a certain class on a layer
Pretty simple question. I'm working in Objective C (cocos2d) and I'm trying to count the number of a sprites of a certain class are present on the current layer being displayed. For example, I have a class named `Seal` which is a subclass of of `CCNode` and in my current layer I want to count how many instances of type `Seal` are present.

I know how to count the number of children of the layer by doing

```
int numberChildren = [[self children] count];

```

which correctly returns the number of children on the layer. But I just want the number of `Seal`s on my layer. How could I do this? Thanks =)

# Answer
Do as ryrich said, however the actual code on Objective-C would be something like this: *(Assuming your CCNode class is called "Seal")*

```
int sealCounter = 0;
for (id *node in self.children) {
    if ([node isKindOfClass:[Seal class]]) {
        sealCounter++;
    }
}

```
> 2 votes

# Answer
I come from a C# background, so I can't write you the code (don't want to give you gross, translated Objective-C code :))

But what you could do is loop through the Children (`[self children]`), check if they can be casted as a `Seal`. If the casted object is not `null`, increment a counter. Then just return the counter after the loop is finished.

Hope this helps!
> 0 votes

---
Tags: ios, cocos2d-iphone, objective-c, xcode
---


title: Best way to test simple cases in games

text:
# Question
Title: Best way to test simple cases in games
When designing and play-testing a new game, a lot of the time, the people trying out functionality get used to things, and no longer try the "dumb ways" any more. So if the development breaks something, it may be a feature only a new user would bother trying. What are some of the best ways to make sure that your game has its "stupid cases" tested when it's finally released, or after a major update? Methodology, software assistance, maybe even sites where people will play-test for you, et ceteras.

# Answer
> 9 votes
A few things I would say are important:

**Encourage Programmer Unit Testing**

This will make sure that certain stupid bugs, if there is a unit test for them, won't recur, because the unit test will fail if they do. This requires a change in programming methodology, but in my opinion it is completely worth it.

**Automate Whatever Testing You Can**

Beyond unit testing, create a set of automated function and acceptance tests that are run on every build to make sure certain builds are good. If you have scriptable controls and your game is generally consistent, you can test lots of bugs automatically.

**Create A Multi-Level Test Plan**

Make sure that your testers have a test plan that tests the most important bugs. This should be multi-level:

* Smoke Test: Tests that the game doesn't crash in the most common cases.
* Regular Test: Tests more uncommon cases.
* Soak Test: Run as deep as you can, regressing as many common bugs as possible. Also test that the game can stay on for very long periods of time (days) without crashing.

Create this test plan and follow it on every build.

# Answer
> 11 votes
A sort of code coverage approach to test cases can be done using simple flags that are tripped once the block of code has been executed in-game. Displaying which flags have been tripped and untripped on screen can allow testers to know which cases have been covered and which haven't.

Simple as it is, it's still effective so long as the flags have meaningful names so the testers can figure out what's supposed to be done.

This technique is credited to Matthew Jack who implemented it in Crysis.

# Answer
> 3 votes
Several good answers here on the programming side. I'll add one that's more design oriented.

**Have your system designers write edge case test plans for testers**

If they know what they are doing, the person behind designing a system, or scripting an in-game sequence, is very likely to know the edge cases of that system, and where it might break down. They should also have an idea of where the system interacts with others. Having them write out a test plan, or discuss with the testers where things are likely to go wrong can save everyone time.

# Answer
> 1 votes
You should investigate so-called Monkey Testing. It can catch a lot of the bugs of this type:

https://secure.wikimedia.org/wikipedia/en/wiki/Monkey\_test

You also need to organize user experience testing with "Kleenex testers", testers that see your game for the first time and that you will never use again. It's a bit expensive and complicated to organize, but well worth the effort. If you do, film every test with 3 cameras: one on the screen, one on the controls and one on the tester's face in order to detect frustration.

# Answer
> 1 votes
Great question, every response in this thread is an excellent response. One thing to add:

In my experience (30 years of software development): apps and games are more reliable if at least one member of the test group is a skilled *gorilla tester*, masterful at ad-hoc testing, abusing apps and deliberately using games the wrong way to find bugs of the kind described by the original poster. Gorilla testers have an uncommon skill -- when you find a good one, keep them on your team.

For an example of effective gorilla testing see: www.youtube.com/watch?v=8C-e96m4730 ;)

To sum up the responses in this thread: **effective software quality strategies are multi-faceted**, combining multiple approaches to achieve a high level of confidence in the functional quality and reliability of your game.

# Answer
> 0 votes
An interesting trick I heard about from a friend to test graphics; during a known-good run through of a level record performance stats from the GPU at regular intervals (polys on screen for example). You can then replay that route and if the numbers change outside a given tolerance it might mean something isn't displaying correctly anymore.

# Answer
> 0 votes
One simple easy thing which helps a lot, especially with stress testing, and network testing. Make it possible for your AI to play against other AI. If you can leave your game alone playing itself, or a small group of AI over a network for a weekend you can learn a lot.

Of course log everything.

---
Tags: testing
---


# Question
Title: Calculating normals after displacement mapping
I'm using C++, DX11 and tessellation. After tessellating a triangle I apply displacement mapping to the new vertices. But they still have the original triangle's normal so the lighting calculation behaves like the surface was flat.

So I see two solutions: sampling a normal map (corresponding to the displacement map) or sampling the displacement map in a few more places to calculate the normal myself (both would be done in the shader).

Since I'm using already using another normal map (with more detail than the displacement map contains) a 2nd normal map seems a little like an overkill. And calculating the normals myself seems inefficient.

Both solutions would work though so my dilemma is really this - am I overthinking it? Should I just go with one of the above solutions? Or is there a better approach?

# Answer
> 5 votes
Applying two normal maps is not that bad. Many games apply multiple normal maps already because they're blending between texture layers (e.g. for terrain), so having a normal map representing the larger displacements and another normal map for fine details is pretty reasonable. Check out Blending in Detail by Colin Barré-Brisebois and Stephen Hill for a look at how to combine multiple normal maps.

Sampling the displacement map in a few places to estimate its slope is also a possibility, but think about this: you'll still have to combine the estimated slope with the fine detail normal map somehow. You effectively have two normal maps again, but one of them is being generated on the fly by filtering the displacement map.

---
Tags: hlsl, directx11, normal-mapping, tessellation, displacement-mapping
---


# Question
Title: How does OpenGL determine different outputs with shaders?
Lets say I have this GLSL code:

```
#version 330

out vec4 outputColor;

void main()
{
    float lerpValue = gl_FragCoord.y / 500.0f;

    outputColor = mix(vec4(1.0f, 1.0f, 1.0f, 1.0f),
        vec4(0.2f, 0.2f, 0.2f, 1.0f), lerpValue);
}

```

(taken from http://www.arcsynthesis.org/gltut/Basics/Tutorial%2002.html)

How does OpenGL determine that outputColor is in fact what color the fragment should be?

# Answer
> 4 votes
By default the output variable (outputColor) is bound to location 0. For a fragment shader this specifies the color value to be used for that fragment for the framebuffer object in position 0.

You can bind the output variable to different locations in the application code using `glBindFragDataLocation()` or in the shader like this `layout(location = 0) out vec4 colorOut;`.

---
Tags: opengl, glsl, fragment-shader
---


# Question
Title: When should I use color keying vs PNG transparency?
SDL (and other toolkits) can use color keying to make a certain color in an image transparent. Alternatively, you could load a PNG image that supports transparency.

When should I use which?

# Answer
> 6 votes
JPG is lossy. Don't use that for sprites -- you will end up with nasty artifacts that will look bad. There's a couple reasons you might want to use colur-keying, but they're a bit lost in todays hardware. Taking a quick look at color key advantages:

**Pros**

* They use up less disk space -- there is no alpha channel to store
* By consequence, their memory foot print is lower because of this
* Can work for older technologies that do not support alpha channels

**Cons**

* Transparency cannot be spotted easily in more subtle spots of images
* You lose a color you can use from your palette
* **This can be computationally expensive in some cases.**

**A note about CPU complexity**

When you use a color key mapped image, you are still converting this to an image with alpha channels when it reaches the video RAM in all cases. You will need an additional channel to record these pixels as an alpha of 0. Due to this, a pass must be made on the image at load time to account for this. Unfortunately, the consequence for this is a higher overhead during loading. The time may be of no consequence for few images, but it is worth taking note.

In the end, PNG transparency is used mostly in todays standards game as it easy to use and widely decodable for the most part (such as with SDL). Most popular game engines no longer support color keying, this method was mostly used in older engines and systems.

Off the top of my head, libGDX and XNA both do **not support color keying.** However, the latter does support it on its content pipeline. Which leads into another interesting option...

**You can process it at build time**

If you really wanted to use color keying to save disk space because you were working on a tight budget disk space wise, you can always choose to store the assets in a color key format and then have them changed and built at build time to the format that is most appropriate.

**Concluding**

However, in the end **do not use JPG for something like a sprite**. If you want to use JPGs, use them on something that lossy behavior is acceptable, like 3D textures or photographs of real objects where picture blur is more or less unnoticed.

---
Tags: sdl, image, transparency, color, png
---


# Question
Title: A name that describes this type of turn-based battle system
I am thinking of a turn-based battle system that follows this workflow:

```
While True
  Get next character
  Determine character's action
  Execute action
  Check Battle Status
end

```

This is a straightforward battle system: there's a queue of battle characters, and on each iteration, it grabs the character at the front of the queue and has it perform an action. Once the action is performed, it gets pushed to the back of the queue.

Everyone gets an equal opportunity to perform an action and it simply rotates through all the participants.

When the loop breaks, end-battle processing occurs (eg: victory, defeat, escape, etc)

Is there a name for this particular type of turn-based battle system?

# Answer
> 2 votes
You can take a look at the wiki for more info, but it seems this type of system falls under a player-alternated, ranked, turn-based system. (AKA "I-GO-YOU-GO")

*Ranked* meaning the first player is first every round. This assumes your loop always executes the same; meaning when a player has performed, they go to the end of the queue. Furthermore, there is no additional system to manipulate a players order in the queue, which might be based on player stats or other outside factors.

# Answer
> 1 votes
Are you perhaps looking for the "Conditional Turn-Based Battle" as coined by Final Fantasy X? In this type of battle system, a sequence is determined based on character statistics and is stored. For example, a starting battle sequence could look like this:

* Ally 1
* Ally 2
* Enemy 1
* Ally 3
* Enemy 2
* Enemy 2
* Ally 1

When the battle begins, Ally 1 would use an action. If the action that Ally 1 affected the outcome of the "action list", then it would be adjusted accordingly. Then, the next unit in line would get to act. Assuming nothing else was affected, this would be Ally 2 who would be followed up with an action from Enemy 1.

You can read more about it here.

---
Tags: terminology
---


title: Change the sprite of a Object in Unity

text:
# Question
Title: Change the sprite of a Object in Unity
Inside the script code of the the hero(object) I want add the possibility to change its sprite.

So the player hits the space button and the sprite changes into the other sprite already added to the project.

Can you provide me a sample code to do this?

# Answer
> 20 votes
The code has been commented for you. Enjoy.

```
public Sprite sprite1; // Drag your first sprite here
public Sprite sprite2; // Drag your second sprite here

private SpriteRenderer spriteRenderer;

void Start ()
{
    spriteRenderer = GetComponent<SpriteRenderer>(); // we are accessing the SpriteRenderer that is attached to the Gameobject
    if (spriteRenderer.sprite == null) // if the sprite on spriteRenderer is null then
        spriteRenderer.sprite = sprite1; // set the sprite to sprite1
}

void Update ()
{
    if (Input.GetKeyDown (KeyCode.Space)) // If the space bar is pushed down
    {
        ChangeTheDamnSprite (); // call method to change sprite
    }
}

void ChangeTheDamnSprite ()
{
    if (spriteRenderer.sprite == sprite1) // if the spriteRenderer sprite = sprite1 then change to sprite2
    {
        spriteRenderer.sprite = sprite2;
    }
    else
    {
        spriteRenderer.sprite = sprite1; // otherwise change it back to sprite1
    }
}

```

You need to have a sprite renderer attached to your GameObject. Create a new C# Script and attach to it a GameObject. Paste the code in between the parenthesis... I'm sure you can figure it out from there :)

---
Tags: c#, 2d, unity, sprites
---