title: Raycast Flashing problem

text:
# Question
Title: Raycast Flashing problem
Can anyone tell me what is wrong with me code? If you can see, whenever the player is in range of the raycast, the enemy turns red. But for some reason, even when the player has meet the requirement to make the enemy turn red, it turns back to white. This is only visible when you move it manually, in normal speed it looks as if it is flashing.

I believe a reason for this is happening is that, one of the raycast doesn't meet the requirement anymore. Probably something related to that. I don't know exactly.

This picture shows that even when the player is within the requirement of of making the enemy red. It doesn't. Why?

```
using UnityEngine;
using System.Collections;

/* TL = Top Left
 * TR = Top Right
 * BL = Bottom Left
 * BR = Bottom Right
 */

public class Script_v2 : MonoBehaviour {

    // Player Properties
    private GameObject player;
    public Vector3 playerSize;
    private Vector3 playerTransform;
    public Vector3 playerTransformTL;
    public Vector3 playerTransformTR;
    public Vector3 playerTransformBL;
    public Vector3 playerTransformBR;

    private Vector3 newPlayerTransformTL;
    private Vector3 newPlayerTransformTR;

    private Vector3[] playerRaycastPoints;

    // Enemy Properties
    private Vector3 enemyTransformTL;
    private Vector3 enemyTransformTR;
    private Vector3 enemyTransformBL;
    private Vector3 enemyTransformBR;

    public float distance;
    public Vector3 enemySize;

    // Detection Alerts
    public bool alerted;
    public bool alertedLock;
    public bool dead;

    Ray ray;
    RaycastHit hit;

    // Use this for initialization
    void Start () {
        playerRaycastPoints = new Vector3[4];

        distance = 3f;
        player = GameObject.FindGameObjectWithTag ("Player");

    }

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

        enemyTransformTL = new Vector3 (transform.position.x - 0.5f, transform.position.y + 0.5f, transform.position.z);
        enemyTransformTR = new Vector3 (transform.position.x + 0.5f, transform.position.y + 0.5f, transform.position.z);

        enemyTransform_TL_TR ();
        detectionAlert ();
        Reference_Player_Transform_Points ();
        Player_Transform_Points_Detection ();

    }

    void OnDrawGizmos() {
        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere (new Vector3(transform.position.x - 0.5f, transform.position.y + 0.5f, transform.position.z), distance);
        Gizmos.DrawWireSphere (new Vector3(transform.position.x + 0.5f, transform.position.y + 0.5f, transform.position.z), distance);
    }

    public void enemyTransform_TL_TR() {

        for (int i = 0; i < 4; i++) {

            double enemyAngleTL = Mathf.Atan2(playerRaycastPoints[i].y - ( transform.position.y + 0.5f ),
                                              playerRaycastPoints[i].x - ( transform.position.x - 0.5f )) * 180f / 3.14159265f;
            Debug.Log (enemyAngleTL);
            double enemyAngleTR = Mathf.Atan2 (playerRaycastPoints[i].y - (transform.position.y + 0.5f),
                                               playerRaycastPoints[i].x - (transform.position.x + 0.5f)) * 180f / 3.14159265f;

            Vector3 directionTL = (playerRaycastPoints[i] - enemyTransformTL).normalized;
            Ray rayTL = new Ray(enemyTransformTL, directionTL);
            RaycastHit hitTL;
            Vector3 directionTR = (playerRaycastPoints[i] - enemyTransformTR).normalized;
            Ray rayTR = new Ray (enemyTransformTR, directionTR);
            RaycastHit hitTR;

            //Debug.DrawRay (rayTR.origin, rayTR.direction * distance, Color.yellow);

            if(Physics.Raycast (rayTL, out hitTL, distance)) {
                if((enemyAngleTL > 90 && enemyAngleTL < 180)) {
                    Debug.DrawRay (rayTL.origin, rayTL.direction * distance, Color.yellow);
                    alerted = true;

                }

            }
            else {
                alerted = false;
            }

        }

    }

    public void detectionAlert() {
        if (alerted == true) {
            gameObject.renderer.material.color = Color.red;
        }
        else {
            gameObject.renderer.material.color = Color.white;
        }
    }

    private void Reference_Player_Transform_Points() {

        playerSize = player.transform.localScale;

        playerTransformTL = new Vector3(player.transform.position.x - (playerSize.x / 2),
                                        player.transform.position.y + playerSize.y  / 2,
                                        player.transform.position.z);
        playerTransformTR = new Vector3(player.transform.position.x + (playerSize.x / 2),
                                        player.transform.position.y + playerSize.y  / 2,
                                        player.transform.position.z);
        playerTransformBL = new Vector3(player.transform.position.x - (playerSize.x / 2),
                                        player.transform.position.y - playerSize.y  / 2,
                                        player.transform.position.z);
        playerTransformBR = new Vector3(player.transform.position.x + (playerSize.x / 2),
                                        player.transform.position.y - playerSize.y  / 2,
                                        player.transform.position.z);

        playerRaycastPoints [0] = playerTransformTL;
        playerRaycastPoints [1] = playerTransformTR;
        playerRaycastPoints [2] = playerTransformBL;
        playerRaycastPoints [3] = playerTransformBR;

    }

}

```

# Answer
> 1 votes
Remove the

```
        else {
            alerted = false;
        }

```

And move the `alerted = false;` to BEFORE the for-loop:

```
public void enemyTransform_TL_TR() {
    alerted = false;
    for (int i = 0; i < 4; i++) {
       ...

```

You're clearing the boolean value on the last iteration, making the previous 3 checks useless.

---
Tags: c#, unity, vector, raycasting
---


title: Changing Light Intensity value

text:
# Question
Title: Changing Light Intensity value
I have this code for creating a light:

```
            GameObject lightGameObject = new GameObject ("Light1");
            lightGameObject.AddComponent (typeof(Light));
            lightGameObject.light.color = Color.white;

            lightGameObject.light.intensity = 0.5f;

```

I want to change the light's intensity to 0.5f but when I run the game, the intensity's still at 1.

# Answer
> 1 votes
That is indeed the correct way to set the light's intensity. It's likely you have an error elsewhere in your code or you're not interpreting the results of the light intensity correctly. For example you might be creating multiple lights on accident and their combined intensities might look brighter than you're expecting.

Check the object hierarchy to make sure you don't have multiple lights. Also use the inspector to determine the actual intensity of the light you have created.

Finally you can attach the debugger and inspect to properties of the light after creation to ensure they're being modified as you expect and that the value is not being modified elsewhere.

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


title: Decoupling AI from game logic

text:
# Question
Title: Decoupling AI from game logic
Imagine a game with different types of characters or "actors" which can perform actions like walking and shooting. They are implemented using the state pattern to reduce the amount of coupling: each actor has a current state which can be one of the different possible state objects like DefaultState, ReloadingState or StunnedState which determine what happens when its methods like Reload(), Shoot() or Walk(direction) are called. Every frame the current state object updates the actor and returns the next state.

This works great for the player who doesn't need to know anything about the internals. However, an AI controller needs to know its character's current state to make intelligent decisions. For example, in the DefaultState the AI character would walk towards the nearest enemy while in StunnedState it would flee. It seems like every state should have its own AI routine, but how should this be implemented while trying to keep this logic separate from the actor class? The AI could query the actor for its current state and decide its actions based on that, but that would result in a bloated and messy if-else block. The State class shouldn't know anything about the AI so it cannot be in charge of changing the AI's state either. How can I implement an AI which chooses different actions based on the actor's current state while maintaining loose coupling?

# Answer
A design pattern I've enjoyed using has two types of things: task management and task execution. Task management asks the question *"What should I be doing right now?"* And task execution asks, *"How do I complete the current task?"*

**Task Managers**

The job of the task manager is to constantly look at the AI's internal state (read-only) to determine whether new tasks should be assigned. Tasks have priorities, and are placed on a *Priority Queue* when assigned. Tasks are also *unique*, so that an agent can't be assigned exactly the same task twice.

For instance, the Task Manager could constantly be checking to see if the agent has sensed any new enemies that must be attacked. If enemies are sensed, it adds high-priority *DestroyThreat* tasks to the task queue.

When the agent is done with the current task, it pops another one off the task queue. Task managers can also *pre-empt* the current task by putting it back on the queue if an extremely high priority task overrides the current task.

**Task Executors**

Your agent will have several *actions* which are merely functions, bits of behavior tree, or states in a state machine. Every action can either fail, or succeed. These are implemented inside the AI agent itself. They should be atomic (like "play animation" or "attack entity").

The task executor will simply tell the AI agent what actions to take given a current task. It does not need to directly know about the agent's state, but only the return values of the actions the agent takes. The executor can either fail the task, or succeed, based on whether the current action fails or succeeds. If the task fails, it is either put back on the task queue or is destroyed, depending on the desired behavior.
> 7 votes

# Answer
Depending on the language you're using use a virtual function, a function pointer, or a delegate for your actor's "do something" function (some engines call it `Process()` or `Update()` )

in C++

```
class BaseAI {
protected:
  //...
  virtual void ProcessFrame() = 0;
public:
  static void ProcessAIs(); // this call the ProcessFrame of all existing BaseAIs

  //...
};

class Monster : public BaseAI
{
protected:
  void ProcessFrame() {
    // do monster stuff
  }

  //...
};

class BigBoss : public BaseAI
{
protected:
  void ProcessFrame() {
    // do big boss stuff
  }

  //...
};

```

That's what function pointers / virtuals / delegates are for.
> 2 votes

# Answer
create corresponding states for the AI. for example:

```
AIDefaultState, AIReloadingState , AIStunnedState

```

you can inherit from the normal states if seemed logically correct in your situation
> 0 votes

---
Tags: architecture, ai, design-patterns
---


# Question
Title: Making multiple VertexPositionColor variables in the same class? - XNA
I have studying XNA on my spare time for about a year now and I could use some professional help on this issue. Any time given to my problem is appreciated.

I have two VertexPositionColor variables both of which are placed into two separate vertex buffers to draw up three triangles

