title: Perfect FPS camera angle

text:
# Question
Title: Perfect FPS camera angle
I am making a multiplayer FPS and I am in search of some helpful tips on the perfect FPS camera angle. Because it is a multiplayer, I am making a full body model holding the gun, I find, however, that some of the gun positions (when held naturally) seem awkward when placing the camera on the position of the characters eyes. Moving the camera has other consequences, for example, when moving the camera to a more appropriate fps position, when looking at your feet, it seems that your head is too far right, as your point of view is past your left foot..

Any expert advice?

# Answer
> 9 votes
The industry standard for first-person view simulation in most shooters is to have character models and animations distinct from those used for third-person view. There are several reasons for this:

* The player has a much smaller field of view upon the world than a real person in the character's situation would, and he lacks other forms of input such as feeling sensations.

Since the game must obey the usability principle of giving feedback for all of the player's actions, a lot of actions and objects must be displayed as if in front of the player character's eyes. E.g. when hip-firing for real, you don't see the gun at all or barely but you can feel it, whereas in an FPS you see it in plain view. When reloading a gun for real, you must look down at your pocket to retrieve the mag (or not if you can just run your hand down your vest or something) and then look down at the gun where you place the mag, whereas in an FPS, this is done in front of the player character's eyes.
* The third-person model is not detailed enough to be displayed from up close. If it were used for first-person view, the low resolution of the texture and the poor geometry would hurt the player's eyes... Using an LOD is not the solution because you have to redo the models anyway due to the previous bullet point.

**edit**: I forgot to add this interesting link.

Finally, again due to the field of view being narrower in games than in real life, the game must somehow display objects that are below the character's head as higher than they really are for the player to get a better understanding of their relative position. Indeed, when you look straight in reality, there's a whole range that is outside of the standard 75-90 degrees FOV in games, where you can waive your arms with your eyes able to see them, whereas in a game you can't. In a game, what happens in front of you must be displayed.

This is done by lowering the camera a bit with respect to its realistic position about the eyes.