```
basicEffect = new BasicEffect(GraphicsDevice);
        VertexPositionColor[] vertices = new VertexPositionColor[6];
        vertices[0] = new VertexPositionColor(new Vector3(0, 1, 0), Color.Red);
        vertices[1] = new VertexPositionColor(new Vector3(-1, -1, 0), Color.Green);
        vertices[2] = new VertexPositionColor(new Vector3(1, -1, 0), Color.Blue);
        vertices[3] = new VertexPositionColor(new Vector3(0.05f, 1, 0), Color.Yellow);
        vertices[4] = new VertexPositionColor(new Vector3(-1, -1, 0), Color.Blue);
        vertices[5] = new VertexPositionColor(new Vector3(-1, 1, 0), Color.Pink);
        vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly);
        vertexBuffer.SetData<VertexPositionColor>(vertices);

        VertexPositionColor[] vertices2 = new VertexPositionColor[3];
        vertices2[0] = new VertexPositionColor(new Vector3(0, 1, 0), Color.Blue);
        vertices2[1] = new VertexPositionColor(new Vector3(-1, -1, 0), Color.Red);
        vertices2[2] = new VertexPositionColor(new Vector3(0.9f, -0.9f, 0), Color.Orange);
        vertexBuffer2 = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 6, BufferUsage.WriteOnly);
        vertexBuffer2.SetData<VertexPositionColor>(vertices2);

```

I then use the draw function to draw all three triangles ..

```
public override void Draw(GameTime gameTime)
    {
        basicEffect.World = world;
        basicEffect.View = view;
        basicEffect.Projection = projection;
        basicEffect.VertexColorEnabled = true;
        GraphicsDevice.SetVertexBuffer(vertexBuffer);
        GraphicsDevice.SetVertexBuffer(vertexBuffer2);
        RasterizerState rasterizerState = new RasterizerState();
        rasterizerState.CullMode = CullMode.None;
        GraphicsDevice.RasterizerState = rasterizerState;
        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 3);

        }
        base.Draw(gameTime);
    }

```

But it does not draw all three triangles. I have tried various variations and all that gets drawn is either the last vertex buffer or the first one. I know it would be more efficient to place them all in the same buffer or have them used with indices, but in the future I will run into issues where I am going to need more than one buffer to draw something and I want to be prepared. What is the problem here and how do I draw more than one vertex buffer at a time?

# Answer
Do your draw calls for each vertex buffer you set, with the corresponding number of primitives as the third parameter in *DrawPrimitives*. Calling *GraphicsDevice.SetVertexBuffer* two times will replace the first vertex buffer.

Your draw function should look similar to this:

```
public override void Draw(GameTime gameTime)
{
    basicEffect.World = world;
    basicEffect.View = view;
    basicEffect.Projection = projection;
    basicEffect.VertexColorEnabled = true;
    RasterizerState rasterizerState = new RasterizerState();
    rasterizerState.CullMode = CullMode.None;
    GraphicsDevice.RasterizerState = rasterizerState;
    GraphicsDevice.SetVertexBuffer(vertexBuffer);
    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);

    }
    GraphicsDevice.SetVertexBuffer(vertexBuffer2);
    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);

    }
    base.Draw(gameTime);
}

```
> 0 votes

---
Tags: xna, c#, vertex, vertex-buffer
---


# Question
Title: How can I implement large moving "colossus" characters that also act as environmental objects?
I'm curious how enormous characters that act both as entities and environments are implemented. I'm thinking of characters like in *Shadow of the Colossus* which move, but which the player can also move *on*.

It seems these objects would be created as characters, rigged like any character would be with their various animations, but they would also need to be usual physical surfaces that we can walk on. Considering the way characters are handled compared to how static environment is handled physically in most game engines, this could prove problematic, and added to that is the problem of size.

So, generalising over engine details (but assuming you have a generic physics/character engine, e.g. Unity/Unreal) what approach should be taken?

Also, screenshot:

As you can see in this screenshot, the colossus is really big, and the player can walk on it and climb on some parts of it (hairs mostly)

And a video of a boss fight here which really shows what this gameplay is all about

# Answer
I read a really great article about SOTC and how the made it. I found a copy of it here.

To summarize, they use a 'deformable' mesh, where by parts of a triangle mesh are weighted to bones, using the same technique as rigged characters. The edges/lips that can be grabbed are specially tagged. I suspect that they keep the previous and new position of each vertex so they can calculate the velocity of each contact to help resolution.

I do not think many physics engines could do this out of the box, but I imagine you could implement it yourself with diligence.

Fundamentally I don't think it is hard, but getting it to run fast, and getting good collision response requires effort. Encapsulating each triangle in a bounding AABB tree (3D version of the box2d broadphase, for example) would help speed up queries. The fact that triangles change size and orientation is a complication but obviously not insurmountable.
> 3 votes

---
Tags: physics, game-mechanics, terrain, character
---


# Question
Title: 3dsMax to Mudbox - Import Warning: UV not a complete set
I'm exporting my 3dsMax model to Mudbox. The import gives me a warning that the UV set is incomplete.

First, what does this mean? That I haven't got all the UVs unwrapped? Web searches have brought nothing.

Also if this is the problem, is there a way to check if all UVs are unwrapped?

I'll post my map if you need it.

# Answer
Looks like sometimes mudbox gets angry when the unwrap has zero-area faces (not correctly unwrapped) or you have UVs too close to the edge of the map. Can you shrink them all down towards the center (0.5, 0.5) and try again?
> 2 votes

---
Tags: models, 3dsmax, uv-mapping, import
---


# Question
Title: What is the difference between a tech tree and crafting?
Are tech trees and crafting the same thing, except the mechanism to attain them? What the real difference between the two?

# Answer
> 1 votes
They do have similarities.

A tech tree is something you advance through in order to gain a skill or ability. Crafting you also advance through, but you gain the ability to create something.

Potentially, you could share the same base data structures between them.

---
Tags: game-mechanics
---


# Question
Title: accessing GUIText and recieveing NullReferenceException Error
I Have this line of code

```
public class HSLerp3 : MonoBehaviour {

   private GUIText textFade;
   private float startAlpha = 0f;
   private float damping = 0.5f;

   // Use this for initialization
   void Start () {

      textFade = gameObject.GetComponents<GUIText>();

   }

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

       textFade.color = new Color (0, 0, 0, startAlpha);
       startAlpha -= damping * Time.time;

   }
}

```

It looks right, But I keep on recieving an error of:

> NullReferenceException: Object reference not set to an instance of an object

I'm trying to make a GUIText from scratch and by codes. been doin it for hours. Help is greatly appreciated.

# Answer
It cant find the object/component in your start void.

Make sure you have a GUIText component on the object you are referencing. Also its a good practice to be implicit by using

```
textFade = this.gameObject.GetComponent<GUIText>();

```

Oh and I just noticed you are using GetComponents\<\>; not GetComponent\<\>; so if you need an array it should be

```
textFade = this.gameObject.GetComponents<GUIText>()[0]; //the array is which descending component to use.

```

Hope this helps, Cheers, Demetry.
> 1 votes

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


# Question
Title: Cocos2d-x supporting multi-resolution using density independent pixels
Is there a way to use Density Independent pixels(dp) in cocos2d-x?

I am developing an Android game using Cocos2d-x 3.0.

The Android reference http://developer.android.com/guide/practices/screens\_support.html tells me not to use pixels in code but use dp when supporting multi-resolution support. It also tells me to provide different images for different screen size groups and different density groups.

However, cocos2d-x tutorials use pixels for multi-resolution support. If I were to use pixels, I think it means I need to have images for all these different resolutions:

240x320, 240x400, 240x432 320x480 480x640, 480x800, 480x854 600x1024 640x960 1024x600, 1024x768 1280x768, 1280x800 1536x1152 1920x1152, 1920x1200 2048x1536 2560x1536, 2560x1600

Even if I don't support every screen resolutions, I think this requires more work than following the Android reference's best practice.

Am I missing something on how supporting multi-resolution works or do I indeed do need to do much more work using cocos2d-x?

# Answer
There is no option about `dp` in cocos2dx and in fact we don't need it.

But cocos2D-x 2.x and 3.x have very easy solution for multi-resolution problem ( either iDevices or Android devices) As you saw in Multi-resolution support document.

In fact you just need to set your `DesignResolution` and then just imagine your target device will has this resolution.

If target device really has this resolution ( or any other with same ratio) cocos2d will handle to fix screen and your game looks same in all devices.

And when ratio of target device is different, you have many option ( `policy`) to manage that.

For example if you use `Exact fit` policy, cocos2d will force your game ( and design) to fit target device screen (without that black boarder).

> Exact fit
>
> The entire application is visible in the specified area without trying to preserve the original aspect ratio. Distortion can occur, and the application may appear stretched or compressed.

For more detail just take a look at the official wiki.

Beside all above word, I found This Link (from V-Play engine) and Its `Safe Zone` definition really interesting and I highly recommend you to use recommended-resolution-value of this page for your work as I did.

Although this link is from another engine but the description helps you understand everything better. Here is a map between this page terms to cocos2d-x terms:

> V-Play::letterbox =\> Cocos2dx::Show All
>
> V-Play::ZoomToBiggerSide =\> Cocos2dx::NoBorder

---

In addition you did ask about required image size in cocos2dx development:

As you know the different size of image is not about game-look in different resolutions and you can publish your game with one size for each asset and your game/app looks good in all resolution with above description for resolution Policies.

But we need multiple image-size for each asset, to optimize memory usage. in this case ( as cocso2dx solution) we check device size and mark appropriate set of image ( each image set is in one folder with same-structure/different-size like HDR/HD/SD) as default folder of resource:

```
    CCSize frameSize = pEGLView->getFrameSize();

    if (frameSize.height > mediumResource.size.height)
    {
        searchPath.push_back(largeResource.directory); //mark HDR default
        pDirector->setContentScaleFactor(largeResource.size.height/designResolutionSize.height); //handle scaling because of different between our programming-design-resolution and artist-design-canvase-resolution
    }
    else ...

```
> 7 votes

---
Tags: android, cocos2d-x, resolution
---


# Question
Title: procedural generation - deterministic or not? (No man's sky)
Here is a link of Sean Murray talking about the game No Man's Sky:

https://www.youtube.com/watch?v=h-kifCYToAU

Starting at around 4:00 in the video, he is talking about how the environment is procedurally generated.

At first, I thought it meant that they ran some incredibly complex algorithms to generate the entire universe and then stored it.

But as he explains, the world doesn't really exist as stored 3d data and what have you, but it really is just the output of a very complex function that takes your position (3d coordinates, and I guess time as well) as input and always generates the exact same environment around you based on that, no matter where you are in this gigantic universe.

This is incredibly smart and interesting but there are a few things that I don't understand:

How can you interact with the environment and have any effect on it if it is the result of a deterministic function? You would have to "update" that function every time you interact, don't you?

How can multiple players interact with the environment and see the same changes?

How can only a single player blow out a piece of rock and then expect it to stay blown apart? Does it change the "world-generating function" ?

# Answer
> 9 votes
> How can you interact with the environment and have any effect on it if it is the result of a deterministic function? You would have to "update" that function every time you interact, don't you?

It's a simple enough concept to create any *unmodified* point in space / event in time / combination of these using a fixed function. The downside is that when *any* player *modifies* the procedurally-generated world at a given place / point in time, you have to store (the results of) this change -- potentially across clients if a multi-client environment. Because of custom modifications, the function alone is now no longer sufficient to produce that given point in space / time... instead you must first generate it from that function, and *then* apply any deltas that players have created at that point in time/space.

I suspect that anyone who was able to change this simple but apparently logically-immutable fact could make a lot of money indeed and the knock-on effects of this would run quite outside of just developing virtual worlds, as this idea runs deep into the heart of both compression and cryptography.

> How can multiple players interact with the environment and see the same changes?

The deltas must be sent. The function alone cannot produce player-made changes on another player's machine, so the only way to get that information across is to send it.

> How can only a single player blow out a piece of rock and then expect it to stay blown apart? Does it change the "world-generating function"?

No (as noted above).

> deterministic or not?

Procedural generation *should*, by default, be considered to be an inherently deterministic concept as without being so, you can see how the whole approach falls apart.

# Answer
> 5 votes
Procedural generation works on the idea that you know what you want to create and how it is created but you leave out the details. Think of a set of sliders for color, size, roundness / sharpness, amplitude and such aspects. You don't want to define every aspect of the result by hand. You want to outline a general idea of what you'd like and won't like to see, color sets, surface smoothness, and such.

This obviously defines the world in it's virginal state. You are saving hard drive and memory space because you aren't storing **a lot** of detail. You let the details get randomized with a predetermined seed which means, you don't know what will happen but it will happen again and again every time (like perlin noise from a seed), in fact, the creator says the worlds are created by noise that uses a seed to repeat the same results. It is all build on the notion that you have the functionality to build a planet using a set of values to define it's properties first and then you let the algorithm, randomly pick these values. The universe itself is built on the concept of randomly picking *far enough* but *not too far* spots to place planets.

To store player modifications, you normally wouldn't want to store the entire mesh with the modifications applied to it (i.e. storing the result) as that would be space consuming, what you normally would do is store the actions the user took. Think Command Oriented Architecture. Then when someones else approaches that area, you need to "replay" these actions as you generate the mesh. This is where things get challenging. If the player has a lot of power to modify things in the world, it could require a lot of processing power to replay these actions. This is why I think something like digging tunnels (like it's done in Minecraft) would be very hard to accomplish if you don't store the results. It is entirely possible though.

Also think of more complicated aspects, a player kills a bunch of animals. Now time passes by and the world changes because time affects it, would the players actions affect the world? In a sense probably no. Killing a hundred deer will probably not cut down on deer population (as we have come to expect from MMO) as the world will be restored to it's virginal state and be repopulated according to the seed of time and space. Unless of course, the server stores the hunting activity and takes it into account when respawning new creatures.

A lot of interesting effects of player activity that don't relate to game mechanics and have to do more with simulation are lost if everything is generated on the spot. How does cutting down the herbavor population affect the carnivor population? How does it affect the plants in the area? But I digress.

# Answer
> 3 votes
You can do this while procedurally generating content. Think about it like this: You procedurally generate like you said, but instead of storing the whole universe, you store a part of the world which you are in, say a sqare kilometer around you in the memory. When the generation is complete, you can throw a rock and store its position accordingly. When you are about to generate an other sqare kilometer of your universe, throw out the previous one.

You can even save the position (or properties) of the rock you thrown, by generating a unique indentifier for your objects in your procedural functions. If the generated id of the rock is deterministic, you can load back its properties once you move back to that area.

---
Tags: procedural-generation
---


# Question
Title: How to export HAXE code to other languages?
I'm using Haxe on the HAXE IDE, HIDE. I can simply create code for any language, but I don't know how to export it. It didn't have any export options, and no tutorials explain this. How do I export it?

# Answer
> 3 votes
If you choose *project \> build* or *project \> run* the project will be exported to the *Export* folder inside the project directory. I don't know what project you exactly started but in the *project \> project options* you can find which platform you are targeting.

If you want to export to multiple platforms, you have to alter the hxml files, and instruct the compiler to also export to different platforms. You can find the basic usage here: http://haxe.org/documentation/introduction/compiler-usage.html

---
Tags: haxe
---


title: 2d parallax edges

text:
# Question
Title: 2d parallax edges
I'm writing a mini 2d game, the scene background is based on two images with parallax effect.

I want the right edge of both images, finish at the same time matching the right edge of the canvas. But I've got, both images finish on the canvas left edge.

I'm doing:

```
parallaxQuotient = nearImage.width / farImage.width;

```

And scrolling like this:

```
speed = 1;
farImage.position.x -= speed / parallaxQuotient ;
nearImage.position.x -= speed ;

```

How to get both images ending on canvas right edge?

# Answer
> 3 votes
The result you get (left image align) is correct given the math you use.

What you want is that when near image is reaching right edge:

```
nearImage.position.x == nearImage.width - viewPort.width

```

we have also far image reaching right edge :

```
farImage.position.x  == farImage.width - viewPort.width

```

All that should happen in the same time, so the speed ratio should be

```
speedRatio = ( nearImage.width - viewPort.width ) / (  farImage.width - viewPort.width )

```

---
Tags: algorithm, parallax-scrolling
---


title: Trying to implement Camera

text:
# Question
Title: Trying to implement Camera
I'm trying to implement a `Camera` class in order to walk and look on the world as follow:

```
#ifndef _CAMERA_H_
#define _CAMERA_H_

#include <glm\glm.hpp>

class Camera
{
public:
    Camera();
    ~Camera();

    void Update(const glm::vec2& newXY);
    //if by = 0.0 it means, it will use the const Class speed to scale it
    void MoveForward(const float by = 0.0f);
    void MoveBackword(const float by = 0.0f);
    void MoveLef(const float by = 0.0f);
    void MoveRight(const float by = 0.0f);
    void MoveUp(const float by = 0.0f);
    void MoveDown(const float by = 0.0f);
    void Speed(const float speed = 0.0f);

    glm::vec3& GetCurrentPosition();
    glm::vec3& GetCurrentDirection();
    glm::mat4 GetWorldToView() const;
private:
    glm::vec3 position, viewDirection, strafeDir;
    glm::vec2 oldYX;

    float speed;
    const glm::vec3 up;
};

#endif

#include "Camera.h"
#include <glm\gtx\transform.hpp>

Camera::Camera()
    :up(0.0f, 1.0f, 0.0), viewDirection(0.0f, 0.0f, -1.0f),
    speed(0.1f)
{
}

Camera::~Camera()
{
}

void Camera::Update(const glm::vec2& newXY)
{
    glm::vec2 delta = newXY - oldYX;
    auto length = glm::length(delta);
    if (glm::length(delta) < 50.f)
    {
        strafeDir = glm::cross(viewDirection, up);
        glm::mat4 rotation = glm::rotate(-delta.x * speed, up) *
            glm::rotate(-delta.y * speed, strafeDir);

        viewDirection = glm::mat3(rotation) * viewDirection;
    }

    oldYX = newXY;
}

void Camera::Speed(const float speed)
{
    this->speed = speed;
}

void Camera::MoveForward(const float by)
{
    float s = by == 0.0f ? speed : by;

    position += s * viewDirection;
}
void Camera::MoveBackword(const float by)
{
    float s = by == 0.0f ? speed : by;

    position += -s * viewDirection;
}
void Camera::MoveLef(const float by )
{
    float s = by == 0.0f ? speed : by;
    position += -s * strafeDir;
}
void Camera::MoveRight(const float by )
{
    float s = by == 0.0f ? speed : by;
    position += -s * strafeDir;
}
void Camera::MoveUp(const float by )
{
    float s = by == 0.0f ? speed : by;
    position += s * up;
}
void Camera::MoveDown(const float by )
{
    float s = by == 0.0f ? speed : by;
    position += -s * up;
}

glm::vec3& Camera::GetCurrentPosition()
{
    return position;
}
glm::vec3& Camera::GetCurrentDirection()
{
    return viewDirection;
}

glm::mat4 Camera::GetWorldToView() const
{
    return glm::lookAt(position, position + viewDirection, up);
}

```

and I update and render as follow :

```
void Game::OnUpdate()
{
    glLoadIdentity();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUniformMatrix4fv(program->GetUniformLocation("modelToViewWorld"), 1, GL_FALSE, &cam.GetWorldToView()[0][0]);

}

void Game::OnRender()
{

    model->Draw();

}

```

Which the Vertix shader is:

```
#version 410

layout (location = 0) in vec3 inVertex;
layout (location = 1) in vec2 inTexture;
layout (location = 2) in vec3 inNormal;

uniform mat4 modelToViewWorld;

void main()
{
        gl_Position    = vec4(mat3(modelToViewWorld) * inVertex, 1);

}

```

But in result the model itslef is moving/rotating instead of moving the camera around the model. What am I doing wrong here?

# Answer
> 2 votes
Depending on the way your matrix type stores its values you may have to transpose the matrix to get the transformation right. You can use the boolean parameter of `glUniformMatrix4fv();` to do that.

And the way you're applying the transformation in the vertex shader is omitting the translation part. Use it this way:

```
gl_Position = modelToViewWorld * vec4(inVertex, 1);

```

---
Tags: opengl, c++, shaders, glsl
---


title: Draw image layer in tmx map - libgdx

text:
# Question
Title: Draw image layer in tmx map - libgdx
I created a map only with an image layer in tiled map editor.

When I want to load the map the layer isn't shown. Only the background color.