There is no universal rule for how much lower than the eyes the camera has to be, but I guess you can try somewhere between the shoulders and the nose (that's a rough estimate), see what's best for you and that should do it.

If you can play Counter-Strike or COD in multiplayer with a friend, try to see what happens when you make your characters face each other and toy with the cameras. I might try that myself and post a screenshot.

**edit 2**: in games where there's a button to level your eyesight ("center view" button), if you approach a standing NPC, apparently in most cases you'll be looking at the base of their neck. See these planetside 2 screenshots.

**edit 3**: also, shoulder-high is where the weapon actually is on the character model, so if the camera is there too then bullets always travel along a straight line from your "eye" to what your crosshair is on, which is pretty convenient and, in some of the most hardcore FPSes, downright essential to gameplay.

# Answer
> 1 votes
It is common to render the players own character vastly different from other characters in order to avoid these issues.

With a real rifle you have got two mechanics that don't translate well to computer games:

When not aiming you'll typically raise your head higher to get a better view, some games implement multiple different tiers of aiming to simulate this, but from a gameplay point of view it seems quite unnecessary. If you want to keep it simple you'll have to cheat a little in order to provide a view that offers both aiming and view.

Humans have two eyes, even when keeping one right at the sight you can still open the other to get a more normal view on the situation, this obviously doesn't translate to a game that use a single flat image.

### Standard solution

For the first person model put the gun at a somewhat lower point than the view. Leave out either the entire player model, everything but the arms, or if you can somehow manage to make it work without the player being able to look down an empty neck, just leave out the head.

# Answer
> 0 votes
I for one, would suggest that you make all of the animations realistic, as if designing a 3rd-person shooter, and have the camera "mounted" between the character's eyes. tThis is because I feel that it is finally time for players to get a **true** first-person experience, rather that a thirty-six foot long model of a gun designed to vaguely resemble a rifle from a specific view.

Anyway, I would also be curious as to what it would look like as a **real** soldier, on a **real** battlefield holding a **real** gun in a **real** way, in a video game.

It would also add a "unique vibe" to your game, making it look unique, and not like every other FPS (with that classic "disembodied floating arms holding a gun in an obviously ineffective position" sort of feel that Project: Snowbound, Halo, Ghost Recon, Call of Duty, Battlefield, Battlefront, and all other FPS games have.

If you do not clearly understand what I'm saying, I can clarify for you. Just ask.

---
Tags: camera, first-person-shooter, angles
---


# Question
Title: How to find objects in front of my player
I am trying to find an object that is in front of my player sprite using the following code

```
RaycastHit2D hit = Physics2D.Raycast(transform.position,Vector2.right,EnemyLayer);
//EnemyLayer is the layer having enemy
if(hit!=null){
print (hit.collider.tag);

}

```

But this is printing "player",the tag of the object on which the script is attached.What am i doing wrong?
EDIT: Ok,I found out why it was printing player-because I had a big circular collider surrounding my player. Deactivating it gives me the following error

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

```

I have no clue what it means. Any help is appreciated.

# Answer
With only the given information I would assume one of a few scenarios is happening here:

1. Something very mysterious because you provided very little information
2. Your player is on the enemy layer and subsequently the ray immediately hits the player
3. You are not setting up your EnemyLayer variable correctly.

To filter a Raycast based on layer you need to set up a layer mask. A layer mask is the result of bitshifting (\>\>) the layer numbers and combine multiple layer masks into a final layer mask using the binary OR operator (|).

```
int layer1 = 3;
int layer2 = 5;
int layermask1 = 1 << layer1;
int layermask2 = 1 << layer2;
int finalmask = layermask1 | layermask2; //variable to use as the Raycast() layermask parameter

```

Given your specific code, we are only working with one layer it looks like so your code might look something like this assuming you've set up the enemy layer on the first available custom layer which would be layer 8.

```
int enemyLayer = 8;
int enemyMask = 1 << enemyLayer;
//int layerMask = enemyMask; //No need for setting up a final mask because we only have one layer to check

RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, enemyMask);

```

**To comment on your edit:**

The above should help you resolve the issue with not needing to disable your player collider. The null reference exception is likely due to the fact that you aren't colliding anything. You need to actually check if `hit.collider` is null as hit will return information even if it doesn't hit.
> 1 votes

# Answer
First of all your code is not correct:

```
if(hit!=null){
    print (hit.collider.tag);
}

```

Raycast will **ALWAYS** return not null object. And you **ALWAYS** need to check hit.collider for null. It can be found easy in manual:

http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
> 1 votes

---
Tags: unity, collision-detection, platformer, raycasting
---


# Question
Title: Modifying depth values in PixelShader (SharpDX)
I'm relatively new to DirectX, and am currently converting some WPF 2D graphics code that displays geo-located sonar returns. I am using SharpDX, and rendering via a D3DImage.

I've got the basics working nicely, with very good performance, rendering segments of sonar as a set of quads textured via a texture array of chunks of sonar data.

I am now trying to modify the pixel shader so that it shows the highest "quality" signal return in the case where I have an overlap. Consider that the sonar return spreads from a central point, and (generally) gets worse the further away it is. When we have an overlap, a starting point to showing only the best data is to simply show the pixels that are nearest to the centre of the track, and a simple way I thought to do this would be to modify the depth values in the pixel shader so that the depth varies with the signal distance.

I have added a PS\_OUT struct as so:

```
struct PS_OUT
{
    float4 Colour   : SV_Color;
    float Depth     : SV_Depth;
};

```

and a simplified version of the PixelShader:

```
    float quality = 1 - input.domain_uv.x;
    result.Colour = float4(quality, quality, quality, 1);
    result.Depth = quality;
    return result;

```

where the quality value varies from 0-1, and in this example I am also colouring the output with this quality value:

..which gives the expected colour output, but not the depth output. What I expect (want!) is that the higher quality (lighter coloured) output is preferred over the dark on a per-pixel basis.

I can confirm that depth testing is enabled, as I can vary the z coordinates of my quads and see the results. What seems to be my sticking point is that the depth value I calculate in the pixel shader is simply ignored, and my best guess is that I am missing something obvious - like I need to tell Directx to use it, and not its own calculated values. I can't find any documentation that suggests anything other than modifying the shader semantics is required.

The depth buffer/stencil is set up like this - this is taken from a WPF/SharpDX integration package:

```
 Set(ref m_depthStencil, DXUtils.CreateTexture2D(this.m_device, w, h,    BindFlags.DepthStencil, Format.D24_UNorm_S8_UInt));
  //Set(ref m_depthStencil, DXUtils.CreateTexture2D(this.m_device, w, h, BindFlags.DepthStencil, Format.D32_Float));
 Set(ref m_depthStencilView, new DepthStencilView(this.m_device, m_depthStencil));

 m_device.ImmediateContext.Rasterizer.SetViewports(new ViewportF[] { new ViewportF(0, 0, w, h, 0.0f, 1.0f) }, 1);
 m_device.ImmediateContext.OutputMerger.SetTargets(m_depthStencilView, m_renderTargetView);

```

I did try varying the texture format (see commented line), to no avail.

Subsequent to this, I also want to blend the very edges of the joins - but I'll leave that question for another day.

thanks, Matt

edit: I can simulate the final effect that I am after by adjusting the depths of my quad vertices such that the middle is lower than the outer. Depths are then "real" depths, and the correct pixels are drawn. I don't think, however, that this is going to work as a solution for me because I want to be able to implement a slightly more complicated "quality" metric in the pixel shader. SO the question remains: why are my depth values calculated in the PS being ignored?

Here's an image of overlapping tracks where the "closest" pixel is rendered at all times:

# Answer
There is a chance that your depth value calculation is wrong. The way the GPU's are calculating the depth values is not that simple. For example if we take a point right in the middle between the near and far planes of the camera, the depth value is not 0.5 .

You can refer to this post by Steve Baker to see how you can calculate the depth value: http://www.sjbaker.org/steve/omniv/love\_your\_z\_buffer.html
> 1 votes

---
Tags: directx, sharpdx, depth-buffer
---


# Question
Title: Rotate Character towards Moving direction
So my Problem is that my Character is always shooting in the way it is looking. Unfortunaly my solution seems to be a very bad one. I am not really cabable of aiming with my solution. Neither with Controller or Touchscreen Control. I already commented many Things out as you can see but nothing works correctly for me. It is a 2D Top-Down Game.

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {
    public int dead = 0;
    //Moving
    public float maxSpeed = 3f;
    public float rotSpeed = 100f;
    public Transform target;
    float zo;
    float opZ;
    //Shooting
    public Vector3 bulletOffset = new Vector3(0, 0.5f, 0);
    public GameObject bulletPrefab;
    int bulletLayer;
    public float fireDelay = 0.25f;
    float cooldownTimer = 0;
    GameObject pau;

    void Start () {
        bulletLayer = gameObject.layer;
        pau = GameObject.FindGameObjectWithTag("MainCamera");

    }

    // Update is called once per frame
    void Update () {
        //Debug.Log("GameP ->" + pau.GetComponent<PauseGame>().isPause);
        if(!pau.GetComponent<PauseGameGameover>().isPause){
        if(dead == 0)
        {
            //Moving
            movePlayer();
            //Shooting
                cooldownTimer -= Time.deltaTime;
            if( CFInput.GetButton("Fire1") && cooldownTimer <= 0 ) {
                shotPlayer();
            }
        }
        }
    }
    void shotPlayer()
    {
            // SHOOT!
            cooldownTimer = fireDelay;

            Vector3 offset = transform.rotation * bulletOffset;

            GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, transform.position + offset, transform.rotation);
            bulletGO.layer = bulletLayer;
    }

    void movePlayer()
    {
        float x = CFInput.GetAxis("Horizontal");
        float y = CFInput.GetAxis("Vertical");
        ////////////////
        /// Rotate the PLAYER
        /// /////////////////////////////
        zo= x*90;
        //Debug.Log("ZO -> " + zo);
        if(y > 0 && x > 0){opZ = 360-zo;} //Oben bis Rechts
        if(y < 0 && x > 0){opZ = 180+zo;} // Rechts bis unten
        if(y < 0 && x < 0){opZ = 180+zo;} //Unten bis Links
        if(y > 0 && x < 0){opZ = -1*zo;} // Links bis oben
        /* Hardcoded Left Right Up Down */
        /*if(y == 0 && x > 0){opZ = 270;}
        if(y == 0 && x < 0){opZ = 90;}
        if(y < 0 && x == 0){opZ = 180;}
        if(y > 0 && x == 0){opZ = 360;}
        if(y == 0.5 && x == 0.5){opZ = 315;}
        if(y == -0.5 && x == 0.5){opZ = 225;}
        if(y == -0.5 && x == -0.5){opZ = 135;}
        if(y == 0.5 && x == -0.5){opZ = 45;}
        //Debug.Log("OPZ: ->" + opZ);
        */
        // Grab our rotation quaternion
        Quaternion rot = transform.rotation;
        // Grab the Z euler angle
        //float z = rot.eulerAngles.z;
        // Recreate the quaternion
        Quaternion rotNew = Quaternion.Euler( 0, 0, opZ );

        transform.rotation = Quaternion.Lerp(rot, rotNew, Time.time * rotSpeed);

        ///////////////////
        // MOVE the PLAYER
        ////////////////////////
        ///

        Vector3 pos = transform.position;

        Vector3 velocity = new Vector3(CFInput.GetAxis("Horizontal") * maxSpeed * Time.deltaTime, CFInput.GetAxis("Vertical") * maxSpeed * Time.deltaTime, 0);

        pos += velocity;

        // Finally, update our position!!
        transform.position = pos;
    }
}

```

# Answer
> 1 votes
It sounds like you wish to control the players movement with keys, and aim the weapon with the mouse (hard to tell as you don't provide enough info.). If that is the case then drive the players movement with something simple like :

```
 //Players Update...
 float speed = 1.0f;

 void Update() {
     var move = Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
     transform.position += move * speed * Time.deltaTime;
 }

```

And then you could use some mouse rotation control eg:

```
//Weapon Update...
void Update() {
    RotateToMouse();
}

void RotateToMouse() {
    Vector3 pos = Input.mousePosition;
    pos.z = Mathf.Abs(Camera.main.transform.position.y - transform.position.y);
    pos = Camera.main.ScreenToWorldPoint(pos);
    transform.LookAt(pos);
}

```

# Answer
> 0 votes
Use tan-1 ( y/x ) to find the angle to face, using x,y relative from the shooter, then use the Rotation Matrix to find other values you might need.

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


# Question
Title: unity animation won't play unless input key is held
The code is simple. If the player presses the right arrow key, one animation clip plays. If the left arrow key, another clip plays, etc. However, the clip doesnt play fully unless the input key is held continuously. The second you release it, the second the clip stops playing. I think it's something to do with update() and the input not being remembered over next frame.

The code is simple:

```
using UnityEngine;
using System.Collections;

public class animatorcontroller_Logic : MonoBehaviour
{

    Animator anim;

    enum MovementState
    {
        Idle = 0,
        run = 1,
        walk = 2,
    }

    MovementState currentMovementState;

    void Start ()
    {
        anim = gameObject.GetComponent<Animator> ();
    }

    void Update ()
    {

        if(Input.GetButton("right"))
        {
            currentMovementState = MovementState.run;

        }

        else if(Input.GetButton("left"))
        {
            currentMovementState = MovementState.walk;

        }

        else
        {
            currentMovementState = MovementState.Idle;    //set movement state to idle
        }

        anim.SetInteger("MovementState", (int)currentMovementState);

    }

}

```

# Answer
> 1 votes
On the `Update()` call immediately following releasing the key, your `else` clause sets `currentMovementState = MovementState.Idle`. This stops the walk animation, I presume.

# Answer
> 0 votes
I figured it out. I just need to set the transition condition to Exit Time = 0.95 in the state machine instead. This ensures the animation plays fully before going back to idle.

---
Tags: unity, animation
---


# Question
Title: How do I convert two vectors into a bounding box with 8 vertices?
I created two vectors named bboxmin and bboxmax using the functions vector3 `applymin_xyz()` and vector3 `applymax_xyz()`.

How do I convert them to 8 vertices,so I can test cull with them?

# Answer
> 6 votes
For an axis-aligned bounding box represented by a minimum and maximum corner, you can extract six pieces of information, `xMin`, `yMin`, `zMin`, `xMax`, `yMax`, `zMax`.

Given those, you can construct your eight vertices as all combinations of the min and max values for each component:

```
{ xMin, yMin, zMin },
{ xMin, yMin, zMax },
{ xMin, yMax, zMin },
{ xMin, yMax, zMax },
{ xMax, yMin, zMin },
{ xMax, yMin, zMax },
{ xMax, yMax, zMin },
{ xMax, yMax, zMax },

```

Of course, normally you would not do this conversion to a polyhedron, but instead work with separating axes or possibly the plane equations. You may want to consult Christer Ericson's Real-Time Collision Detection book and the table of intersection methods from Real-Time Rendering.

---
Tags: vector
---


# Question
Title: How can I get the "SelfActor" in OnBeginActorOverlap?
The signature it takes is

```
void ( AActor* OtherActor )

```

However, The actor that is handling this event is not involved in the overlap. How can I access the actor that owns this delegate? Assuming I can't store a reference to this elsewhere. Is there another delegate that takes that parameter? Is this reference stored in OtherActor somewhere?

# Answer
> 2 votes
Irritatingly, I don't believe there isn't a simple way (which is why most events in other frameworks have a `sender` parameter...). Instead, one way I've worked around is:

Bind to the collision event inside the actor that has the `UPrimitiveComponent` you want to listen to.

Create an event in that actor that others can subscribe to. But this event has the signature `void (AActor* OtherActor, AActor* Sender)`.

When the first event is triggered, simply fire the other event, filling in `this` as the second parameter.

This also works in BP using event dispatchers.

# Answer
> 0 votes
The actor that is firing the event is the current instance:

(this-\> ) Will get you the actor that is firing the event.

(OtherActor-\> ) Will get you the actor that it collided with.

---
Tags: c++, collision-detection, unreal-4
---


# Question
Title: Share a function between two passes inside CG Shader for unity3d
I'm writing a shader in CG language for Unity3d. When making transparent object you need to create two similar passes in SubShader. First to render only back faces (with `Cull Front`) and second to render only front faces (with `Cull Back`). But the code for vertex and fragment function is the same.

Is it possible not to double a code and declare some functions, that would be shared between passes?
I want to have something like in my code example.

```
Shader "cool shader" {
Properties {
    ...
}
SubShader {

    CGPROGRAM
    // need to declare vertexOutput somewhow here
    float4 sharedFragFoo(vertexOutput i) : COLOR  // How to make smth like this?
    {
        ....
        return float4(...);
    }
    ENDCG

    pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        vertexOutput vert(vertexInput v) {
            vertexOutput o;
            ...
            return o;
        }

        float4 frag(vertexOutput i) : COLOR
        {
            return sharedFragFoo(i); // call the shared between passes function
        }

        ENDCG
    }

    pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        vertexOutput vert(vertexInput v) {
            vertexOutput o;
            ...
            return o;
        }

        float4 frag(vertexOutput i) : COLOR
        {
            return sharedFragFoo(i); // call the shared between passes function
        }

        ENDCG
    }
}
}

```

# Answer
We can define all that lies between `CGPROGRAM` and `ENDCG` in separate **\*.cginc** file and include it inside each pass.

For details look https://stackoverflow.com/a/30530184/1351629 .

Sorry for the cross-post. I have found out how to do it using includes and posted the answer on SO.
> 1 votes

---
Tags: unity, shaders, cg, architecture
---


# Question
Title: Game lags when my player collides with a specific object (solution known, unsure how to implement)
I'm developing a game in Android using LibGDX (although this is more of a JAVA problem than an engine problem). My aim is to have my player bounce off one spring onto another that will eventually take him over an obstacle like so:

I have a feeling the lag is because im creating new objects in a method that gets called in `update()`. This is because I had the same issue with coins in the game until I stopped initialising the `Coin`object in a method that gets called by `update()` \- now they work smoothly.

However, I'm not sure how to implement the spring collision without initialising `Spring` objects. Currently, objects are initialised through a text file - however, `Spring` is only initialised in a Box object rather than the text file. In my `update()` method I loop through the objects and if an object is a `Box` which contains a `Spring`, the following method is called:

```
public void playerSpringCollision(Box containsSpring) {
        // first spring (on the box)
        Spring boxSpring = containsSpring.getSpring();
        // second spring (on the platform)
        Spring platformSpring = containsSpring.getPartnerPlatform().getSpring();
        // distance in x between first & second spring
        float dx = platformSpring.getxPos()
                + platformSpring.getSprite().getWidth() - boxSpring.getxPos()
                - player.getSprite().getWidth();
        // distance in y between first & second spring
        float dy = platformSpring.getyPos() - boxSpring.getyPos();
        directionToSpring.x = dx;
        directionToSpring.y = dy;
        // if player collides with first spring
        if (player.getRectangle().overlaps(boxSpring.getRectangle())) {
            player.springImpulse(directionToSpring); // send player to platform spring
        }
        // if player collides with second spring
        if (player.getRectangle().overlaps(platformSpring.getRectangle())) {
            directionToObstacle.x = -directionToSpring.x;
            directionToObstacle.y = directionToSpring.y;
            player.springImpulse(directionToObstacle); // send player over obstacle
        }
}

```

I'm not sure how to do this without initialising `Spring` and `Vector2` objects in the method - any ideas? Highly grateful for any help, thanks.

# Answer
> 1 votes
For the instanciation inside update method problem i suggest you to use the Pool class for every object in your game that must be instantiated a lot of times. You can follow this guide in particular (in the guide the object is a bullet). The guide also contains suggestions for other memory and lag problems.

As for the way you calculate and execute the jump, i suggest to place the `Spring` objects on the game level when it is created and not while updating. You can also pre-calculate the direction the Spring will give to the player based on the Spring position.

Then, in the `update` method you only check if player collides with a spring (you will have to use a "for" loop for checking all Spring objects available) and change direction based on the jump direction stored in a variable inside the Spring.

# Answer
> 0 votes
I don't see any n`ew Spring` calls in the code you posted, if the springs are being instanciated in the `getSpring` method then you need to ask yourself if you always have to return a new instance.

With `Vector2` for example, it comes with a `set` method, so you can have a temporary (or many) instance in your class that you work with when doing vector math, so you don't do;

```
private void foo() {
  Vector2 result = new Vector2(vectorA);
  result.add(vectorB);
}

```

You do;

```
private final Vector2 result = new Vector2();

private void foo() {
  result.set(vectorA);
  result.add(vectorB);
}

```

That will take the cost of allocating and instanciating the `result` only once, and not every time the foo method is called (obviously, if you're doing any parallel stuff, you need to make sure you access the temporaries in a safe way).

Find the places where you create new instances of objects, be it `Vector2` or `Spring`, and think about whether or not you can re-use an existing instance.

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


title: Color submeshes in unity3d

text:
# Question
Title: Color submeshes in unity3d
I have a `main_mesh` that has 10 submeshes, I wonder how I can change the color of of these submeshes to a different color (e.g submesh1 will have a red color, submesh2 will have a blue color,...etc). Any advise please?

UPDATE:

This is how I'm getting my mesh which has 10 submeshes:

```
        SkinnedMeshRenderer smr  = gameobject1.GetComponent<SkinnedMeshRenderer>();
        Mesh main_mesh = smr.sharedMesh;

```

# Answer
> 1 votes
Usually , you have a different material for each submesh. If this is the case change the properties of each material to achieve what you want

Example: I tried this

```
Renderer r =  GetComponent<Renderer>();
    r.materials[0].SetColor ("_Color",new Color(123f/255f, 0f/255f, 123f/255f));

```

Where r,g,b are your color components.

Some references : Ref1 , Ref2

# Answer
> 1 votes
If you have `N` submeshes, the renderer for those meshes will need to have `N` materials.

Many tutorials focus on renderers with only one material, which you access through its `material` property. If you have multiple materials, you can instead access the `materials` array. Each material `n` corresponds to submesh `n`.

If you want, you can apply different materials to each submesh by editing your assets in the inspector. Each material could have different textures, different instance parameters, or so on.

Or, you could apply one material to all of them, and then edit that material in a script. Bear in mind that Unity uses a copy-on-access pattern, so it will internally create `N` new material instances the first time you access the `materials` array.

As an example, the following would apply a random color to each submesh:

```
void Start() {
    Material[] materials = renderer.materials;
    for (int i=0; i<materials.Length; i++) {
        float r = Random.value;
        float g = Random.value;
        float b = Random.value;
        materials[i].color = new Color(r, g, b, 1f);
    }
}

```

---
Tags: unity, unityscript
---


title: Skeletal Animation Mirrored

text:
# Question
Title: Skeletal Animation Mirrored
Okay so I've been working on GPU skinning skeletal animations.

I need help assessing what is going on here. Looks like the animations are completely mirrored

What are the possible issues? I've been looking at it for so long I'm numb to it. Maybe some fresh eyes will be able to pinpoint what it could be?

Thanks in advanced.

This is in Blender(how is should look):

This is what it looks like in my engine:

# Answer
Solved: I had to negate the w component of the rotation quaternion on both the bind pose bones and the animation frame bones.
> 2 votes

---
Tags: skeletal-animation, gpu, skinning
---


# Question
Title: Angled topdown perspective camera for 2.5d game
I have a 2d tile based game created using Unity's 2d tools and orthographic camera:

The tiles are created by programmatically generating a mesh, assigning a texture to each pair of triangles, and setting the normals to -Vector3.forward.

I'd now like to switch to a perspective camera, to add a 3d feel to the tiles, while still using sprites (and following the player):

How do I go about setting up this kind of camera, and will it still be possible to retain the player's x/y co-ordinates which are heavily used in my game logic.

Thanks in advance!

Update: I've realised that in terms of my original grid and sprites, I simply need to swap their vectors Y and Z co-ordinates so that the tiles and sprites are nicely positioned in the scene, however I'm still unsure about how to nicely position the camera and center it on the player.

# Answer
> 1 votes
All you need to do is represent your sprites as 3D billboards, and backgrounds as 3D geometry (such as planes). The X/Y coordinates will be exactly the same as they were before. The camera will be offset from the player along the Z coordinate, and a little bit in the Y coordinate.

In unity, this can be accomplished by changing your camera type to a perspective camera, then having a script which follows the player and uses the `lookAt` function of the camera to orient it. The sprite renderer will work correctly, since in Unity, sprites are always just 3D billboards anyway. Your backgrounds will have to be converted into textured planes and other 3D geometry for them to be displayed appropriately though.

# Answer
> 0 votes
There are a couple things you will need to do here I believe:

1 Sorting the objects based on rendering order because they have a "Z component" 2 Translating the world coordinates into screen coordinates/scale by account for camera position 2 Touch up art assets that have a "depth" or "thickness" when portrayed in 3d space.

---
Tags: c#, unity, camera, 2.5d
---


# Question
Title: How to implement a professional fighting game input buffer?
Ok guys, I understand how to make a basic input buffer.

Here is my code:

```
public class InputBuffer : MonoBehaviour {

    public int max_buffer;
    public enum keys { down, up, left, right, X, Y, Z, A, B, C }
    public List<keys> InputPlayer;
    public enum Special { WPunch, MPunch, SPunch, WKick, MKick, SKick, Hadouken, Shoryuken }
    public List<Special> SpecialsPlayer;

    void Start () {
        InputPlayer = new List<keys>();
        SpecialsPlayer = new List<Special>();
    }

    void AddKey(keys key)
    {
        InputPlayer.Add(key);

        if (InputPlayer.Count > max_buffer)
        {
            InputPlayer.RemoveAt(0);
        }
    }

    void CheckSpecial()
    {
        if (InputPlayer[InputPlayer.Count-1] == keys.A)
        {
            if (InputPlayer[InputPlayer.Count-2] == keys.right)
            {
                if (InputPlayer[InputPlayer.Count-3] == keys.down)
                {
                    SpecialsPlayer.Add(Special.Hadouken);
                }
            }
        }
    }
}

```

This works really well, but then I get repeated keys in the buffer when I keep a key pressed.

I could fix it by having a last keypressed variable and then only calling the inputbuffer.getkey if the key pressed is diferent. But this makes the buffer to behave rather stiff.

I would love to see how can I improve my code so It doesn't recognizes multiples keys when a button is kept pressed, but also allow for charge moves (Guile's sonic boom).

I also would love to see how input shortcuts works (using a previous special command as part of a second one, usually used in cancels to supers).

I would love to see what's the proper way to handle input buffers in kof and SF.

# Answer
> -1 votes
Store the flag for each key and set it true on keydown. Don't add this key to buffer while corresponding flag true. Set flag to false when keyup happens.

---
Tags: c#, input, fighting-game
---


# Question
Title: How to prevent the player from calling the Jump function if no collision is detected?
I am back once again. This time with a basic 2D platformer game. I would like to allow my player to jump but only if the ground bool checks as true. I would like to fix my script so that upon collision with the ground the player is able to jump, but while the player is in the air the player is not able to jump. My platform has a box collider and my player has a collider as well as a rigidbody. How do I go about fixing my script to allow this system to go into effect? Please and Thank you!

```
public class MovePlayer : MonoBehaviour {

    public float speed = 0f;
    public float height = 0f;
    public GameObject player;

    private bool grounded = false;

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "ground")
            grounded = true;
            return;
    }
    // Use this for initialization
    void Movement ()
    {
        if (Input.GetKey (KeyCode.RightArrow))
        {
            transform.Translate(Vector3.right * speed * Time.deltaTime);
        }

        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.Translate (Vector3.left * speed * Time.deltaTime);
        }

        while (grounded = true)
        {
             Jump();
        }
    }

    void Jump()
    {
        if (Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKey (KeyCode.Space)) {
            transform.Translate (Vector3.up * height * Time.deltaTime);
            return;
        }
    }

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

        Movement ();
    }
}

```

# Answer
> 2 votes
You have an error:

```
while (grounded = true)
{
  Jump();
}

```

So each time Movement() is called - each frame - grounded will be true. Use "grounded == true" as condition check. But don't forget to set grounded var back to false or you'll see infinite loop.

I suggest you to change workflow and use State design pattern or something like that to not mess with different bools and flags.

# Answer
> 0 votes
I think what you want is void OnCollisionStay(); It is a built in (intrinsic) function used by Unity. When the unit enters or stays in any collision you check to make sure the collidable object is tagged as a floor then if the player is hitting the "Jump" button, jump. Its not elegant but it works just fin in my experience.http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionStay.html This is the 3D version. There is a 2D version as well if you wanted that.

---
Tags: c#, unity, collision-detection
---


# Question
Title: Is there such thing as a hybrid View that combines SurfaceView and GridView in Android?
I am trying to develop several Android games that work on a grid system. I will need to update the game surface frequently, so using a `GridLayout` does not seem to be a good option. The frequent updates to the game surface would be similar to what you see in Plants vs Zombies: the user can interact with parts of the grid, but the sprites representing the computer opponent will always be moving until the level ends.

I want to sublcass `SurfaceView` but give it many of the built-in properties of a `GridLayout` (ex. I want to allow the user to drop a game object in a grid cell and have that object start animating within the bounds of the grid cell, so I would want row and column indexes built in to my custom `SurfaceView`) but that's a lot of work.

Do you now if something like this already exists?

Is it better to just use a "normal" `SurfaceView` and somehow keep track of where on the `SurfaceView` the grid lines should fall, maybe using a HashMap or something to track the vertices of all the grid cells? That seems like a lot of work and I don't want to reinvent the wheel if I don't have to.

I'm looking for design device or recommendations on free libraries (\*.jar) that I could use to accomplish this goal efficiently. I'm coding in plain old Android Studio so no Unity access :(

# Answer
1. Don't subclass SurfaceView. Use composition, not inheritance. There's no value in subclassing it, and many basic mistakes (like overriding `onDraw()` when your goal is to draw on the Surface) are impossible if you don't.
2. The View-based UI is rendered on a separate layer from the SurfaceView's surface. (The SurfaceView has a View as well, but generally that's just a transparent hole that the layout code uses to position things.) Mixing View elements with stuff drawn directly on a surface is viable but trouble-prone given the wide variety of device characteristics, so mixing GridLayout and SurfaceView isn't a good idea.
3. What you have described so far doesn't sound that complicated to do, unless you try to reinvent GridLayout and all of the invalidate/measure/layout fun -- a simple regularly-spaced grid subdividing the surface should be easy. You can even set the surface size to a fixed value with `setFixedSize()`, though you still need to worry about the display aspect ratio. (demo)
> 1 votes

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


# Question
Title: How do I use graphics APIs to select the proper display device among multiple attached to a PC?
I have an LCD monitor display and Oculus Rift attached to my PC. I have an Nvidia 820M dedicated GPU. How does the GPU know to which display device it has to render (or to send rendered information)? Are there any OpenGL/DirectX calls to bind display with the GPU?

# Answer
> 7 votes
The GPU doesn't, the programmer does.

The initialization of the graphics API will typically involve optional specification of which display device to use; not explicitly specifying this generally results in the default of whatever the OS thinks the "primary monitor" is.

OpenGL and D3D handle this decision differently. D3D has the concept of "adapters" modeled in to its API, and you can query the available number and figure out the the properties of each and then automatically decide or present a choice to the user.

OpenGL doesn't actually concern itself with formally specifying the creation of its context object for every OS; the OS itself handles that. You generally need to use the OS-level display-enumeration features (`EnumDisplayDevices` or `NSScreen` on OS X) to find the set of available displays and give them to the appropriate OS-level functions used to create the OpenGL context.

Usually this only matters if you're trying to use exclusive full-screen on a specific monitor, or render to a device that the system doesn't necessarily normally consider a "screen" (in that case getting the appropriate handle may involve the use of APIs specific to that hardware; this may be the case with the Rift, I'm not sure).

Generally if you're just doing windowed rendering, you don't need to worry about which monitor you are on.

# Answer
> 2 votes
If you're running on a Windows platform with the latest version of the Oculus SDK (0.6) and you're trying to figure out how to create a window and a rendering context to target the Rift, then this question is kind of meaningless. As of 0.6 the SDK now completely handles creation of the onscreen window to target the Rift display, regardless of whether the Rift is running in extended or direct mode.

Your responsibility as a developer is just to create a new D3D or OpenGL rendering context for creating the content that will be sent to the SDK. You can either create an onscreen window or an offscreen surface for this, and it doesn't really matter where you put the window, so it's simplest just to let the underlying system use a default location. The only caveat is that if you're running in extended mode, you *don't* want the window you create to end up on the Rift display, but since there's no way (in 0.6) to determine whether you're running in extended mode or which display belongs to the Rift, that's not possible, so just target the primary monitor on the assumption that it's probably not the Rift display.

---
Tags: opengl, directx, graphics, graphics-programming, oculus
---


# Question
Title: Ping Pong bat is not detecting the collision with the wall
I have been learning Unity for last couple of days. I want to make one simple ping pong game. The idea is simple. The game has a Sphere as a ball, a plane as ground, 2 rectangles as bats and 4 rectangles as walls. Look at the image

It is a 2 players game. One player will use 'W' and 'S' key and another player will use 'Up Arrow' and 'Down Arrow' on the keyboard to move the bat up and down.

But I have a problem here. If a player moves the bat at the limit (up or down), the bat does not detect the collision with the wall. It just goes through the wall. Look at the image.

The bats and the walls have Box Collider, but still the problem persists. So what should I do so that the bat detects the collision with the wall.

# Answer
Use Raycast to collider: http://docs.unity3d.com/ScriptReference/Collider.Raycast.html

Just like in example:

```
  void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (coll.Raycast(ray, out hit, 100.0F))
            transform.position = ray.GetPoint(100.0F);

    }
  }

```

Replace input method and use ray pointed from bat to the wall to detect collision with walls. But in your case I **DEFENITELY** check bat coordinate to not exceed wall bounds (Y or Z coordinate), because it is simple and I suggest do this for you if want to study coding

Good luck!
> 1 votes

# Answer
Oh this... I tried to make a pinball game. There were several methods I tried which included making the hitbox larger, decreasing the time slice for the physics engine (the time in between each physics check was smaller) and a few other things. In the end I had to hand code the physics of the ball to shoot off when it touched the paddles, as long as the paddles weren't at rest. https://www.youtube.com/watch?v=hg3AyHEEGws I will add a link to the project soon. (a reminder wouldnt hurt)

https://www.dropbox.com/s/hraflyt9tj67ikh/ATLATLfinalWithSQL.zip?dl=0
> 0 votes

---
Tags: unity, collision-detection
---


title: Server networking - Thread per player

text:
# Question
Title: Server networking - Thread per player
As my game is purely multiplayer, online performance is important.

Should I run two threads for each player/connection? (One for input and one for output) or should I run one thread for all player input and one thread for all player output?

What is the pros and cons, and how do I deal with high ping players in the second method?

# Answer
As a general guiding principle, avoid "One Thread Per User" designs, especially for networking. Managing thread interactions is a known hard problem, and having an uncertain number of threads drives that complexity.

A thread per major functional category is more manageable, and scales nicer with actual multiple cores. (@Alan Wolfe's comment alludes to this.) A thread for physics, a thread for management console, a thread for networking...

> deal with high ping players

The same way as with fast-ping players: you never (ever!!) block on network access. What you want is known as "asynchronous i/o". It can take various forms, such as event callbacks to your code from the i/o system (like JavaScript), or look like one master polling loop (like \*NIX select() call).

(I confess, I've only done very simple client-side Java networking, not recently, so I'm not fluent in server side asynch for Java. But it looks like java.nio.channels.AsynchronousXxx are the relevant classes.)

Now, behind the scenes, the i/o system may be using threads... but they're trained professionals, that is, it's mission critical and they've worked the bugs out so we don't have to.
> 2 votes

---
Tags: java, networking, server, architecture
---


# Question
Title: Unity3D WWW get HTML displayed in browser
I currently have in a web page, on a localhost server, some information that I want to use in Unity. My problem is that this information are stored in some js variables.

I tried to use the WWW class in a coroutine, but I only get the html source code. Is there a way to get the value of this variables inside Unity Editor ?

Thanks !

# Answer
There is this page on Unity and browser communication: http://docs.unity3d.com/Manual/UnityWebPlayerandbrowsercommunication.html

If you are doing something different you may want to consider wrapping it in a RESTful API. The webpage then returns JSON/XML which you can parse to get your data out.
> 1 votes

---
Tags: unity, javascript, html
---


# Question
Title: Players Health getting recuded only once when attacked
I made a game in Unity 2D

Issue: I have made some spikes and other aliens, which decreases the players health if they come in contact. The health only decreases once instead of getting decreased every time player move or till the time player is in contact with the spike/alien. have tagged player as "player" and alien and other things as "deadly"

public class Explode : MonoBehaviour {

```
public BodyPart bodyPart;
public int totalParts;

private Player player;

// Use this for initialization
void Start () {
    player = GameObject.FindObjectOfType<Player> ();
}

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

}

public void OnTriggerEnter2D(Collider2D target){
    if (target.gameObject.tag == "Deadly") {
        LifeMeter script = player.GetComponent<LifeMeter>();
        script.life();
    }

}

public void OnCollisionEnter2D(Collision2D target){
    if (target.gameObject.tag == "Deadly") {
        LifeMeter script = player.GetComponent<LifeMeter>();
        script.life();
    }

}

public void OnExplode(){
    Destroy (gameObject);

    var t = transform;

    for (int i = 0; i < totalParts; i++) {
        BodyPart clone = Instantiate(bodyPart, t.position, Quaternion.identity) as BodyPart;
        clone.GetComponent<Rigidbody2D>().AddForce(Vector3.right * (Random.Range (-50, 50)));
        clone.GetComponent<Rigidbody2D>().AddForce(Vector3.up * Random.Range(100, 400));
    }

    GameObject go = new GameObject ("ClickToContinue");
    ClickToContinue script = go.AddComponent<ClickToContinue> ();
    script.scene = Application.loadedLevelName;
    go.AddComponent<DisplayRestartText> ();

}

```

}

# Answer
I'm not familiar with Unity, but it seems you should implement

> http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerStay2D.html

and

> http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionStay2D.html

as well. These functions are called each frame instead of only the first frame there is a contact.

In fact, you should probably only implement these as otherwise on the first frame you'd get 2 life reductions instead of only one.
> 0 votes

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


title: Play audio clip from where it left

text:
# Question
Title: Play audio clip from where it left
I spent some time playing with AudioSource.time & AudioSource.timeSamples and read some posts about them. So I get that due to audio compression I can't rely on .time for accuracy so I need to use .timeSamples. Yet, when I printed some output of how .timeSamples work coudn't understand the idea behind it at all. I simply made a 30 sec audio loop and with first play it starts from 7526 and 2nd time 38 and every next time it loops, starts and ends with different timeSample values. Why?

What I simply want to achieve is the thing I wrote in the header and also to be able to play the sound at for example the 5th or 10th or any second without losing the accuracy from the compression for android or ios. How can I do that?

# Answer
Pausing and resuming playback can be achieved with this approach:

```
AudioSource audio = GetComponent<AudioSource>();
float playbackProgress = 0f;

//play
audio.Play();

//pause
playbackProgress = audio.timeSamples;
audio.Stop()

//resume
audio.timeSamples = playbackProgress
audio.Play();

```
> 1 votes

---
Tags: unity
---


# Question
Title: Checking collision from below using OnCollisionEnter
Want to use OnCollisionEnter to see if there is a collision from below.

```
void OnCollisionEnter(Collision other)
     {
         foreach (ContactPoint contact in other.contacts)
         {
             if(contact.point.y<transform.position.y)
             {
                 Debug.Log("Collision from below");
             }
         }
         collision = true;
     }

```

it doesn't work for me

# Answer
1.For that just create Empty game object with collider on it.

2.Attach it to bottom of object.

3.Done
> -1 votes

---
Tags: unity, collision-detection
---


title: glDrawElements and Texture Coordinate

text:
# Question
Title: glDrawElements and Texture Coordinate
I just move on from Immediate Mode and try Vertex Array method using glDrawElements and I got the texture is mess. How to draw the texture correctly?

This is a piece of my render code

```
glBindTexture(GL_TEXTURE_2D, BMap.Mesh[i].TextureID);

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, BMap.Mesh[i].Vertice);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, BMap.Mesh[i].TexCoord);

glDrawElements(GL_TRIANGLES, BMap.Mesh[i].TotalFace * 3, GL_UNSIGNED_INT, BMap.Mesh[i].Face);

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

```

The TexCoord stores U and V value, and this is the result:

And this is the model should be

This is the model (ASCII) https://www.dropbox.com/s/9y466krh6gu1oej/lobby.bmap?dl=0

EDIT: I attach my full code BMap.h

```
class CBMap
{
public:
    struct SMesh
    {
        /*SVertice* Vertice;
        STexCoord* TexCoord;
        SNormal* Normal;*/

        float* Vertice;
        float* TexCoord;
        float* Normal;
        int* Face;
        int* FaceNorm;

        char Texture[32];
        int TextureID;
        int TotalVertice;
        int TotalNormal;
        int TotalFace;
    };

    SMesh* Mesh;
    /*SMesh* Mesh;
    SVertice* TempVertice;
    STexCoord* TempTexCoord;
    SNormal* TempNormal;*/

public:
    CBMap();
    ~CBMap();

    int TotalMesh;

    int Load(char* szFile);
    int GetTotalMesh(char* szFile);
    int GetData(char* szFile);
};

void Render(int MDL);
int LoadTexture(char* m_pFile);

```

BMap.cpp

```
int CBMap::Load(char* szFile)
{
    TotalMesh   = GetTotalMesh(szFile);
    Mesh        = new SMesh[TotalMesh];
    GetData(szFile);

    float* TempVertice;
    float* TempTexCoord;
    float* TempNormal;
    int* TempFace;
    int* TempFaceNorm;

    FILE* pFile = fopen(szFile, "r");

    if (!pFile) return 0;

    char szHeader[32];
    int readMode = 0;
    int iMesh = 0;

    while (!feof(pFile))
    {
        fscanf(pFile, "%s", &szHeader);

        if (!strncmp(szHeader, "BMAP", 4)) continue;
        if (!strncmp(szHeader, "mesh", 4)) continue;
        if (!strncmp(szHeader, "mtl", 3))
        {
            fscanf(pFile, "%s", Mesh[iMesh].Texture);
            Mesh[iMesh].TextureID = LoadTexture(Mesh[iMesh].Texture);
            //printf("Texture %s\n", Mesh[iMesh].Texture);
        }

        if (!strncmp(szHeader, "ve", 2))
        {
            TempVertice = (float*)malloc(sizeof (float) * Mesh[iMesh].TotalVertice * 3);
            readMode = 1;
            continue;
        }

        for (int i = 0; i < Mesh[iMesh].TotalVertice; ++i)
        {
            if (readMode != 1) continue;

            fscanf(pFile, "%f %f %f", &TempVertice[i*3+0], &TempVertice[i*3+1], &TempVertice[i*3+2]);
            memcpy(&Mesh[iMesh].Vertice, &TempVertice, sizeof (TempVertice));

            if (i+1 == Mesh[iMesh].TotalVertice) readMode = 2;
        }

        if (!strncmp(szHeader, "uv", 2))
        {
            TempTexCoord = (float*)malloc(sizeof (float) * Mesh[iMesh].TotalVertice * 2);
            readMode = 3;
            continue;
        }

        for (int i = 0; i < Mesh[iMesh].TotalVertice; ++i)
        {
            if (readMode != 3) continue;

            fscanf(pFile, "%f %f", &TempTexCoord[i*2+0], &TempTexCoord[i*2+1]);
            memcpy(&Mesh[iMesh].TexCoord, &TempTexCoord, sizeof (TempTexCoord));

            if (i+1 == Mesh[iMesh].TotalVertice) readMode = 4;
        }

        if (!strncmp(szHeader, "vn", 2))
        {
            TempNormal = (float*)malloc(sizeof (float) * Mesh[iMesh].TotalNormal * 3);
            readMode = 5;
            continue;
        }

        for (int i = 0; i < Mesh[iMesh].TotalNormal; ++i)
        {
            if (readMode != 5) continue;

            fscanf(pFile, "%f %f %f", &TempNormal[i*3+0], &TempNormal[i*3+1], &TempNormal[i*3+2]);
            memcpy(&Mesh[iMesh].Normal, &TempNormal, sizeof (TempNormal));

            if (i+1 == Mesh[iMesh].TotalNormal) readMode = 6;
        }

        if (!strncmp(szHeader, "f", 1))
        {
            TempFace = (int*)malloc(sizeof (int) * Mesh[iMesh].TotalFace * 3);
            TempFaceNorm = (int*)malloc(sizeof (int) * Mesh[iMesh].TotalFace *3);
            readMode = 7;
            continue;
        }

        for (int i = 0; i < Mesh[iMesh].TotalFace; ++i)
        {
            if (readMode != 7) continue;

            fscanf(pFile, "%d %d %d %d %d %d",  &TempFace[i*3+0], &TempFace[i*3+1], &TempFace[i*3+2],
                                                &TempFaceNorm[i*3+0], &TempFaceNorm[i*3+1], &TempFaceNorm[i*3+2]);
            memcpy(&Mesh[iMesh].Face, &TempFace, sizeof (TempFace));
            memcpy(&Mesh[iMesh].FaceNorm, &TempFaceNorm, sizeof (TempFaceNorm));

            if (i+1 == Mesh[iMesh].TotalFace) readMode = 0;
        }

        if (!strncmp(szHeader, "end", 3)) iMesh ++;
    }

    printf("Model loaded\n");

    fclose(pFile);
    return 1;
}

int CBMap::GetTotalMesh(char* szFile)
{
    FILE* pFile = fopen(szFile, "r");

    if (!pFile) return 0;

    int iData = 0;

    while (!feof(pFile))
    {
        char szHeader[32];
        fscanf(pFile, "%s", &szHeader);

        if (!strncmp(szHeader, "mesh", 4))
        {
            fscanf(pFile, "%d", &iData);
            break;
        }
    }

    return iData;
}

int CBMap::GetData(char* szFile)
{
    FILE* pFile = fopen(szFile, "r");

    if (!pFile) return 0;

    int iVertice, iNormal, iFace;
    int iCount = 0;

    while (!feof(pFile))
    {
        char szHeader[32];
        fscanf(pFile, "%s\n", &szHeader);

        if (!strncmp(szHeader, "ve", 2)) fscanf(pFile, "%d", &iVertice);
        if (!strncmp(szHeader, "vn", 2)) fscanf(pFile, "%d", &iNormal);
        if (!strncmp(szHeader, "f", 2)) fscanf(pFile, "%d", &iFace);

        if (!strncmp(szHeader, "end", 3))
        {
            Mesh[iCount].TotalVertice = iVertice;
            Mesh[iCount].TotalNormal = iNormal;
            Mesh[iCount].TotalFace = iFace;
            iCount ++;
        }
    }

    return 1;
}

void Render(int MDL)
{
    glPushMatrix();

    glTranslatef(0.0f, 0.0f, -5.0f);
    glRotatef(20.0f, 45.0f, 45.0f, 0.0f);
    glColor3f(255.0f, 255.0f, 255.0f);
    glEnable(GL_TEXTURE_2D);

    for (int i = 0; i < BMap.TotalMesh; ++i)
    {
        glBindTexture(GL_TEXTURE_2D, BMap.Mesh[i].TextureID);

        glEnableClientState(GL_VERTEX_ARRAY);
        glVertexPointer(3, GL_FLOAT, 0, BMap.Mesh[i].Vertice);

        glEnableClientState(GL_NORMAL_ARRAY);
        glNormalPointer(GL_FLOAT, 0, BMap.Mesh[i].Normal);

        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glTexCoordPointer(2, GL_FLOAT, 0, BMap.Mesh[i].TexCoord);

        glDrawElements(GL_TRIANGLES, BMap.Mesh[i].TotalFace * 3, GL_UNSIGNED_INT, BMap.Mesh[i].Face);

        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_NORMAL_ARRAY);
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        glBindTexture(GL_TEXTURE_2D, 0);
    }

    glDisable(GL_TEXTURE_2D);

    glPopMatrix();
}

int LoadTexture(char* m_pFile)
{
    char szHeader[54]; // Each BMP file begins by a 54-bytes header
    int DataPos; // Position in the file where the actual data begins
    int iWidth, iHeight;
    int Size; // = width*height*3
    char* BitMap; // Actual RGB data

    char dir[64];
    sprintf(dir, "%s", m_pFile);

    FILE *pFile = fopen(dir,"rb");

    if (!pFile)
    {
        printf("CModel::LoadTexture->Image could not be opened %s\n", m_pFile);
        return -1;
    }

    // If not 54 bytes read : problem
    if (fread(szHeader, 1, 54, pFile) != 54)
    {
        printf("CModel::LoadTexture->Not a correct BMP file\n");
        fclose(pFile);
        return -1;
    }

    if (szHeader[0] != 'B' || szHeader[1] != 'M')
    {
        printf("CModel::LoadTexture->Not a correct BMP file\n");
        fclose(pFile);
        return -1;
    }

    // Read ints from the byte array
    DataPos     = *(int*)&(szHeader[0x0A]);
    Size        = *(int*)&(szHeader[0x22]);
    iWidth      = *(int*)&(szHeader[0x12]);
    iHeight     = *(int*)&(szHeader[0x16]);

    // Some BMP files are misformatted, guess missing information
    if (!Size) Size = iWidth * iHeight * 3; // 3 : one byte for each Red, Green and Blue component
    if (!DataPos) DataPos = 54; // The BMP header is done that way

    // Create a buffer
    BitMap = new char [Size];

    // Read the actual data from the file into the buffer
    fread(BitMap, 1, Size, pFile);

    //Everything is in memory now, the file can be closed
    fclose(pFile);

    GLuint pTex;

    glGenTextures(1, &pTex);
    glBindTexture(GL_TEXTURE_2D, pTex);
    //glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, iWidth, iHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BitMap);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    //gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, iWidth, iHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, BitMap);

    //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    //Mesh[MeshTotal - 1].pTex = pTex;
    ////strncpy(pTexture.szFile, szFile, sizeof (pTexture.szFile) - 1);
    //printf("Texture loaded %s Tex %d\n", pTexture.szFile, pTexture.pTex);
    printf("CModel::LoadTexture->Texture loaded %s %d\n", m_pFile, pTex);
    free(BitMap);
    return pTex;
    //TexNum++;
}

```

# Answer
> 1 votes
There are several things wrong with your vertex and texture coordinate reading code. It's not doing what you think it is, and I think you could greatly simplify it while making it more robust. Let's just look at vertexes for the moment.

When it detects that the next thing in the file is a vertex, it allocates memory for 3 floats for each vertex. It then reads 3 coordinates into memory pointed to by `TempVertice`. Next it attempts to copy those 3 coordinates into the actual mesh, but it doesn't. What this line says:

```
memcpy(&Mesh[iMesh].Vertice, &TempVertice, sizeof (TempVertice));

```

is to copy the thing at the address of `TempVertice` into the thing at the address of `Mesh[iMesh].Vertice`. In other words, you're constantly writing the `TempVertice` pointer into the `Mesh[iMesh].Vertice` pointer. This clearly isn't what you intended, but it works out nicely because you never release the memory in `TempVertice`, and it actually does contain all the vertices. So you get lucky and your vertex data is correct, but just by chance. Since you never allocated `Mesh[iMesh].Vertice`, it doesn't cause a crash or leak any memory. (Well, I guess it leaks because you never free `Mesh[iMesh].Vertice`, but it doesn't leak twice.)

The rest of the code makes the same mistakes with texture coordinates and normals. This is likely the source of your problems.

What I would do is try to clean up the code. First, don't use magic numbers like:

```
readMode = 3;

```

Instead, create constants for them so others can read it. Write something like this:

```
readMode = READMODE_UV_COORDINATES;

```

or whatever. (You'll need to #define `READMODE_UV_COORDINATES` as 3 somewhere above or in a header.)

Next, create structs for your data. Your vertices aren't just a 1 dimensional string of floats. They're a 1 dimensional array of 3D coordinates, so you should declare them as such:

```
typedef struct Coord3D {
    float x;
    float y;
    float z;
} Coord3D;

```

Then you can do something like:

```
fscanf(pFile, "%f %f %f", &tempVertice [ i ].x, &tempVertice [ i ].y, &tempVertice [ i ].z);

```

Much easier to read and understand than `[ i * 3 + 1 ]`.

And of course, you need to keep better track of your memory. Since you're in C++, you should consider using the standard template containers like `std::vector`. They resize on-the-fly and you can declare them directly in your main object instead of having pointers to them which need to be tracked.

---
Tags: opengl, c++, 3d, textures
---


# Question
Title: track how far player is from finish line
We are developing mobile racing game.We are looking to implement tracking system.

For example if four players are on race track then in up side of screen one slide bar type line will be there whcich will show how far user is from finish line.

Angry birds GO has done similar thing,Check in https://i.stack.imgur.com/YoAGy.jpg

Any suggestion on implementation ?

# Answer
Assuming your track is *not* straight, a way to calculate the ratio:

1. Place invisible gates on strategic parts of your track, mainly in curves.
2. The total length of your track is the sum of the distance between each gate.
3. Each frame, given the last passed gate position to be Gl and the next gate position to be Gn, and the player position being P, D = |P - Gn| / (|P - Gl| + |Gn \- P|) * (|Gn \- Gl|), where D is the distance you calculate from the last passed gate.
4. You add D to the sum of the distances between all passed gate, lets call this T. T is the distance from the start of the track to the current point.
5. Divide T by the total length of the track and you get the current completed ratio of the player.

The odd calculation in 3 is to determine the ratio the player has to complete in the current gate span, and takes into consideration that the player could be off-track.
> 7 votes

# Answer
I'd say you probably want to trace out the track. Try setting up a script for the camera that adds the current position of the camera to a list every so many steps (AKA don't do it by time, but do it by distance.) Once you're done tracing the track you should probably dump a list of positions to a text file so that you can copy them and use them in-game.

The more positions (aka checkpoints) you have around your race track, the more exact the position bar will be.

Here's a picture for demonstration:

Sorry about the bad image quality. :P

EDIT: btw something just occurred to me - if your racing game has walls around the track edges then it won't be possible to cut through a section of grass. So if you're on two bends that come very close to eachother just using the distance formula will result in the game thinking that you are further ahead than you can possibly be. So to fix this, to get marker N, find the closest marker that is not more than 3 or 4 markers ahead of the last marker you were closest to.

Hope this helps!
> 5 votes

# Answer
SOLUTION

As posted algorithm in the other answer, here is the documented code flow of it,

Requirements,

> Add one slider
>
> Waypoints/checkpoints/gats holder script

Code,

```
Add following code in Coroutine,

  float totalDistance;
    int lastPassedWaypoint, upCoimngWayPoint;
      float dis;
    PlayerController playerCOntroller;
    float TotalDistanceCovered,ratio;

IEnumerator TrackPositions(){

//getting total distance of track
 for (int i = 0; i < Waypoints.Count - 1; i++)
        {
            totalDistance += Vector3.Distance(wayPoints[i].transform.position, wayPoints[i + 1].transform.position);
        }
    while (true)
    {

        if (upComingWayPoint == 0)
            continue;

            lastPassedWaypoint = upComingWayPoint - 1;

        upCoimngWayPoint = Manager.upComingWayPoint; //get this from player manager script

   //Use below multiline code if you need to track out of the track palyer position

       /*dis = Vector3.Distance(this.transform.position, wayPoints[lastPassedWaypoint].transform.position) /
        //  (  Vector3.Distance(this.transform.position , wayPoints[lastPassedWaypoint].transform.position) +
        //         Vector3.Distance(wayPoints[upCoimngWayPoint].transform.position , this.transform.position) *
        //        Vector3.Distance(wayPoints[upCoimngWayPoint].transform.position , wayPoints[lastPassedWaypoint].transform.position));
        ////totalDistance = wayPoints[WayPointsHolder.wayPointsHolder.wayPoints.Count].transform.position - wayPointsHolder.wayPoints[0].transform.position;
*/

//else use below line (optimized)
            dis = Vector3.Distance(this.transform.position, wayPoints[lastPassedWaypoint].transform.position);

        TotalDistanceCovered = 0;

        for (int k = 0; k < lastPassedWaypoint ; k++)
        {

            TotalDistanceCovered += Vector3.Distance(wayPointsHolder.wayPoints[k].transform.position, wayPointsHolder.wayPoints[k + 1].transform.position);
        }
        TotalDistanceCovered += dis;
        ratio = TotalDistanceCovered / totalDistance;

        YOUR_SLIDER.value = ratio;

        yield return new WaitForSeconds(0.02f);
    }

```
> 1 votes

# Answer
All players move according to the x-axis. Your target has a constant x position. You can know how far they're from the finish line by knowing the value of `Target.X - Player.X`. If it equals zero, he's arrived.
> 0 votes

---
Tags: unity
---


# Question
Title: Draw a line/curve for the path an object has taken
Hello I am making a game in libgdx. I want to draw a line/curve of the path a object have taken.

First a thought I could save all positions of the objects each iteration and draw line between them using the Shaperenderer. This is however inefficient because the number of saved positions for a object becomes really large, and I have alot of objects.

My second thought was to draw a line between only the previous position and the current position on to a pixmap, and then draw the pixmap to the screen. This way I only need to save the old position because I don't clear the pixmap. The problem is that the world is infinitely big, and the pixmap cant cover the entire world (and it is bad to make a really big pixmap?). Also when I zoom out of the world the lines becomes really small and I cant see them. When I use the shaperenderer, the lines are always one pixel wide independent of the zoom.

So is there a smart way where I can draw the path my objects have taken without saving all previous positions, and where the line stays constant width?

# Answer
Why not save the position every 2.5 seconds? It will reduce the number of units needed to save variable
> 2 votes

# Answer
In either cases you'll run out of memory.

For lines you need to discard old lines, or simplify the lines as you go, or both.

For pixmaps you'll need to make multiple pixmaps in a grid and either discard them when they go off the screen or write them to the filesystem and reload them when you come back. And eventually running out of disk space if your world is infinitely big, might take years, but you will.

And as for zooming out pixmaps, you'll have to generate **mipmap**s (http://en.wikipedia.org/wiki/Mipmap) yourself by using the MAX or OR function so that when merging pixels if any of the 4 pixels are marked the resulting pixel is marked as well so they don't fade as you zoom out.

There is no easy solution for this as the amount of memory and CPU/GPU processing power are finite.
> 0 votes

---
Tags: libgdx
---


title: 3D isometric depth sorting

text:
# Question
Title: 3D isometric depth sorting
How is it possible to depth sort tiles and objects in an isometric environments without any limitations? I've been researching this for a while now and there seems to be no publicly available answers to this question.

There are two obvious options for depth-sorting when doing isometric environments:

1. Draw all tiles from screen top to screen bottom, followed by all objects from screen top to screen bottom
2. Draw each tile and then each object on that tile from screen top to screen bottom

The limitations with number 1 is that tiles cant have different heights because objects will always appear on top of the tiles. Screenshot example:

The limitations with number 2 is that objects can't move between tiles on the x-axis without the tile below overlapping it (because it's drawn later). I've grabbed a screenshot to exemplify this:

I've read lots on bubble sorting and other algorithms, but none of them seem to take this into account, or if they do, they don't document how.

(Please not before answering, this is **NOT** about how to sort objects that are larger than 1 tile, I'm more than happy with slicing them up so they fit into a tile)

# Answer
> 3 votes
You can do it with a topological sort (usually) but even with just straight rectangular prisms you can still get cycles, so you have to watch out for that. But you may well be able to avoid that in your level design.

Here's a great introduction (since the article has moved once, this is the code on github, which should hopefully always have a current link to the article):

https://github.com/shaunlebron/IsometricBlocks

http://en.wikipedia.org/wiki/Topological\_sorting has two algorithms for doing a topological sort: I've used the depth-first one and just broken cycles by choosing the first one I encountered to be in front. So it won't crash or fail to complete if you have cycles, it will just look wonky. And you can easily report them if you're writing a map editor.

# Answer
> 1 votes
totov, split scene on layers (sort scene by layers) and draw it layer by layer.

For example:

* layer 1: tiles
* layer 2: object, that lays over tiles layer
* layer 3: objects, that lays over objects on layer 2
* ...
* ...

then count layers, and for each:

* draw tiles (top to bottom)
* draw objects, marked as layer 2 (top to bottom)
* draw objects, marked as layer 3 (top to bottom)
* ...

---
Tags: 2d, 3d, mathematics, algorithm, isometric
---


title: Native vs Desktop Resolution

text:
# Question
Title: Native vs Desktop Resolution
I have code set up that finds the native resolution of a monitor and uses that to determine the resolution for (DirectX exclusive) fullscreen mode, using SetupAPI:

```
HRESULT Window::Output::extractNativeResolution() {
    DISPLAY_DEVICEW dd = { 0 };
    CString DeviceID;
    HDEVINFO devInfo = NULL;
    HRESULT hr;
    DWORD err;
    BOOL bresult;

    static const GUID GUID_CLASS_MONITOR = {
        0x4d36e96e,
        0xe325,
        0x11ce,
        0xbf,
        0xc1,
        0x08,
        0x00,
        0x2b,
        0xe1,
        0x03,
        0x18
    };

    dd.cb = sizeof(dd);

    if (EnumDisplayDevicesW(desc.DeviceName, 0, &dd, 0) == FALSE) {
        goto failure;
    }

    DeviceID.Format(L"%s", dd.DeviceID);
    DeviceID = DeviceID.Mid(8, DeviceID.Find(L"\\", 9) - 8);

    devInfo = SetupDiGetClassDevsExW (
        &GUID_CLASS_MONITOR,                    //const GUID* ClassGuid
        NULL,                                   //PCWSTR Enumerator
        NULL,                                   //HWND hWndParent
        DIGCF_PRESENT,                          //DWORD Flags
        NULL,                                   //HDEVINFO DeviceInfoSet
        NULL,                                   //PCWSTR MachineName
        NULL                                    //PVOID Reserved
    );

    if (devInfo == NULL) {
        err = GetLastError();
        CHECK_ERR();
    }

    for (ULONG i = 0; ERROR_NO_MORE_ITEMS != GetLastError(); ++i) {
        SP_DEVINFO_DATA devInfoData;
        memset(&devInfoData, 0, sizeof(devInfoData));
        devInfoData.cbSize = sizeof(devInfoData);

        if (SetupDiEnumDeviceInfo(devInfo, i, &devInfoData)) {
            bool bRes = false;

            HKEY hDevRegKey = SetupDiOpenDevRegKey (
                devInfo,                        //HDEVINFO DeviceInfoSet
                &devInfoData,                   //PSP_DEVINFO_DATA DeviceInfoData
                DICS_FLAG_GLOBAL,               //DWORD Scope
                0,                              //DWORD HwProfile
                DIREG_DEV,                      //DWORD KeyType
                KEY_READ                        //REGSAM samDesired
            );

            if (!hDevRegKey || (hDevRegKey == INVALID_HANDLE_VALUE)) {
                continue;
            }

            {
                DWORD dwType, AcutalValueNameLength = 128;
                TCHAR valueName[128];

                BYTE EDIDdata[1024];
                DWORD edidsize = sizeof(EDIDdata);

                for (LONG i = 0, retValue = ERROR_SUCCESS; retValue != ERROR_NO_MORE_ITEMS; ++i) {
                    retValue = RegEnumValueW (
                        hDevRegKey,             //HKEY hKey
                        i,                      //DWORD dwIndex
                        &valueName[0],          //LPWSTR lpValueName
                        &AcutalValueNameLength, //LPDWORD lpcchValueName
                        NULL,                   //LPDWORD lpReserved
                        &dwType,                //LPDWORD lpType
                        EDIDdata,               //LPBYTE lpData
                        &edidsize               //LPDWORD lpcbData
                    );

                    if (retValue != ERROR_SUCCESS || 0 != wcscmp(valueName, L"EDID")) {
                        continue;
                    }

                    nativeWidth = ((EDIDdata[58] >> 4) << 8) | EDIDdata[56];
                    nativeHeight = ((EDIDdata[61] >> 4) << 8) | EDIDdata[59];

                    bRes = true;
                }
            }

            RegCloseKey(hDevRegKey);

            if (bRes) {
                break;
            }
        }
    }

    bresult = SetupDiDestroyDeviceInfoList(devInfo);
    CHECK_BRESULT();

    if (nativeWidth == 0 || nativeHeight == 0) {
        failure:

        nativeWidth = desktopMode.dmPelsWidth;
        nativeHeight = desktopMode.dmPelsHeight;
    }

    return S_OK;
}

```

(Adapted from here)

Basically, this code digs into the monitor's EDID information to find the primary resolution. Any time the user enters exclusive fullscreen, the back buffer will be set to this resolution, and an intermediate buffer will be used for cropping and scaling based on the user's graphics settings. I've decided to use this method instead of relying on DXGI because the implementation is much simpler (DXGI is... weird).

The problem with this code, though, is that it doesn't work on all monitors. Some don't follow the standard, or opt to provide resolution information in a different format. I'm thinking about improving this to work on all (or most) monitors, but is something like this really necessary for a game? Is it safe to assume that most users' desktop resolution is the same as their native resolution? If not, does it really matter?

# Answer
> Is it safe to assume that most users' desktop resolution is the same as their native resolution

You're asking the wrong question. Is it a "safe" assumption? Yes.

The real question: is it safe to actually *try* to use the "native" resolution without the user explicitly telling you to do so? Absolutely not!

> If not, does it really matter?

What matters is making a game that *works* the first time the user opens it.

The desktop resolution is the one that the user has selected which we know works. The "native" resolution may in fact not work at all for any number of reasons (perhaps the monitor misbehaves at native resolution, or the user might play primarily from an attached mirror-mode projector that can't support the monitor's full resolution, or their GPU may have trouble driving their monitor's native resolution at a sensible refresh rate, or so on).

Always default your fullscreen mode to the user's desktop resolution. *Always*. Yes, this also means you shouldn't default to a smaller resolution like so many other games do, as that can also break in many of the same ways outlined above. If you want to be even safer, default to windowed mode (and make sure the window actually fits on the user's desktop) and not fullscreen.

Default to the option that is most certainly going to *work*, not the most flashy. If the user is for some reason running the desktop at a lower resolution than maximum, they have a reason. Respect the user, their system, their needs, and their choice.
> 3 votes

# Answer
EDIT: The DPI issue was my fault for not reading all of the documentation. Calling `SetProcessDPIAware()` before anything else renders this point moot.

EDIT2: `EnumDisplaySettings()` can get the screen resolution regardless of whether or not the application is registered as "DPI aware".

While it probably is safe to assume that the users set resolution is the same as their desktop resolution, this doesn't mean that the values returned from those functions are necessarily accurate. Case in point, using the standard Windows API, I get 1280x720 for these calls, whereas the actual resolution of my screen is 1920x1080. Due to DPI scaling, however, Windows returns the modified resolution. This can be fixed with a call to `SetProcessDPIAware()`, or by using `EnumDisplaySettings()` to get the current screen's resolution.

```
#include "stdafx.h"
#include "wtypes.h"

#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    int w, h;

    // Works regardless of DPI setting
    DEVMODE dev;
    EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &dev);
    w = dev.dmPelsWidth;
    h = dev.dmPelsHeight;
    std::cout << w << ", " << h << std::endl;

    // Fix DPI issue
    SetProcessDPIAware();

    RECT desktop;
    const HWND hDesktop = GetDesktopWindow();
    GetWindowRect(hDesktop, &desktop);
    w = desktop.right;
    h = desktop.bottom;

    std::cout << w << ", " << h << std::endl;

    w = GetSystemMetrics(SM_CXFULLSCREEN);
    h = GetSystemMetrics(SM_CYFULLSCREEN);

    std::cout << w << ", " << h << std::endl;

    w = GetSystemMetrics(SM_CXVIRTUALSCREEN);
    h = GetSystemMetrics(SM_CYVIRTUALSCREEN);

    std::cout << w << ", " << h << std::endl;

    system("pause");
    return 0;
}

```

Not sure if this helps.
> 2 votes

---
Tags: directx11, windows
---


# Question
Title: In Unity, how do I render a chromatic aberration effect?
I'd like to replicate the effect used in Teleglitch:

In this scene, an object is rendered more than once at different position with different color.

This game uses this shader effect to create impact. Whenever an object with high velocity moves or hits, this distortion is rendered to give more weight to the moment.

If I had complete control over rendering cycle, I would have re-drew all the in-game objects with different color and position.

However, in Unity, rendering is done via Renderer and I am not sure how to apply this effect to all objects in the game (except the world, so I cannot do post processing).

How can I do this?

# Answer
This effect is called **chromatic aberration**, it is achieved by **offsetting** the different **color channels**.

In the examples you have given it seems like all three channels have been offset without any blur or distortion, which is usually used along with chromatic aberration to create the effect of an old tv or lens.

I know that Unity 3d has a shader in the **standard assets** called **Vignetting**, which also **includes** the more advanced effects like **chromatic aberration**. I'm not sure if you can tweak the offsets, but you should be able to edit the shader.

As for only applying the effect to certain objects, you need to look into renderlayers and cameras. You need to have two cameras at the exact same position.

One camera will render **everything but** your characters. The other camera will then render the characters on top. You then want to apply the chromatic aberration shader to the second camera.

Keep in mind that the two camera technique might cause some z-depth problems.
> 3 votes

---
Tags: unity, rendering, graphic-effects
---


title: Game maker else checks all ifs?

text:
# Question
Title: Game maker else checks all ifs?
I have a list of if functions (checking if various spots in the room are empty) in one event. I want to check them ALL with an else statement (if none of the spots are cleared), and display a message. How would I do this?

# Answer
I do not know about game maker, but if it is as in the other programming languages, you must nest all the ifs, one inside the other.

Your former approach was:

```
If there is an object
    Start
    Create Instance
    End
If there is an object
    Start
    Create Instance
    End
//....
Else
    Start
    Do Something else
    End

```

You should try:

```
If there is an object
    Start
    Create Instance
    End
Else
    Start
    If there is an object
        Start
        Create Instance
        End
    Else
        Start
        If there is an object
            Start
            Create Instance
            End
        End
        Else
            Start
                Do Something Else.
            End
    End
//....

```
> 2 votes

# Answer
Gustavo Maciel wrote right answer. But I want add one more solution (sometime it can be very useful).

Using code it can be something like this:

```
var result = false;
if (statement)
{
    // action 1;
    result = true;
}
...
if (statement)
{
    // action N;
    result = true;
}

// no actions
if !result             // same with: if (result = false)
{
    // else action
}

```

P.S. I advise nevertheless to use a code, but not buttons. Solution of Gustavo Maciel via code:

```
if position_meeting(pos_x, pos_y, your_object)
{
    instance_create(pos_x, pos_y, blockObject);
    result = true;
}
else if position_meeting(pos_x, pos_y, your_object)
{
    instance_create(pos_x, pos_y, blockObject);
    result = true;
}
...
else if position_meeting(pos_x, pos_y, your_object)
{
    instance_create(pos_x, pos_y, blockObject);
    result = true;
}
else
{
    show_message("Your message");
}

```

Of course, here need to change all coords and object names.

btw,

```
else if (statement)
{
}

```

it same with

```
else
{
    if (statement)
    {
    }
}

```
> 0 votes

---
Tags: game-maker
---


# Question
Title: Are square or hex grids better for pathfinding?
Is there any significant difference between using a square or hexagonal grid for the area searched by a path finding algorithm. In other words, is square or hexagonal better, and if so why.

# Answer
> 19 votes
The main consideration for deciding whether to use square vs hex grids shouldn't be ease of AI implementation -- breadth-first and depth-first search algorithms are pretty much the same no matter what kind of graph you have.

Rather, this is a gameplay issue that should be considered by the game designers. Square grids are more accessible to the mass market (hex boards tend to look "geeky"), and in a world of up/down/left/right controls it's a lot more intuitive to navigate around squares than hexes from a UI standpoint. Square grids also tend to restrict movement a bit more; assuming orthogonal movement (and not diagonal), it takes 4 moves to walk around a one-square obstacle, compared to 3 moves in a hex grid. From a programming standpoint, hexes are also a little bit easier to implement but it's not about search algorithms as much as that a square grid equals a two-dimensional array, but a hex grid doesn't really map to a standard data structure.

The down side of square grids is that the movement never feels right. Moving diagonally should take sqrt(2) movement points, but in practice it's either 1 movement (which makes it feel like walking on diagonals is fast and there's rarely a reason to walk orthogonally) or it's 2 movement (which makes diagonal movement feel too slow). With hex grids, movement distance is a lot more intuitive, as it's always the same distance from one hex to another no matter which path you take.

# Answer
> 3 votes
I'm not an AI expert by any means, but the difference should be negligible. Square grids are a bit faster (4 connections per node instead of 6), but that's really not the limiting factor in the algorithmic runtime. Depending on what algorithm you're planning to use, the code might be a bit more complex for a hex grid, since it's a bit more complicated to calculate coordinates, and it's harder to use the sort of quadtree/octree shortcuts that I believe are often used in pathfinding.

But for a simple world like a turn-based-strategy game level, the difference between the two layouts shouldn't matter much; a square grid will be slightly simpler and faster.

# Answer
> 3 votes
There's one practical difference i can think off regarding path planning. Traversing from the center of an hex cell to on of its neighbors is always the same distance whereas, if you a allow diagonal travel, this is not true for squares.

# Answer
> 0 votes
This guide on hexagons is awesome. The part about pathfinding has an interactive example and some info on how to adapy square pathfinding.

> If you’re using graph-based pathfinding such as A\* or Dijkstra’s algorithm or Floyd-Warshall, pathfinding on hex grids isn’t different from pathfinding on square grids.
>
> * Neighbors. The sample code I provide in the pathfinding tutorial calls graph.neighbors to get the neighbors of a location. Use the function in the neighbors section for this. Filter out the neighbors that are impassable.
> * Heuristic. The sample code for A\* uses a heuristic function that gives a distance between two locations. Use the distance formula, scaled to match the movement costs. For example if your movement cost is 5 per hex, then multiply the distance by 5.

---
Tags: ai, path-finding
---


# Question
Title: My sprites are spwaning on top of each other with a new class?
I am making a game for college in XNA C#, however I have got to the point where I need some enemy sprites to be spawned in for the player to shoot. I did this with one enemy by itself without using arrays and for loops to load and update all the enemy's at once as I have my enemy sprites inside a class. The class I have it supposed to give the enemy a random position, load the texture in and then draw them.

So I thought I would put my enemy sprites in a form of a array, and use a for loop to load, update and draw them. However, it all works but they all spawn in the random position on top of each other, but this works with one enemy at a time without for loops or putting them in an array.

Here is some of the code I used:

This is how I decide how many enemy sprite I want.

```
giantManager[] giant = new giantManager[7];

```

Because I have to create an instants of the giantManager class before the load content I use this to do so:

```
        for (int i = 0; i < 7; i++)
        {
            giant[i] = new giantManager();
        }

```

The following is how I load the giantManager class with the texture for my giants in the load function:

```
            for (int i = 0; i < 7; i++)
            {
                giant[i] = new giantManager(Content.Load<Texture2D>("giant"));
            }

```

Then to draw them I just use:

```
            for (int i = 0; i < giant.Length - 1; i++)
            {
                giant[i].Draw(spriteBatch);
            }

```

And this is the draw method inside the class:

```
public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(giantTexture, new Rectangle((int)position.X, (int)position.Y, giantTexture.Width, giantTexture.Height), null, Color.White, giantAngle, new Vector2(giantTexture.Width / 2, giantTexture.Height / 2), SpriteEffects.None, 0);
    }

```

To choose my random spawn location I just use the Random C# data type and use if statements to decide which spawn location to set depending on the Random number generated. This happens in the constructor here:

```
    public giantManager(Texture2D newTexture)
    {
        giantTexture = newTexture;
        position = randomPosition();
    }

```

Just to conclude this question I would like to say sorry if I have posted to much code or not explained it in enough detail, I have tried by best.

Also if you look at this image below, it shows the rectangles in a black box, now the player rectangle is a little see through, but the giant rectangle is totally black which is because they all spawn on top of each other. That is my problem.

Thanks for reading all of this and any help in advanced would be great.

# Answer
> 1 votes
It is probably because you are creating a new `Random` object in `randomPosition()`.

You should create one `Random` instance and then use `Next()` to generate further unique random numbers. Otherwise the `Random` objects are instanced with the same seed (which is the current time) and thus return the same random number.

You can solve this by passing a `Random` object to `randomPosition()` and using it to generate the random numbers.

For example:

```
public Point randomPosition(Random r)
{
    return new Point(r.Next(), r.Next());
}

```

Then the create Giant function also needs to take a `Random` object as an argument which passes that argument to the `randomPosition` function.

```
Giant createGiant(Texture t, Random r)
{
    ...
    Pos = randomPosition(r);
}

```

And in your for loop:

```
Random r = new Random();
for(...)
{
    giant = CreateGiant(texture, r);
}

```

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


title: Simplify navmesh path

text:
# Question
Title: Simplify navmesh path
I'm trying to implement pathfinding in my game, I'm using navmesh with triangles.

I'm able to find a path but I want to simplify the path. This is what I have right now :

Green quad is start position and blue quad is the destination, the path taken by my character is in white.

Wireframe :

Node 1 and Node 2 are in differents triangles, I want to delete Node2 and go from Node1 to final destination.

How can I simplify this path ?

# Answer
What you are looking for is called string pulling, or the funnel algorithm. Basically these algorithms work by seeing if they can straighten the path. They do this in small increments until they have straightened it as much as they can - taking into account static obstacles and such. Here's a link that ought to help get you started.

http://digestingduck.blogspot.com/2010/03/simple-stupid-funnel-algorithm.html?m=1
> 3 votes

---
Tags: path-finding, navmesh
---


title: Basic vertex shader, moving

text:
# Question
Title: Basic vertex shader, moving
I am new in shader concepts and I am trying to implement a sprite of 8x8 in OpenGL ES.

I want to move the texture in the vertex shader but I cant figure out how to this, my code may be wrong, feel free to correct me

If I change this line in the vertex shader, the texture scale but I want to move not scale!:

```
v_TexCoordinate = a_TexCoordinate*vec2(1.5,1.5);

```

Vertex shader:

```
uniform mat4 u_MVPMatrix;       // A constant representing the combined model/view/projection matrix.
uniform mat4 u_MVMatrix;        // A constant representing the combined model/view matrix.
uniform mat4 u_TextureMatrix;

attribute vec4 a_Position;      // Per-vertex position information we will pass in.
attribute vec3 a_Normal;        // Per-vertex normal information we will pass in.
attribute vec2 a_TexCoordinate; // Per-vertex texture coordinate information we will pass in.

varying vec3 v_Position;        // This will be passed into the fragment shader.
varying vec3 v_Normal;          // This will be passed into the fragment shader.
varying vec2 v_TexCoordinate;   // This will be passed into the fragment shader.

// The entry point for our vertex shader.
void main()
{
// Transform the vertex into eye space.
    v_Position = vec3(u_MVMatrix * a_Position);

// Pass through the texture coordinate.
    v_TexCoordinate = a_TexCoordinate;

// Transform the normal's orientation into eye space.
    v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));

// gl_Position is a special variable used to store the final position.
// Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
    gl_Position = u_MVPMatrix * a_Position;
}

```

This is my draw fuction

```
private void drawMagia()
{
    GLES20.glUseProgram(mMagiaProgramHandle);
    mTextureMatrixHandle = GLES20.glGetUniformLocation(mMagiaProgramHandle, "u_TextureMatrix");
    mMagiaTextureCoordinateHandle = GLES20.glGetAttribLocation(mMagiaProgramHandle, "a_TexCoordinate");

    mMagiaPositions.position(0);
    GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false,
            0, mMagiaPositions);

    GLES20.glEnableVertexAttribArray(mPositionHandle);

    // Pass in the normal information
    mMagiaNormals.position(0);
    GLES20.glVertexAttribPointer(mNormalHandle, mNormalDataSize, GLES20.GL_FLOAT, false,
            0, mMagiaNormals);

    GLES20.glEnableVertexAttribArray(mNormalHandle);

    // Pass in the texture coordinate information
    mMagiaTextureCoordinates.position(0);
    GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, GLES20.GL_FLOAT, false,
            0, mMagiaTextureCoordinates);

    GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);

    // This multiplies the view matrix by the model matrix, and stores the
    // result in the MVP matrix
    // (which currently contains model * view).
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

    // Pass in the modelview matrix.
    GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVPMatrix, 0);

    GLES20.glUniformMatrix4fv(mTextureMatrixHandle, 1, false, mTextureMatrix, 0);

    // This multiplies the modelview matrix by the projection matrix, and
    // stores the result in the MVP matrix
    // (which now contains model * view * projection).
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

    // Pass in the combined matrix.
    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    // Pass in the light position in eye space.
    GLES20.glUniform3f(mLightPosHandle, mLightPosInEyeSpace[0], mLightPosInEyeSpace[1], mLightPosInEyeSpace[2]);

    // Draw the square.
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
}

```

# Answer
> 0 votes
The problem was that I was adding 1.5 and the range should be between 0-and 1.0

---
Tags: android, shaders, opengl-es
---


# Question
Title: How can I get the user altitude from an iPhone using Unity 3D?
I can see in the Unity 3D documentation that its possible to get the altitude of the user from their iPhone, but I cannot figure out how to actually do it.

I try this code:

```
using UnityEngine;
using System.Collections;

public class Altitude : MonoBehaviour {

    void Start () {
        Input.location.Start();
    }

    void Update () {
        Debug.Log (LocationInfo.altitude);
    }
}

```

and I get this error:

> Assets/Altitude.cs(11,41): error CS0120: An object reference is required to access non-static member \`UnityEngine.LocationInfo.altitude'

# Answer
LocationInfo is a struct so you need an instance of it to access its members. You can find a populated instance under (`LocationService.lastData`)\[http://docs.unity3d.com/ScriptReference/LocationService-lastData.html\] or `Input.location.lastData` references `LocationService.lastData`.

Meaning you can get the `altitude` like this:

```
void Start ()
{
    Input.location.Start();
}

void Update () {
    //lastData is an instance of LocationInfo
    Debug.Log (Input.location.lastData.altitude);
}

```
> 3 votes

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