Followed the tutorial from http://www.gamefromscratch.com/post/2014/04/16/LibGDX-Tutorial-11-Tiled-Maps-Part-1-Simple-Orthogonal-Maps.aspx

Here the code (left out empty overrides):

```
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class Main extends ApplicationAdapter implements InputProcessor  {
TiledMap tiledMap;
OrthographicCamera camera;
TiledMapRenderer tiledMapRenderer;

@Override
public void create () {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera();
    camera.setToOrtho(false,w,h);
    camera.update();
    tiledMap = new TmxMapLoader().load("C:/Users/Robin/Desktop/map.tmx");
    tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);

    Gdx.input.setInputProcessor(this);
}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
}
}

```

I added a tileset and tried again (just a little test). Only the tiles are visible:

Any ideas how to set the layer visible?

Greetings Kaito

# Answer
When browsing the libgdx documentation (for example at http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/maps/MapLayer.html), I don't see any mention of the image layer, so most likely this relatively new (and still quite limited) layer type is not supported by libgdx yet.

If you would like to see this supported in libgdx, I suggest opening an issue about it at https://github.com/libgdx/libgdx/issues

*Update: This feature has been implemented in libgdx in the meantime. See https://github.com/libgdx/libgdx/issues/2741*
> 3 votes

---
Tags: libgdx, tiled
---


# Question
Title: Unity's StartCoroutine funtionality inside a .NET Library and outside a MonoBehaviour
This code is used in a MonoBehaviour script in my current code:

```
    // a simple WWW post
    WWW www = new WWW(this.Url, bytes);
    StartCoroutine(WaitForRequest(www));
}

// simple handler for the WWW error/return data.
private IEnumerator WaitForRequest(WWW www)

```

The problem is that I want to move this into a dll, that will be used by other dlls, not just monobehaviours, which as far as I can tell, means that StartCoroutine will no longer be available.

In .NET, Async and Await sounds similar, but I don't know how to use them. Is there a way to duplicate the Coroutine functionality? I do have access to UnityEngine.dll.

(If it is possible to use Coroutine without inheriting MonoBehaviour, that can work as well)

Thanks.

# Answer
Yes, it is possible to do using iterators. I've put some pseudo C# code here to give you an idea. You use `yield return` to return something from an iterator, which has the same behavior as `yield` in a theoretical coroutine. You can then store the iterators in a list, dictionary, or other structure to keep track of them, and run them all. Note that coroutines are *not* a natively supported feature of C#, and are usually implemented using enumerators. I think Unity does it in the same way.

```
enum Status
{
   Running, Success, Failure
}

// An example of a coroutine that does something until some
// condition is true.
IEnumerable<Status> Coroutine(arguments)
{
    while(true)
    {
        DoStuff();

        yield return Running;

        if(Condition())
        {
            yield return Success;
            break;
        }
    }
}

// Keeps track of all running coroutines, and runs them till the end.
class CoroutineManager
{
     List<IEnumerator<Status> > Coroutines = new List<Enumerator<Status> >();

     // Starting a coroutine just means adding an enumerator to the list.
     // You might also want to be able to stop coroutines or delete them,
     // which might mean putting them into a dictionary
     public void StartCoroutine(Func<IEnumerable<Status> > func)
     {
         Coroutines.Add(func().GetEnumerator());
     }

     // Updating just means stepping through all the coroutines
     public void Update()
     {
         foreach(Enumerator<Status> routine in Coroutines)
         {
             routine.MoveNext();
         }
     }
}

```

You then just need to call

```
CoroutineManager.StartCoroutine(YourFunction)

```

to begin the coroutine. Somewhere in your code you also need to call

```
CoroutineManager.Update();

```

each tick.
> 4 votes

---
Tags: c#, unity, unityscript, .net
---


title: Monogame [Linux] cannot resize screen

text:
# Question
Title: Monogame [Linux] cannot resize screen
While working on a Monogame project on Linux (Arch to be exact), I found that I could not change the screen height away from the default 800 px, while I could easily, perfectly change the width to whatever I want. Has anyone ever had this issue, and is there a fix for it? I am going to try the solution that @Jon explained in this post, but I doubt it will work since this seems to be a Linux-only problem. I have installed the latest version of OpenTK and built the latest build of Monogame as of a few days ago, and have looked through the source for the Monogame `OpenTKGameWindow` and `GraphicsDevice` classes, as well as the `GraphicsDeviceManager`. I don't see the issue in any of those, but I might be missing something.

# Answer
It seems that my bug report on Github has been responded to. If this is being read before the next official version is released, this fix will most likely contained in the development branch of the repository on Github. All that you have to do is pull down the repo and dependencies from Github and then build Monogame using Protobuild (this requires Mono to be installed to compile the framework). After that, you can link the generated library files to your Monogame project and then it should work fine.

Links to Github:

Issue: https://github.com/mono/MonoGame/issues/3254

Pull Request w/ fix: https://github.com/mono/MonoGame/pull/3315
> 4 votes

# Answer
I thinks this is the same bug I found when experimenting with MonoGame to decide if I will use C#/MonoGame rather than C++/Various Libraries.

I suggest the following work around: try to change the resolution more than once. The property AllowUserResizing must be set to true before doing the change of resolution. And you must call ApplyChanges(). All of this came from the bug report.

I made a ResolutionChanger class that automates all that. The class has an update() method that should be called each frame. This update method will check the current resolution to see if it is the same as the last requested resolution, if it is not the same, the change is assumed as failed and the class will continue trying to change the resolution until it see that the current resolution is the same as the requested resolution.

Note that I had some success with this approach but I observed that some times the game starts with the default resolution, switch to full screen and back to windowed fixs it but I don't remember now if that worked 100% of the time.

I don't know if this will work for you, but you can try.

How to use (in your main game class extending Game):

In the constructor create a ResolutionChanger instance:

```
public MyGame ()
{
    graphics = new GraphicsDeviceManager (this);
    Content.RootDirectory = "Content";
    this.IsFixedTimeStep = true;
    screen = new VirtualScreen(graphics, Window, 1366, 768);
    resolution = new ResolutionChanger(graphics, Window);
    //(...) More code
}

```

In the Initialize() method:

```
protected override void Initialize ()
{
    resolution.DesiredWidth = 1280;
    resolution.DesiredHeight = 720;

    base.Initialize ();
}

```

In the Update() method:

```
protected override void Update (GameTime gameTime)
{
    //(...) your code

    // Switch fullscreen with Enter key. Change it if you do not like it
    if (Keyboard.GetState().IsKeyDown(Keys.LeftAlt) && Keyboard.GetState().IsKeyDown(Keys.Enter))
    {
        resolution.FullScreen = !resolution.FullScreen;
    }

    // This will change the back buffer bounds and game window bounds if required
    resolution.Update(false);

    //(...) your code

    base.Update (gameTime);
}

```

Here is the code for the ResolutionChanger class:

```
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGameTest
{
    public class ResolutionChanger
    {
        private int mDesiredWidth;
        private int mDesiredHeight;
        private bool mFullScreen;
        private Rectangle mLastWindowedBounds;
        private GraphicsDeviceManager mGraphics;
        private GameWindow mWindow;

        public ResolutionChanger (GraphicsDeviceManager graphics, GameWindow window)
        {
            mLastWindowedBounds = window.ClientBounds;
            mDesiredHeight = 640;
            mDesiredWidth = 480;
            mGraphics = graphics;
            mWindow = window;
        }

        public void Update (bool force)
        {
            if (mGraphics.GraphicsDevice.PresentationParameters.BackBufferWidth != mDesiredWidth ||
                mGraphics.GraphicsDevice.PresentationParameters.BackBufferHeight != mDesiredHeight ||
                force)
            {
                bool setUserResizing = mWindow.AllowUserResizing;

                if (!mGraphics.IsFullScreen && !setUserResizing)
                {
                    mWindow.AllowUserResizing = true;
                }

                mLastWindowedBounds = mWindow.ClientBounds;
                mGraphics.PreferredBackBufferWidth = mDesiredWidth;
                mGraphics.PreferredBackBufferHeight = mDesiredHeight;
                mGraphics.ApplyChanges();

                if (!mGraphics.IsFullScreen && !setUserResizing)
                {
                    mWindow.AllowUserResizing = false;
                }

                Console.WriteLine("ResolutionChanger: a change in resolution took place");
            }

            if (mFullScreen != mGraphics.IsFullScreen)
            {
                mGraphics.IsFullScreen = mFullScreen;

                if (!mGraphics.IsFullScreen)
                {
                    mDesiredWidth = mLastWindowedBounds.Width;
                    mDesiredHeight = mLastWindowedBounds.Height;
                    Update(false);

                    //var form = (System.Windows.Forms.Form)System.Windows.Forms.Control.FromHandle(mWindow.Handle);
                    //form.Location = new System.Drawing.Point(mLastWindowedBounds.X, mLastWindowedBounds.Y);
                }

                Console.WriteLine("ResolutionChanger: Full Screen state changed");
            }
        }

        public int DesiredWidth
        {
            get {
                return mDesiredWidth;
            }

            set {
                mDesiredWidth = value;
            }
        }

        public int DesiredHeight
        {
            get {
                return mDesiredHeight;
            }

            set {
                mDesiredHeight = value;
            }
        }

        public bool FullScreen
        {
            get {
                return mFullScreen;
            }

            set {
                mFullScreen = value;
                if (mFullScreen)
                {
                    mDesiredWidth = mGraphics.GraphicsDevice.DisplayMode.Width;
                    mDesiredHeight = mGraphics.GraphicsDevice.DisplayMode.Height;
                }
            }
        }

    }
}

```
> 2 votes

---
Tags: graphics, monogame, linux, window-management
---


title: Collision Direction Detection

text:
# Question
Title: Collision Direction Detection
I'm making an RPG game where players and enemies can collide with walls. Right now it pushes the player off the wall when he tries to 'go through' it. However, I detect which way he should be pushed based on his current direction. This means that enemies can still push him through walls. Also if the player moves diagonally, detection doesn't work properly. This is a problem...

I'm using SFML and these Collison-Detection methods: https://github.com/LaurentGomila/SFML/wiki/Source:-Simple-Collision-Detection-for-SFML-2

Specifically I'm using this method:

```
bool BoundingBoxTest(const sf::Sprite& Object1, const sf::Sprite& Object2)
{
    OrientedBoundingBox OBB1 (Object1);
    OrientedBoundingBox OBB2 (Object2);

    // Create the four distinct axes that are perpendicular to the edges of the two rectangles
    sf::Vector2f Axes[4] = {
        sf::Vector2f (OBB1.Points[1].x-OBB1.Points[0].x,
        OBB1.Points[1].y-OBB1.Points[0].y),
        sf::Vector2f (OBB1.Points[1].x-OBB1.Points[2].x,
        OBB1.Points[1].y-OBB1.Points[2].y),
        sf::Vector2f (OBB2.Points[0].x-OBB2.Points[3].x,
        OBB2.Points[0].y-OBB2.Points[3].y),
        sf::Vector2f (OBB2.Points[0].x-OBB2.Points[1].x,
        OBB2.Points[0].y-OBB2.Points[1].y)
    };

    for (int i = 0; i<4; i++) // For each axis...
    {
        float MinOBB1, MaxOBB1, MinOBB2, MaxOBB2;

        // ... project the points of both OBBs onto the axis ...
        OBB1.ProjectOntoAxis(Axes[i], MinOBB1, MaxOBB1);
        OBB2.ProjectOntoAxis(Axes[i], MinOBB2, MaxOBB2);

        // ... and check whether the outermost projected points of both OBBs overlap.
        // If this is not the case, the Seperating Axis Theorem states that there can be no collision between the rectangles
        if (!((MinOBB2<=MaxOBB1)&&(MaxOBB2>=MinOBB1)))
        {
            return false;
        }
    }
    return true;
}

```

Note that the method only checks if the sprites collide, not **how or where** they collide. I don't know how exactly the collision detection works, I've tried printing out the OBB values but they're nonsensical to me.

Should I somehow modify the function, or is there another way of doing collision direction detection? I'm stuck here.

**UPDATE**

I managed to actually check for which direction the player was colliding with the wall. I have a really odd problem now: *It only works properly on the last wall I place.*

* I have 4 booleans (canWalkUp, canWalkDown, canWalkLeft, canWalkRight) to check for if the player is holding down both left and right, or up and down - so they don't negate each other. This prevents wonky movement.
* I also have 4 booleans to check if the player is currently colliding with a wall.

The code which handles player-boundary collision is as follows:

```
void EventHandler::collisionPlayerBoundary(std::shared_ptr<Entity> player,     std::shared_ptr<Entity> boundary)
{
std::vector<sf::Vector2f> distances = Collision::BoundingBoxDistance(player->sprite, boundary->sprite);
float pushSpeed = 75;
if(distances.at(0).y < 20) //push left!
{
    std::cout << "pushing left" << std::endl;
    player->pushX = -pushSpeed;
    player->canWalkRight = false;
    player->collidingRight = true;
}
if(distances.at(1).y < 20) //push down!
{
    std::cout << "pushing down" << std::endl;
    player->pushY = pushSpeed;
    player->canWalkUp = false;
    player->collidingUp = true;
}
if(distances.at(0).x < 20) //push right!
{
    std::cout << "pushing right" << std::endl;
    player->pushX = pushSpeed;
    player->canWalkLeft = false;
    player->collidingLeft = true;
}
if(distances.at(2).x < 20) //push up!
{
    std::cout << "pushing up" << std::endl;
    player->pushY = -pushSpeed;
    player->canWalkDown = false;
    player->collidingDown = true;
}
}

```

# Answer
> 0 votes
First you need to add all forces (movements) applied to the player, in this case both the intentional movement and the enemy pushing (collisions with enemies first).

If both push against one another equally you're left with (0, 0) and you're done.

Otherwise, iteratively do collision detection (environment and enemies) using the potentially new position `(current_position + movement)`, and reduce movement until there is no collision.

As long as movement isn't larger than the smallest AABB (incl. the character) discrete collision checks should be fine (as opposed to full raycast).

You can add a check `if player_still_collides_post_push then hurt_player`

Optionally you can check/reduce both X and Y movements separately to allow the player to slide along walls when pushed away. This works for square maps, maps with diagonals gets more complicated.

You can make enemy collisions "soft" allowing the player to intersect with enemies and not walls so the player can still squeeze out of a pinch while not going through walls.

# Answer
> 0 votes
There are two ways to this that I know of. The first is to separate the velocity of object into independent axis. For example, if you are at (0,0) moving towards (5,5), you would first move the object to (5,0) and then from (5,0) to (5,5). If there is an obstacle at (2,0) Then starting from (0,0) you would move object to (2,0) and then to (2,5).

Of course, the issue with this implementation is that the actual path taken by object and the path used for collision are different and thus sometimes your object will phase through objects and other times stopped by an "invisible" object. This can be alleviated (not completely) by ensuring the velocities are small. This might be enough for your needs.

The second method would be a sweep which actually returns the point of intersection and the normals of intersection. This method is more involved and here is an excellent tutorial: http://www.gamedev.net/page/resources/\_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084.

---
Tags: c++, collision-detection, sfml, direction
---


title: Translating Objects in Worldspace

text:
# Question
Title: Translating Objects in Worldspace
Given the worldspace coordinates of a collection of arbitrarily positioned objects, how do I translate them while preserving their relative placement? For instance, I have a table and a few bowls that are placed on top of it at (x1, y1, z1) and wish to moved them to (x2, y2, z2).

# Answer
> 2 votes
One popular method is to use parent-children hierarchies to store matrix transformations in relative space. If you are moving the table and everything along with it, the bowls are the children of the table as far as their location is concerned. This can be done as simply as storing and pushing matrices in an array, and multiplying them. This could also be a simple use of a scene graph (note that scene graphs are not strictly defined as a spatial hierarchy though, as they can be used for many purposes).

`PushMatrix()` and `PopMatrix()` are examples in OpenGL for stack local transformations. However, these operations are expensive if you frequently look up their world position this way. It's a better to store an extra matrix for each object for its absolute position in space. You access this matrix when the object in question is not being moved at the moment, to save performance. Multiplication of local matrices then would happen only when the object is moved, and then its world (absolute location) matrix will be updated.

# Answer
> 1 votes
This problem is called Inverse Kinematics. In Inverse Kinematics, you begin with some "desired" translation and rotation for the endpoint in a kinematic chain. The goal is to determine where all the other objects in the kinematic chain are (their rotations and translations), and joint angles (if you have any joints).

In your case, you are putting in the rotation/translation of the final object in the chain (the bowl), and asking for the required rotation/translation of the first object in the chain (the table). Unfortunately, there is no general solution to your problem, since there are an *infinite* number of ways to place the bowl at `(x2, y2, z2)` while preserving the relative transform between the bowl and the table. (because you can rotate the objects arbitrarily and preserve the local transformation).

However, all you need to do to get *a single* solution is to invert the transformation between the table and the bowls. For this, I am going to assume you already know about transformation matrices.

Call the relative transform matrix between the table and the bowls `H_tablebowl`. Call the transform from the world to the table `H_table`. The global transform `H_bowl = H_table * H_tablebowl`. Now, what you're asking is, suppose we fix `H_bowl` to some value `H_desired`. How then do we find the resulting `H_table`? We know:

```
H_desired = H_table * H_tablebowl

```

And therefore

```
H_table = H_desired * inverse(H_tablebowl)

```

If you have just the *translation* of the bowl, then you can arbitrarily fix the orientation to some value (like the identity). Then the solution simply becomes:

```
translation_table = translation_bowl_desired - translation_table_bowl

```

---
Tags: 3d, mathematics, algorithm, transformation
---


# Question
Title: Launch Velocity for Simple 3D Projectile
This is a pretty easy question, but I can't quite figure out the answer. I have:

1. The initial position of a projectile.
2. The gravity vector.
3. The (stationary) target I want to hit.
4. A maximum launch speed of the projectile.

I want to calculate the initial velocity the projectile must be launched at to hit the target, assuming it follows a ballistic trajectory.

# Answer
> 1 votes
I solved it thanks to one of the comments:

```
Vector3 displacement = (end - start);
float dist = displacement.Length();
float T = dist / MaxSpeed;
Vector3 initial_velocity = 1.0f/T*(displacement) - 0.5f*Gravity*T;

```

---
Tags: mathematics, physics, projectile-physics
---


title: Creating a single GUI Text with Fade-In

text:
# Question
Title: Creating a single GUI Text with Fade-In
I have this line of code

```
void Update () {

    float alVal = 0.0f;
    float damping = 1f;
    alVal += damping * Time.time;
    GameObject text2 = new GameObject();

    text2.AddComponent (typeof(GUIText));
    text2.guiText.color = new Color (1f,1f,1f);
    text2.guiText.name = "name";
    text2.guiText.text = "YOLOMF";
    text2.guiText.pixelOffset = new Vector2 (100, 100);

    text2.guiText.color = new Color(1f,1f,1f,alVal);

    Debug.Log (alVal);

}

```

I want to create a SINGLE TEXT, but I guess the Update() function keeps on making more.

I need that SINGLE TEXT to do an animation of Fade-In that's why it is in Update()

# Answer
This is a rough translation of the code you've provided into something that does not spawn a new GameObject on every frame.

```
private GUIText textObject;

void Start ()
{
    // Initialize the text when the behavior is "started"
    GameObject text2 = new GameObject();
    textObject = text2.AddComponent<GUIText>();
    textObject.color = new Color (1f,1f,1f);
    textObject.name = "name";
    textObject.text = "YOLOMF";
    textObject.pixelOffset = new Vector2 (100, 100);
}

void Update ()
{
    // Fade a bit every frame ...
    float alVal = 0.0f;
    float damping = 1f;
    alVal += damping * Time.time;
    textObject.color = new Color(1f,1f,1f,alVal);

    // TODO: Re-architect this to clean itself up.
}

```

There's several ways to improve the architecture of this but the "best" way completely depends on other architecture not defined here. This will have the effect you're looking for but I'd recommend you alter it to clean up after itself.
> 2 votes

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


# Question
Title: Rendering order of shadowing point lights?
I'm implementing shadow mapping in my deferred rendering engine. I've got spot lights working, and now I'm working on point lights. Currently, I do it like this:

```
// Loop through the point lights
for each point light do

    Loop through "directions"
    for I = 1, 6 do
        Render the shadow map for direction 'I'
        Render the point light
    end
end

```

This works fine, but is this sub-optimal? Should I instead render all the shadow maps at once? If so, how would I handle all the shadow maps at once in the second phase when rendering the light volume?

# Answer
> 2 votes
If I understand your question correctly, you are building and applying the shadow maps at the same time. You really do not want to do that.

If you are smart about this, you can vary the frequency of shadow map updates and save massive amounts of memory bandwidth necessary to actually fill the shadow maps (*e.g.* if nothing in the world moves inside the light volume and the light doesn't move, then there is no need to recompute the shadow map). I have gone as far as to determine which of the individual faces in a shadow cubemap need to be recalculated - a lot of work to implement, but worth it.

Another thing to consider is that you do not actually have to update shadow maps every frame. Surprisingly, for distant light sources or a reasonably small number of nearby light sources you can get away with updating at 1/2 or lower render frequency without the end-user noticing. I have used this to great success in my own work, on lower-end GPUs I update half of the shadow maps every frame (so a full update takes 2 frames) and very few people ever notice ;)

In short, consider implementing some logic that allows you to update the shadow maps periodically instead of every frame. Performance should improve drastically.

# Answer
> 0 votes
You can use a cube map for point lights.

The cube shadow map might need to be rendered face-by-face as before but the last step can be done as one pass.

---
Tags: opengl, shadow-mapping, deferred-rendering
---


title: What is FOVx in this diagram?

text:
# Question
Title: What is FOVx in this diagram?
a beginner game developer here. I have recently taken upon learning about 3D game development and I am stuck on a simple matrix problem.

The image is found from this article: http://www.codinglabs.net/article\_world\_view\_projection\_matrix.aspx

I am trying to represent this matrix in my code but I am not sure what precisely is meant by FOVx and FOVy. What is the difference and how would I represent this in my perspective matrix? I am not using any 3D api.

# Answer
Here's wiki on topic: Field of view in video games

X and Y angles can be set separately to allow for wide/tall views. For example if you need a panorama for 3 displays like so, with default FOVy, but 120 degrees FOVx:
> 2 votes

---
Tags: 3d, matrix, software-rendering
---


# Question
Title: Torch fire always up regardless of handle direction
I have a prefab from some asset pulled into our project. It is a simple torch.. handle and a particle system for the fire. Works perfect if mounted on a wall and torch angle adjusted no problem.

Now the problem. I attach the torch to the hand of a walking person, so the arm is not "fixed" and is in a more fluent movement environment. How can I adjust this (C# scripts possible to attach too) so that the fire element is always in an upright burning position even if the arm/hand are in a somewhat swinging position.

I'm still a little early on in my gaming exposure, but 3+yrs in C#.net and OOP experience.

# Answer
you can set the velocity to "world space" and just provide a vertical velocity, the particle system will follow the hand orientation, but the particles emitted will always move upwards.
> 2 votes

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


# Question
Title: Handling image size based on different ios device versions (Unity2D)
This game is built using Unity 4, C#, and the 2D toolkit. In the unity game scene settings, it is set to (ios 5 tall) and I matched the Menu background dimensions with the dimensions of an ios 5 tall device. When testing this build on a different ios device(ios 4 etc...), the menu background doesn't fit (stretch) to the width and height of the tested device's dimensions. The answer seems pretty obvious that i'm not handling all devices dimensions.

What would be a good approach on handling images based on different ios devices? Are there any build settings to build a project that handles each device dimensions?

Thanks in advance for any advice or a good approach for cross-device handling

# Answer
to figure out which device the app is running on have a look at:

http://docs.unity3d.com/ScriptReference/iPhone-generation.html function http://docs.unity3d.com/ScriptReference/iPhoneGeneration.html enumeration list

example here: http://forum.unity3d.com/threads/iphone-generation.32742/
> 0 votes

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


title: Problems with Raycasting Requirements

text:
# Question
Title: Problems with Raycasting Requirements
Im working on a script which kinda works like an Enemy AI. Its kinda like a detection system with requirements that are required to be met.

This is a recent question i asked using my code Raycast Flashing problem

So this is the how it works:

```
using UnityEngine;
using System.Collections;

public class Script_v2 : MonoBehaviour {

    // Player Properties
    private GameObject player;
    public Vector3 playerSize;
    private Vector3 playerTransform;
    public Vector3 playerTransformTL;
    public Vector3 playerTransformTR;
    public Vector3 playerTransformBL;
    public Vector3 playerTransformBR;

    private Vector3 newPlayerTransformTL;
    private Vector3 newPlayerTransformTR;

    private Vector3[] playerRaycastPoints;

    // Enemy Properties
    private Vector3 enemyTransformTL;
    private Vector3 enemyTransformTR;
    private Vector3 enemyTransformBL;
    private Vector3 enemyTransformBR;

    public float distance;
    public Vector3 enemySize;

    // Detection Alerts
    public bool outOfVision;
    public bool alerted;
    public bool alertedLock;
    public bool dead;

    Ray ray;
    RaycastHit hit;

    // Use this for initialization
    void Start () {
        playerRaycastPoints = new Vector3[4];

        distance = 3f;
        player = GameObject.FindGameObjectWithTag ("Player");

    }

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

        enemyTransformTL = new Vector3 (transform.position.x - 0.5f, transform.position.y + 0.5f, transform.position.z);
        enemyTransformTR = new Vector3 (transform.position.x + 0.5f, transform.position.y + 0.5f, transform.position.z);

        enemyTransform_TL_TR ();
        detectionAlert ();
        Reference_Player_Transform_Points ();

        Debug.Log (alerted + " " + alertedLock);

    }

    void OnDrawGizmos() {
        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere (new Vector3(transform.position.x - 0.5f, transform.position.y + 0.5f, transform.position.z), distance);
        Gizmos.DrawWireSphere (new Vector3(transform.position.x + 0.5f, transform.position.y + 0.5f, transform.position.z), distance);
    }

    public void enemyTransform_TL_TR() {

        alerted = true;
        alertedLock = false;
        for (int i = 0; i < 4; i++) {

            double enemyAngleTL = Mathf.Atan2(playerRaycastPoints[i].y - ( transform.position.y + 0.5f ),
                                              playerRaycastPoints[i].x - ( transform.position.x - 0.5f )) * 180f / 3.14159265f;
            //Debug.Log (enemyAngleTL);
            double enemyAngleTR = Mathf.Atan2 (playerRaycastPoints[i].y - (transform.position.y + 0.5f),
                                               playerRaycastPoints[i].x - (transform.position.x + 0.5f)) * 180f / 3.14159265f;

            Vector3 directionTL = (playerRaycastPoints[i] - enemyTransformTL).normalized;
            Ray rayTL = new Ray(enemyTransformTL, directionTL);
            RaycastHit hitTL;
            Vector3 directionTR = (playerRaycastPoints[i] - enemyTransformTR).normalized;
            Ray rayTR = new Ray (enemyTransformTR, directionTR);
            RaycastHit hitTR;

            //Debug.DrawRay (rayTR.origin, rayTR.direction * distance, Color.yellow);

            if(Physics.Raycast (rayTL, out hitTL, distance)) {
                if((enemyAngleTL > 90 && enemyAngleTL < 180)) {
                    Debug.DrawRay (rayTL.origin, rayTL.direction * distance, Color.yellow);
                    alerted = false;

                }
                else {

                    alertedLock = true;
                }

            }
        }
        //alertedLock = true;
    }

    public void detectionAlert() {
        if (alerted == false && alertedLock == false) {
            gameObject.renderer.material.color = Color.green;
        }
        if (alerted == false && alertedLock == true) {
            gameObject.renderer.material.color = Color.magenta;
        }
        if(alerted == true && alertedLock == false) {
            gameObject.renderer.material.color = Color.blue;
        }
        if(alerted == true && alertedLock == true) {
            gameObject.renderer.material.color = Color.red;
        }
        else {
            //gameObject.renderer.material.color = Color.red;
        }
    }

    private void Reference_Player_Transform_Points() {

        playerSize = player.transform.localScale;

        playerTransformTL = new Vector3(player.transform.position.x - (playerSize.x / 2),
                                        player.transform.position.y + playerSize.y  / 2,
                                        player.transform.position.z);
        playerTransformTR = new Vector3(player.transform.position.x + (playerSize.x / 2),
                                        player.transform.position.y + playerSize.y  / 2,
                                        player.transform.position.z);
        playerTransformBL = new Vector3(player.transform.position.x - (playerSize.x / 2),
                                        player.transform.position.y - playerSize.y  / 2,
                                        player.transform.position.z);
        playerTransformBR = new Vector3(player.transform.position.x + (playerSize.x / 2),
                                        player.transform.position.y - playerSize.y  / 2,
                                        player.transform.position.z);

        playerRaycastPoints [0] = playerTransformTL;
        playerRaycastPoints [1] = playerTransformTR;
        playerRaycastPoints [2] = playerTransformBL;
        playerRaycastPoints [3] = playerTransformBR;

        /*
            Debug.Log (playerTransformTL);
            Debug.Log (playerTransformTR);
            Debug.Log (playerTransformBL);
            Debug.Log (playerTransformBR);
        */
    }
}

```

The problem with this code is that. If you look in the diagram. alertLock should be false when its outside the greenZone.

But for some reason it doesnt. When the player is fully inside the greenZone, the enemy turns green. I dont know why.

# Answer
> 0 votes
I think you have a typo in `detectionAlert()`...

`(alerted == false && alerted == false)` should be `(alerted == false && alertedLock == false)`

---
Tags: c#, unity, vector, raycasting
---


# Question
Title: How can I expose a property to Unity that should be treated like an asset path?
I want to be able to do something like this:

```
public FileInfo XmlBehaviourFile;

```

And then use the asset browser in the Unity editor to select an asset. Ideally, I would like to limit it to XML files but that isn't too important.

I am aware of `TextAsset` but I can only access either a string or byte array of the contents. I can probably make this work, but at the moment, my library takes a `FileInfo` and handles the reading itself.

Is there a Type I can use that will make Unity let me choose a file in the editor and then simply store the path (ideally, it would handle making sure the path is relative and including the asset in the build).

Alternatively, would it be possible to write such a type that would work, I've not extended Unity, but I am aware it is possible.

# Answer
> 1 votes
I think it's a bad idea to store the path; if you want to pick it from the asset browser, then your file is handled by the asset database, and referencing it through this is much better: it will automatically get gathered into builds, you can move or rename it, etc.

So, the real question is, why do you need a FileInfo? Note that in a build, the file won't exist as far as the OS is concerned, it will be part of a bigfile (Unity packages all the assets into one giant sharedAsset file). So if you need to read the file in builds, you **will** need to change your API to accept a string or TextAsset directly.

If you need to read the file at editor-time, you can use AssetDatabase.GetAssetPath() to get the file path, then the FileInfo. But again, won't work in builds.

Now if your XML files were outside of the asset database (outside of the project/Assets folder), like if you plan on getting them from a server or whatever, then it's a different issue...

Lastly... are you sure you need an XML file? couldn't you use a ScriptableObject instead?

---
Tags: unity
---


title: Synchronization with game tick

text:
# Question
Title: Synchronization with game tick
I'm working on a multiplayer game and it's currently set up like this. It accepts packets from the client on the fly and does whatever processing it needs to. There is also a main game tick which is set up like so:

```
for every online player
    update every player in the region

for every online player
    reset flags

```

The problem I see that can happen is that since it handles packets on the fly, it may modify something between the updating and the flag reset, which could cause it to completely ignore something. I don't think it's possible to synchronize it using the actual synchronize block since it can't update and reset flags at the same time - it needs to reset flags after it updates every player.

The only solution I see is not processing packets on the fly and doing it in the main loop, but this could hurt performance. Is this the best solution, or is there another option I'm not considering?

Thanks

# Answer
> 1 votes
Welcome to the beautiful world of thread safety and race conditions. The problem you see is very real and a nasty source of impossible to reproduce bugs.

A solution I am using is to not process received network messages immediately. Instead, I have the network system add all received input events into a synchronized list.

One step of the general update loop is then to process that list in a `synchronized` block and clear it afterwards:

```
synchronized(messageList) {
     for (Message message: messageList) {
          // process message
     }
     messageList.clear();
}

```

As long as one thread is in a `synchronized` block for a specific object, any other threads who try to enter a `synchronized` block for the same object (which they will do inside the `add` method of a synchronized list) will wait until that thread is finished. So no network events will be pushed while the message queue is being processed and cleared. Those events will be pushed afterwards and will then be the first to get processed in the next update tick.

That way you process all of your network events at a controlled point of your update method and avoid any race conditions caused by network events being processed at an unexpected moment.

---
Tags: java, multiplayer, multithreading, synchronization
---


# Question
Title: Can I (safely) assume that people playing my game have a middle mouse button?
The title pretty much says it all.

I am currently writing a desktop game, which will probably not be played by the casual gamer. Thus my expectation is that nearly every user will most likely already have a mouse with a scroll wheel + button. Is that true?

This question is for "gamers" - I don't care if my grandmother's laptop doesn't have that button.

(Of course I know that I should think about a system that allows to change the input settings to make the game playable - even without a third mouse button.)

# Answer
> 34 votes
Although you are targeting desktops, there *will* be players on (gaming) laptops and for some of them, it will be an inconvenience to get a mouse before being able to play your game. It would sound like a good thing to me, if you were to support alternative control schemes or customizable controls.

This is not a very "sciency" answer - I've just run into this problem a lot with games and tools I developed. My experience might not reflect the one you are about to acquire, so feel free to disregard this advice.

# Answer
> 22 votes
It really depends what you mean by "assume". Are you making this assumption at the point of designing your gameplay mechanics? Or at the point of deciding whether or not to implement fully customizable key bindings?

You could mean "**I assume real gamers have a 3 button mouse, therefore I don't need to offer the option to rebind *bayonet-thrust* to a keyboard button**". If you think this you are wrong. Always, always wrong. I personally have my peculiarities when it comes to input configuration, as will a sizable chunk of your player base. E.g. I started playing FPS games when I was much younger and my left little finger struggled with the default crouch/sprint arrangement. I swapped them and got used to them being swapped. I will always resent games that lack this option to rebind. I also weirdly expect "up" to mean "up" with a mouse, but with a controller I like it to mean "up" in first-person and "down" in third person. Games that let me configure these separately give me a warm glow. Games that don't give me the option better not have me switching between the two during an action sequence (e.g. 3rd melee, 1st person iron-sights), or I'll find myself looking at my feet or the sky as the action plays out around me.

However, you could easily mean: "**I assume a middle mouse button exists when deciding that there will be 3 unique actions my player can execute at a full run, while comfortably strafing either left or *RIGHT***" If this is going to be true of your game then rebinding MMB to a keyboard button is an option (and you really should offer the option), but probably not an ideal option. I strongly feel that in this situation you should assume that your players will have the appropriate equipment, rather than hamstring your gameplay mechanics. Certain games will always suit certain input methods better than others. ***Imagine if the Assassin's Creed series had cut out any gameplay mechanics that wouldn't have played equally well on a trackpad.***

To sum up: don't compromise on gameplay, but offer every configuration option you can imagine.

# Answer
> 10 votes
Many laptops lack a middle button, especially those with a trackpad, and you need special software to emulate it.

Mac laptops have only one button. Right-click is pretty easy (two finger click) and not uncommon in Mac games, and the two finger drag to scroll isn't bad, but only in slower paced games. However, there is no concept of a middle click in the Mac Trackpad system settings. You need special software.

You might say "who cares about laptops, nobody games on a laptop". The Steam Hardware & Software Survey is a wealth of information about what people actually use. 70% of the Mac users on Steam are using a laptop. PC laptop gamers are harder to track, but you can get an idea by looking at the video cards and noting the mobile ones (GeForce blah blahM, Intel HD Graphics, "Mobility", and "Mobile"). By my reckoning that's 30% of the market.

For example, I have a custom built desktop PC at home for gaming with a five button Logitech gaming mouse. Tomorrow I will get on a seven hour flight. I will have my Macbook Pro laptop and 200+ Steam and GOG games to choose from. I will not have room on the tray for a mouse. The games I will be playing will be ones which work well with a trackpad.

***Absolutely*** allow ***all*** of your controls to be reconfigured. Even if people have the buttons, there will be people who will not like your default controls. It's such a small thing to avoid your customers getting frustrated.

FWIW I generally avoid the middle mouse button because it can trigger the scroll wheel. I also avoid the scroll wheel to switch weapons because I find it slow in games with more than two choices. For something like a melee attack or crouch, I typically use F or a thumb side button.

# Answer
> 5 votes
Some people use a trackball (some trackballs have no middle mouse button), trackballs generally are just as good pointing devices for players as ordinary mouses.

The trackball I linked has no middle mouse button, and (at least on Windows) has an unusable scrollbar; despite these shortcomings I managed to finish quite few action games using it ;).

# Answer
> 1 votes
Even if I do have a middle mouse button, its awkward to click. I personally would not ever want to use it for anything other than scrolling. Also, speaking from experience, having the middle mouse button be set as scrolling/zooming has also caused me grief in the past. There was a game that I played (called Rappelz in case anyone is curious) in which the middle mouse button was the only control set to zoom in/out. I used to play with a mouse without such a wheel, and several times the game changed the zoom without me knowing why, and it was quite an annoyance trying to fix it afterwards.

TLDR: In my opinion, using the middle mouse button is not a good idea

# Answer
> 0 votes
I would certainly include a controller customization screen in the settings of the game. Even though you noted that you are aware of a controller-customization system, I think it is the correct way to do this and it is the answer to your question.

I would quickly make a customization class and assign the keys by code (initially/harcoded), so I could just continue developing the game without losing time. Later I can get back to the customization class to create a UI.

---
Tags: input, mouse, user-experience
---


title: Implementing line-of-sight in 3D?

text:
# Question
Title: Implementing line-of-sight in 3D?
I've been searching for information on implementing line-of-sight in my game. I've found some great resources for 2D implementations that produce pixel-perfect results, but there's very little info on 3D implementations.

So far, I've found these methods that could be used to achieve line-of-sight:

* Shadow maps
* Shadow volumes
* 3D grids / octrees

However, each of these seems to have limitations. Shadow maps are quite expensive to calculate, especially for omni-directional line-of-sight (just like omni-directional shadows). Shadow volumes have special requirements for geometry and are rather difficult to produce. 3D grids and octrees are not pixel-perfect and require an additional renderer on top of the grid implementation.

Have I missed something here? Which method would be the most suitable for a top-down 3D game?

# Answer
> 6 votes
The first thing I would suggest is to use a 2d implementation like the one in Teleglitch, like you said yourself, you found solutions, this is a lot simpler.

Line of sight is a gameplay mechanic. If the game is top-down, the gameplay is essentially 2d and there is likely a limited benefit to using actual 3d line of sight.

No, you are absolutely right. This is not a simple problem. Imagine that without knowing anything about the content (without making assumptions about the visual space / the geometry of the environment), you actually "need" to send a ray for each tiny spot you wish to decide on. It is like checking collisions for a bunch of infinitely small balls moving towards all directions that are within the viewing angle of the source. It is not simple in 2d either if the data is complex enough, the advantage is that in 2d, you only need to sample a 1d space. In 3d you need to sample a 2d matrix so the amount of work needed especially for real time applications is very daunting.

Using shadow volumes is probably your best bet. Octrees could help to reduce the amount of work too but those are both suggestion you alread made.

---
Tags: 3d, line-of-sight
---


# Question
Title: Can I break the UI MASK hierarchy in unity 4.6?
I'm using unity 4.6. I saw a couple of UI masks tutorials and saw that there's a certain hierarchy I can't seem to break:

* -Canvas
* --- Panel (holds the mask component)
* --------Image

**I want to move the mask and leave the image in its place.**

(Attach the mask to a moving object, and by that, exposing the image by the moving object position)

I have 2 problems with it:

My moving object barely moves my mask (I guess because of the canvas). The image is a child of the mask, so even if it will move, it will move with it. Can I even do it?

# Answer
I Solved this by detaching the image from the mask parent, move the mask, and then reattach it (Set the image's parent to the canvas and after moving the mask set it to be the image's parent again). That way the image stays still and the mask is slowly revealing the image.
> 2 votes

---
Tags: unity, masking
---


# Question
Title: Why would it be faster to render using multiple canvas elements?
This video suggests that rendering using multiple `canvas` elements helps performance.

How does this work?

The idea was to use one for the player, one for the enemies, another for the background, though I really don't understand how could it be faster if you use more of the same thing.

Could someone clarify?

# Answer
Multiple canvases can help in *some* cases. Just as a quick example - say you have 2 layers (canvases) to your game.

The background of your game is not going to change very frequently, for example. So one canvas will be dedicated to just rendering the background of your game. This means you only have to render the background once, and only re-render it when it changes. The other layer of your game can render anything that moves constantly.

If all were rendered on the same canvas, the background would be re-drawn every frame along with everything that moves, and this can cause a more slow rendering time.

I hope this was somewhat clear - I can elaborate more if needed.
> 10 votes

---
Tags: 2d, javascript, performance, html-canvas
---


title: Should unbind buffers?

text:
# Question
Title: Should unbind buffers?
I'm making some tests with OpenGL ES 2 and got some questions, my current program is like that:

```
Init
-------
-> create index buffer
-> fill index buffer glBufferData …
-> create vertex buffer
-> fill vertex buffer glBufferData …

Draw
-------
 1. Apply vertex buffer

    -> Bind VAO
       -> bind vertex buffer
          - enable attributs (glVertexPointer, …)
       -> unbind vertex buffer
    -> Unbind VAO
    -> Bind VAO

 3. Apply index buffer
 4. Draw

```

**The problem**

The given code crash, after some researches, I've understood why: I need to unbind my index buffer in init part (after "fill index buffer glBufferData") or unbind it before the first "Bind VAO"

**My questions are:**

* Can I put my index buffer in VAO (VAO stock index buffer?)?
* Did I have to unbind buffers after each update (glBufferData)?

In my application I've got some buffers who are updated on each frame (Exemple: Particles) so I've got an OpenGL stack like that:

```
-> bind buffer 1
-> update buffer 1
-> close buffer 1
-> bind buffer 1
-> draw

```

First 3 lines update the Vertex buffer, the two last draw object, that should be something like that:

```
-> bind buffer 1
-> update buffer 1
-> draw

```

Thanks

# Answer
You seem to be doing a lot on unnecessary binding/unbinding. If you are using a VAO, then you should only bind the VAO when you set it up and when drawing the geometry. You only bind the VBO/IBO again when you need to update them.

After drawing or updating a buffer, you don't necessarily have to unbind it, though it might be a good idea to do so to avoid accidental writes to buffers that were left bound.

Now taking your fist sequence of operations, this is the overall order I would expect to see:

### On init:

1. Create & bind a VAO. Any VBO and IBO that you bind in the sequence will be associated with the current VAO (this one).
2. Create & bind index buffer.

* Fill index buffer with `glBufferData/glMapBuffer`.
3. Create & bind vertex buffer.

* Fill vertex buffer `glBufferData/glMapBuffer`.
4. Set up vertex attributes with `glEnableVertexAttribArray/glVertexAttribPointer`, etc.
5. Optionally unbind everything to avoid accidental modification of the buffers and VAO. Remember to *unbind the VAO first*. E.g.: `glBindVertexArray(0);`

### On draw:

1. **If only drawing the buffers**:

* Bind the VAO;
    * Perform the draw call(s).
2. **If updating and drawing**:

* Bind the VAO, VBO, IBO;
    * Update the buffers (updating vertex atributes is only necessary if the vertex format has changed);
    * Perform the draw call(s).
3. Optionally unbind to avoid accidental modification of the buffers and VAO.

That's as simple as that. This order of operations should function without problems.
> 20 votes

---
Tags: opengl, opengl-es2
---


# Question
Title: MonoGame: Draw thousands of quads without hardware instancing
In my game, every bit of geometry is a textured quad billboard in 3D. I have many thousands of these things on screen at once, sometimes with overdraw. As I understand it, there are a few ways I can go about drawing these:

1. Have a single VBO per type of quad (ie, unique set of texture coords). Batch the VBO and texture, but make multiple draw calls. Looks something like this:

```
foreach (Quad quad in quadTypes)
{
    // The VBO just contains 4-6 vertices.
    GraphicsDevice.SetVertexBuffer(quad._vertexBuffer);
    Shader.SetTexture(quad._texture);

    // Draw each instance using multiple draw calls
    foreach(QuadInstance instance in quad._instances)
    {
       Shader.SetWorldMatrix(instance._worldMatrix);

       foreach(ShaderPass pass in Shader._passes)
       {
           pass.Apply();
           GraphicsDevice.DrawPrimitive(TRIANGLES);
       }
    }
}

```
2. Make a single draw call by somehow combining all the triangles of all the instances of a quad type. Looks something like this:

```
foreach (Quad quad in quadTypes)
{
    Shader.SetTexture(quad._texture);
    // Probably can cache a vertex buffer for when quads are created/destroyed instead.
    VertexBuffer vertexBuffer = new VertexBuffer();

    foreach(QuadInstance instance in quad._instances)
    {
       // Add all of the (world transformed) triangles of this instance to
       // the vertex buffer
       vertexBuffer.AddAll(instance.CreateTriangles());
    }

    // Draw all the quads with a single draw call and vertex buffer.
    GraphicsDevice.SetVertexBuffer(vertexBuffer);

    foreach(ShaderPass pass in Shader._passes)
    {
        pass.Apply();
        GraphicsDevice.DrawPrimitive(TRIANGLES);
    }
}

```
3. True hardware instancing. This is currently how I do it in my (XNA HiDef profile) game, but I can't figure out a way to get it to work in Monogame. With true hardware instancing, each instance is represented as a vertex, and the GPU creates all the necessary duplicate vertices in a single draw call.

In general, which one of these is most desirable? 1) makes many draw calls, but saves the most memory. 2) has a single draw call, but requires creating a vertex buffer for all of the instances, which seems really inefficient, and 3) has the best of both worlds but is not widely supported. Is there a fourth way that I'm missing?

# Answer
> 3 votes
Your question title explicitly states "thousand of quads". That is really not a lot of geometry. I would have to say that unless you expect millions, or are targeting mobile, I suggest going with simple batching to reduce draw calls. It is easiest to implement and should do the job admirably.

**If you really do need more geometry, read on...**

Since Monogame genuinely does not support this yet, I can only suggesting extending it using the underlying OpenTK, or looking around on the Monogame issues to see if someone else has already made headway into hardware instancing and is likely to provide source that you can adapt.

I can say definitely that OpenGL 3 hardware instancing is not much harder to implement than rendering single geometries; however, integrating this into Monogame would probably be a lot harder to do *right*. If you do implement hardware instancing in OpenTK, allow me to save you some time by strongly suggesting instancing **without** using `gl_InstanceId` & using uniform arrays for instance data -- this is an outdated, inefficient, and limited approach. The best way is to use VAO + a vertex buffer containing all your per-instance data (e.g. model matrices) and uniforms for whatever is shared by all instances (e.g. view-projection matrix and textures).

**Your approaches**

It depends on cost. If calculating all transformations of all vertices on CPU is less than the cost of all the draw calls, it's definitely worth doing simplistic batching i.e. method 2. Otherwise you may be better off sticking with method 1 because you'll need to get per-instance matrices across without the cost of calculating them all on CPU. However, there is middle ground... see the below paragraph for more information on getting these across individually within a single draw call.

**Best practices**

Some sources outlining best practices (and their pros and cons) for where hardware instancing is not available:

Putting your per-instance matrices etc. in a texture can be very fast if you can wrangle it. You can also use a uniform array but I believe there is a fairly low limit on the number of individual uniforms you can have in a given shader program. Either way you are going to need to index into these in view of the lack of `glAttribDivisor` & `gl_InstanceId` -- this requires that you repeat the appropriate index for every single vertex of every instance, which is a bit costly but can't be avoided, and gets the job of reducing draw calls done.

---
Tags: xna, c#, graphics, monogame, vertex-buffer
---


# Question
Title: Movement on objects in 2D tile/grid based game
This question is an addition to both of these questions:

While I get the idea that you can just have multiple independant "layers" of your grid for each unit type. I'm curios as to how this works out in an action game where a player controls a character that can jump (or even crouch). So let's say I want to have the following kind of things:

* Bridges or other places that a player can walk over or under.
* Slopes that allow a player to move up or down without jumping
* Crates, walls or even little differences in hight that a player should be able to jump onto or down.
* Tall walles or cliffs that a player should not be able to jump down or up but walk on top of them if he finds another way to get up/down.
* Pseudo-free-movement. A player can walk freely on the tiles while movement is still limited by the tile grid.

So slopes and crates are identical in a way that they allow a player to traverse from one layer to another one.

I'm not sure if this can even be achieved with a simple 2D approach, so maybe I'm better off with a full 3D engine? I liked the idea of a simple 2D engine but I don't want to make it more complicated if a a 3D engine is the right call here.

I'm also having a hard time finding any descriptions or papers that deal with these things.

# Answer
> 4 votes
Add a logical third dimension and add logic to tiles by type. So a horizontal bridge will allow you to pass from left to right on Z = 1 and from top to bottom on Z = 0.(like flow bridges game) Now change the Z when walking up or down a hill. Allow jumping 1 unit high.

That's about it.

edit: here is an example tutorial-

http://rpgmaker.net/tutorials/163/

# Answer
> 3 votes
Going 3D when the game is basically a 2D game seems like an overkill.
In your place, i'd rather use a 2D engine that handles already tiles and slopes, and just use a few tricks for the parts where a '3D' effect is required.

Just a small example, a bridge :

So for the player, that would look like :

Now you can add some invisible trigger zones that will make this part of your map behave like a bridge you can go under.

imagine the yellow trigger means : change the character state so that it is drawn before the bridge and collides with red zones.
And the green trigger means : switch back to normal state where the character is drawn after the bridge and collides with yellow zones.

with such a scheme you'll have a bridge :

I made up this example quickly : i don't claim that the above scheme work fine in all situations, and if the 'z' is a key aspect of the game you'll have to dig further, but i just want to emphasize that for localized effects some small tricks can allow you to have 100% of your features with far less work than a complete re-design.

In other words : Having a physically accurate model of your world is just *one way* to get your game to behave as you want. If some tricks can get you faster to the point with simpler code, just remind yourself that gamers do not see your code, just how it behaves.

---
Tags: 2d, 3d, tiles, movement
---