# Question
Title: How do I stop the player from rotating when they collide with a tile?
I use Touch movement and if I jump and hit a corner with the feet of my player, my player rotates but I don't want this. Can anyone help me jumping without rotating if I hit anything ?

here is my Script:

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed = 10, jumpVelocity =  10;
    public LayerMask playerMask;
    public bool canMoveInAir = true;
    Transform myTrans, tagGround;
    Rigidbody2D myBody;
    bool isGrounded = false;

    private Animator anim;

    // Use this for initialization
    void Start ()
    {
        myBody = this.GetComponent<Rigidbody2D>();
        myTrans = this.transform;
        tagGround = GameObject.Find (this.name + "/tag_ground").transform;

        anim = GetComponent<Animator> ();
    }

    // Update is called once per frame
    void FixedUpdate ()
    {
        isGrounded = Physics2D.Linecast (myTrans.position, tagGround.position, playerMask);

        #if UNITY_ANDROID && !UNITY_IPHONE && !UNITY_BLACKBERRY && !UNITY_WINRT
        Move(Input.GetAxisRaw("Horizontal"));
        if(Input.GetButtonDown("Jump"))
           Jump();
        #endif
    }

    public void Move(float horizontalInput)

    {
            //Er klebt nicht mehr an den Waenden
        if (!canMoveInAir && !isGrounded)
            return;

        Vector2 moveVel = myBody.velocity;
        moveVel.x = horizontalInput * speed;
        myBody.velocity = moveVel;

        anim.SetFloat ("speed", Mathf.Abs (GetComponent<Rigidbody2D> ().velocity.x));

        if (horizontalInput < 0)
        {
            transform.localScale = new Vector2 (25, 25);
        }
        if (horizontalInput > 0)
        {
            transform.localScale = new Vector2 (-25, 25);
        }
    }

    public void Jump()
    {
        if (isGrounded)
            myBody.velocity += jumpVelocity * Vector2.up;
    }
}

```

# Answer
> 0 votes
Disable the rotation on the physics object that's part of your character. There's a few ways of going about that. You can do it via scripts:

```
void Start ()
{
    myBody = this.GetComponent<Rigidbody2D>();
    myBody.freezeRotation = true;

```

Or you can freeze specific axis of rotation in the Unity editor using the Inspector (found under the constraints section):

# Answer
> 0 votes
Alternatively to Byte56's answer, you can cancel the rotation, but not lock it. If you want to stop the rotation but not necessarily freeze it, you can use `myBody.angularVelocity = Vector3.zero`.

This means it will stop rotating, but if a new force is applied, it will start a fresh rotation.

---
Tags: 2d, physics, rotation, touch, jumping
---


# Question
Title: Blender game engine module file location
Where can I find the "bge" module file ? It imports well from a python script but I want to know where from.

# Answer
> 1 votes
As far as I am aware, there isn't an actual module file defining the `bge` module. Rather, the module is defined within Blender's actual engine code through Python's interop facilities.

---
Tags: blender-game-engine
---


title: Windows 10 User has only DX 10.1 API

text:
# Question
Title: Windows 10 User has only DX 10.1 API
A user of ours has an issue whereby they cannot run our application, which requires DX11 API support and hardware support for DX10.1. The strange this about this issue is that the user is running Windows 10, having upgraded from Vista(!).

His DXDiag output looks like this:

```
         Operating System: Windows 10 Pro 64-bit (10.0, Build 10240) (10240.th1.150930-1750)
             Language: English (Regional Setting: English)
  System Manufacturer: Dell Inc.
         System Model: Studio 1747
                 BIOS: Default System BIOS
            Processor: Intel(R) Core(TM) i7 CPU       Q 720  @ 1.60GHz (8 CPUs), ~1.6GHz
               Memory: 4096MB RAM
  Available OS Memory: 4084MB RAM
            Page File: 3956MB used, 3839MB available
          Windows Dir: C:\WINDOWS
      DirectX Version: 10.1

...

---------------
Display Devices
---------------
      Card name: ATI Mobility Radeon HD 4650
   Manufacturer: Advanced Micro Devices, Inc.
      Chip type: ATI display adapter (0x9480)
       DAC type: Internal DAC(400MHz)
    Device Type: Full Device
     Device Key: Enum\PCI\VEN_1002&DEV_9480&SUBSYS_02EB1028&REV_00
 Display Memory: 2809 MB
 Dedicated Memory: 1017 MB
  Shared Memory: 1792 MB
   Current Mode: 1600 x 900 (32 bit) (60Hz)
   Monitor Name: Generic PnP Monitor
  Monitor Model: unknown
     Monitor Id: SEC544B
    Native Mode: 1600 x 900(p) (60.209Hz)
    Output Type: Internal
    Driver Name: aticfx64.dll,aticfx64.dll,aticfx32,aticfx32,atiumd64.dll,atidxx64.dll,atiumdag,atidxx32,atiumdva,atiumd6a.cap,atitmm64.dll
Driver File Version: 8.17.0010.1129 (English)
 Driver Version: 8.970.100.9001
    DDI Version: 10.1
 Feature Levels: 10.1,10.0,9.3,9.2,9.1
   Driver Model: WDDM 1.1
Graphics Preemption: DMA
 Compute Preemption: DMA
       Miracast: Not Supported
Hybrid Graphics GPU: Not Applicable
 Power P-states: Not Applicable
Driver Attributes: Final Retail
Driver Date/Size: 1/13/2015 17:45:56, 1094024 bytes

```

I am by no means a DirectX expert, but my understanding was that all post W7 OS's had DX11+ support baked in to the operating system, and that updates are provided via Windows Update. I've never seen this particular issue before, and am not sure what the next step is. The user says that they are fully up to date wrt Windows Update.

Just to clarify a little more, here is a quote from a Q&A on the steam site:

> DirectX has two components - the API on the computer (the software) and the GPU (the hardware). You need both to have "support" for a specific DirectX version. What you get when you look at DxDiag is the API version installed on your operating system. It gives you the software. This number is useless if you don't have the equal number for your hardware.
>
> DirectX 11 API (the software) comes standard with Windows 7 and Windows 8.

The issue we are having is that we use the DX11 API via SharpDX, and use feature level 10.1. So we need the DX11 API, which we had assumed was always available for \> W7. It seems that this is not the case for this user, and it's the first time we have seen this.

# Answer
> 1 votes
Installing Windows 7 does not add DirectX 11 support for a GPU that does not have hardware support for it. Hovewer, DirectX 11 applications should not be able to fall back to DirectX 10 feature set, unless it was developed as relying heavily on 11 features, like tessellation or compute shaders.

```
D3D_FEATURE_LEVEL featureLevels[] =
{
    D3D_FEATURE_LEVEL_11_1,
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
};

```

If you pass in that array when creating your device, the highest available feature level will be enabled for the user, in your case that would be D3D\_FEATURE\_LEVEL\_10\_1.
You can check the current feature level by calling ID3D11Device::GetFeatureLevel() method when your device is created.

In case your application is using shader model 5 or higher, you must also provide shaders compiled as shader model 4.1 which is what directX 10 cards should support.

---
Tags: directx, directx11
---


# Question
Title: In Game Maker Studio, why does the image rotation have to be performed every step?
I'm a software developer who's trying to get into game development casually on the side. I picked up Game Maker Studio a while ago on a Steam Sale, and I'm finally getting into using it, especially after hearing that games like Undertale and Hotline Miami were products of said studio. I'm going through Shaun Spalding's Game Maker tutorials to familiarize myself with some of Game Maker's features and GML's coding syntax.

Following this tutorial, I rolled my eyes a little when he said to put the `image_angle = direction;` in the step event for my object rather than the creation event to rotate my object's sprite. "Why would you want to set a variable to the same value ***every frame*** when you could just set it once upon creation?" I thought to myself in my apparent naivety. But lo and behold, when running my project, the images aren't rotated if the `image_angle = direction;` is in the create event, and not the step event. Why? If `image_angle` is a member of my bullet object, shouldn't I be able to set it once upon creation? Or does it somehow reset on every frame?

# Answer
Naivety indeed! My `image_angle = direction;` code was on my bullet creation event. An alarm on my ship object is what creates the bullets, then sets their direction. The creation code on my bullet object was being called before the new direction had been set. I removed the creation code from my bullet and added the following code to my ship's alarm.

```
bullet1 = instance_create(x, y - 16, obj_bullet);
bullet2 = instance_create(x, y - 16, obj_bullet);
bullet3 = instance_create(x, y - 16, obj_bullet);

bullet1.direction = 90;
bullet2.direction = 80;
bullet3.direction = 100;

bullet1.image_angle = bullet1.direction;
bullet2.image_angle = bullet2.direction;
bullet3.image_angle = bullet3.direction;

```

Which allows the bullets to be created, sets their directions, and *then* re-angles their images.

A resounding "duh" is in order.
> 2 votes

---
Tags: 2d, rendering, rotation, game-maker, angles
---


title: Recognize hand drawn shape

text:
# Question
Title: Recognize hand drawn shape
I want to ask player to replicate a simple shape (triangle, square, star, anything that can be done in single stroke) with mouse or on a touchscreen.

Orientation matters, size does not. Example:

Can anyone give me directions to what techniques can be used?

# Answer
You will need to think of the shapes in vector form. So for your triangle, the shape might be represented as the series of vectors: (-0.5, -0.5), (1, 0), (-0.5, 0.5). because you know the shape and orientation, you are basically matching the user's finger movement to the expected shape.

The way you determine the scale of the image is by logging the user's initial touch point and then, every update, the point where their finger is, up until they reach the end of the first line (more on this later). The length of the vector from where the touch started to where the first corner is, is the scale of the image you are expecting them to draw. you multiply your vector representation of the expected shape by this scale to get the correct shape which they should draw.

To determine the first corner, you should probably keep track of the angle of the vector from the initial tap point to the current tap location. Once this angle differs from the expected angle by some threshold, you assume the user changed drawing direction.

Since the point where we detect the change in direction (lower blue cross on the image above) is not the actual corner is, instead it's where the threshold angle was crossed, we need to still determine the actual point to determine the correct scale. The way this is done is by looking at the first two vectors of our shape - in our case (-0.5, -0.5) and (1, 0). We adjust them so that the first goes through the tap start position and so that the second goes through the point where the threshold angle is crossed. We are left with (-0.5 + x1, -0.5 + y1) and (1 + x2, 0 + y2), where x1, y1, x2 and y2 are the offsets needed to ensure the lines go through the specified points. Then we find the intersection of these two lines. This is the point where the X value of both lines will be the same and the Y value of both lines will be the same.

To calculate the drawing quality, you will need to sample the user's path in equal distance intervals.

At each interval, you will find the closest point on the correct shape. The distance is the error.

At the end you will also need to normalize this error based on the drawn distance versus the correct distance. This is so that drawing a longer shape does not increase your error and so drawing a shorter one does not decrease it.

```
adjusted_error = measured_error * (correct_shape_length / drawn_shape_length)

```

Many of the things I mentioned here have alternative approaches. I could also go a lot more in depth regarding the linear algebra needed to do the calculations or the specific classes and methods used in Unity itself. I'll however need more information as to what additional help you need before I can do that.
> 12 votes

---
Tags: unity
---


# Question
Title: Resolution independence (for touch input on different mobile screens)
I have drag mechanic in Unity game and I want to have same experience in all devices. I've done this before in another game engine and now that Unity gives us Dpi with Screen.DPI, it should be much easier to achieve, but I can't figure it out for the love of the god.

My theory is you have to divide the delta movement of touch with Screen.Dpi to normalize the movement and make it same across devices with different screen sizes and dpi's:

(touch0.deltaPosition.x / dpi) * SENSITIVITY * Time.deltaTime;

But this doesn't work. Would someone please tell me why?

I've done extensive search on this but surprisingly nothing much can be found.

Thanks in advance and regards.

# Answer
> 2 votes
If I understand correctly, the issue you are having is finger movement not translating perfectly to pixel movement. The solution which worked for me came from the accepted answer to this post: Android Touch Variation Correction? (How to use Screen.dpi?)

Passing the `Touch` object into the `FixTouchDelta()` function made it work correctly.

---
Tags: unity
---


# Question
Title: Strange shadow behavior when light direction is parallel to a plane
i have a strange problem with shadow acne. It occurs when the light direction is parallel to a plane. Here is my code and a few images of the problem:

```
//this calculates the shadow matrix

    //########## 1st phase ##########

    float rangeX = globalData::windowWidth;
    float rangeY = globalData::windowHeight;

    m_ProjectionMatrix =  glm::ortho<float>(-rangeX,rangeX,-rangeY,rangeY, 0.1f,(float)globalData::zFar); // zfar is 500.0f here

    m_viewProjection = glm::lookAt(
                                glm::vec3(lightPosition.x,lightPosition.y,lightPosition.z),
                                glm::vec3(
                                            ((lightDirection.x==lightPosition.x) ? lightDirection.x+0.1f : lightDirection.x),
                                            ((lightDirection.y==lightPosition.y) ? lightDirection.y+0.1f : lightDirection.y),
                                            ((lightDirection.z==lightPosition.z) ? lightDirection.z+0.1f : lightDirection.z)
                                        ),
                                glm::vec3(0,1,0)
                            );

    glm::mat4 biasMatrix(
        0.5, 0.0, 0.0, 0.0,
        0.0, 0.5, 0.0, 0.0,
        0.0, 0.0, 0.5, 0.0,
        0.5, 0.5, 0.5, 1.0
    );

    glm::mat4 depthModelMatrix = glm::mat4(1.0);
    //this is used in the 2 phase, when i render the world objects
    mDepthBiasMVP = biasMatrix * m_ProjectionMatrix * m_viewProjection * depthModelMatrix;

    //Now for each object in the "world", i use another function like this:

    glm::mat4 depthMVP = m_ProjectionMatrix * m_viewProjection * objectModelMatrix;

    shader.sendUniform4x4("depthMVP", &depthMVP);

    //########## 2nd pahase ##########

    //for each object in the world, i send this uniform

    shader.sendUniform4x4("DepthBiasMVP", mDepthBiasMVP);

//in the shader i use this function to get the shadow "visibility"

float getVisibility(sampler2D shadowMap, vec4 vShadowCoord, float windowWidth, float windowHeight)
{
    float visibility = 1.0;
    float bias = 0.0001;
    float highResolutionShadowNearDistance = 20.0f;
    int PCF = 0;
    int blurRange = 1;
    float shadowFactor = 0.01;
    vec2 texelSize = 1.0 / textureSize(shadowMap, 0);

    for(int x = -blurRange; x <= blurRange; ++x)
    {
        for(int y = -blurRange; y <= blurRange; ++y)
        {
            int index = (PCF==1) ? int(4.0*random(floor(vWorldPos.xyz*100.0), y))%4 : y%16;
            vec4 vShadowSmooth = vec4(vShadowCoord.x + poissonDisk[index].x/windowWidth, vShadowCoord.y + poissonDisk[index].y/windowHeight, (vShadowCoord.z-bias)/vShadowCoord.w, 1.0);
            float pcfDepth = texture(shadowMap, vShadowSmooth.xy + vec2(x, y) * texelSize).r;
            visibility += vShadowSmooth.z - bias > pcfDepth ? -shadowFactor : shadowFactor;
        }
    }

    return visibility;
}

```

and the results are here:

this is OK:

this is OK:

this is WRONG:

the problems are marked with a red circle. Thanks a lot!

EDIT: this is the result of Peethor suggestion (maybe i havent implemented it well, please help :) ):

and this is de modified shader function:

```
float getVisibility(sampler2D shadowMap, vec4 vShadowCoord, float windowWidth, float windowHeight, camera _camera, vec3 vNormal)
{

    float visibility = 1.0;
    float bias = 0.0001;
    float highResolutionShadowNearDistance = 20.0f;
    int PCF = 0;
    int blurRange = 2;
    float shadowFactor = 0.01;
    vec2 texelSize = 1.0 / textureSize(shadowMap, 0);

    for(int x = -blurRange; x <= blurRange; ++x)
    {
        for(int y = -blurRange; y <= blurRange; ++y)
        {
            int index = (PCF==1) ? int(4.0*random(floor(vWorldPos.xyz*100.0), y))%4 : y%4;
            vec4 vShadowSmooth = vec4(vShadowCoord.x + poissonDisk[index].x/windowWidth, vShadowCoord.y + poissonDisk[index].y/windowHeight, (vShadowCoord.z-bias)/vShadowCoord.w, 1.0);
            float pcfDepth = texture(shadowMap, vShadowSmooth.xy + vec2(x, y) * texelSize).r;
            visibility += vShadowSmooth.z - bias > pcfDepth ? -shadowFactor : 0.001;
        }
    }

    // vNormal is a vertex normal and _camera.direction is the current light direction
    float parallelLightFactor =  dot(vNormal, _camera.direction);
    visibility *= parallelLightFactor;

    return visibility;
}

```

# Answer
This is to be expected. When the light is parallel to the surface, you would need an infinite resolution to make it smooth. Obviously that's not possible. In my game, I solved this by getting the normal of the light surface, getting the light direction, and taking the dot product of those vectors. When you darken everything in the shadow, multiply the 'shadow factor' with that dot product. The shadows will get darker when the light is perpendicular to the surface, and lighter when the light is parallel to the surface. Actually, the shadows disappear when parallel to the surface. But when you have global illumination on your object, you won't notice.
> 2 votes

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


# Question
Title: On a 2D generated terrain what is the easiest way to pick tiles for the shoreline?
If I have a two-dimensional array with ones and zeros for water and land respectively how do I choose what shoreline tile to use according to the water and land tiles surrounding it? The shoreline can form straight lines, outside corners and inside corners and there are four possible orientations for all of them. I have all the necessary tiles in the sprite sheet numbered. I want it to look similar to the shoreline in Age of Empires 2.

I could come up with a way to do this by comparing the eight surrounding tiles but this quickly became a mess as there are a lot of different possible combinations to take into account and manually assessing all of them with if statements seemed very unpractical and I'm quite sure there is a more elegant way of doing this. (I'm making this game with Slick2D)

# Answer
You can accomplish this with bitmasking. Each tile determines if it is an edge tile, based on its neighboring tiles.

From the image above, we would assign a value to each neighbor. 1, 2, 4, or 8 based on its location. If the neighbor is a different tile Type than the one in the middle, you add the corresponding value.

These values map out as shown in the image. You can then assign textures based on these values.

In your case, if anything is not 15 -- then you know it is part of an edge tile.

Take a look at my blog post on Finding Neighbors and Bitmasing here for more information.
> 7 votes

---
Tags: java, 2d, slick, terrain-rendering
---


# Question
Title: What is the exact difference between the game and game engine?
I thought game engine are something like Unity or Unreal. They have a editor with scene editor, some Physics library, some scripting editor and tools to improve the workflow of developer. Furthermore, I thought game engine should independent of the actually game.(i.e.) The game engine should not have any game logic in it.

However, I watched this game engine video and I am totally confused. https://www.youtube.com/watch?v=GK7ntA7a2vk . In the game engine video, I don't see the game engine anywhere because it seemed as though the professor developed the game straightaway.

I hope someone can explain the exact difference between a game engine and the actual game.

# Answer
First off, a game engine is more of a tool you use to create a game. It's something like Unity3D or Unreal, etc. But the difference of creating a game (I'll try to come up with the best explanation I can!) is that the game engine (https://en.wikipedia.org/wiki/Game\_engine) already supplies the bare bones you need to create a game, and most times, a lot of extra stuff also. The physics, editor, scene editors, etc, are stuff that a game engine would most likely have. Now, if you were to create 3D a game ALL BY YOURSELF, you would most likely want to use a rendering engine like OpenGL or DirectX. Like Minecraft used code written in Java, and there was no game engine used to create it. But there was a rendering engine to render all the 3D graphics.
> 1 votes

---
Tags: terminology
---


# Question
Title: How can I adapt A* pathfinding to work with platformers?
I have an A\* implementation that works in "top down" situations where gravity is not taken into account for pathfinding. But, I am looking to modify to work in a 2d platformer situation. I am using the Unity Engine in C# but any examples or even pseudocode would be really helpful. I have found a source so far but it haven't been that helpful as I am not understanding the way they have adapted A\*, I have listed them below.

http://gamedevelopment.tutsplus.com/tutorials/how-to-adapt-a-pathfinding-to-a-2d-grid-based-platformer-theory--cms-24662 (Very specific to authors implementation and hard to understand)

# Answer
You don't need to adapt A\* at all. The only consideration is where you put your nodes and how you connect them. The linked article seems to convert from a platformer-friendly model to a grid based pathfinding model, which I don't think you want.

A\* itself is a tree search algorithm which finds the optimal path through your graph and requires some heuristic - meaning a function, which establishes how close to the target they are. In your case this can just be Manhattan or Euclidean distance. A\* doesn't really care what the graph represents, it just sees it as a graph.

The only concern here is how to create the actual graph and how to determine movement cost between nodes. When moving on a 2 dimensional plane (so not a platformer), I've found that making a move in a cardinal direction (horizontal or vertical) costing '1' and a move in a diagonal direction costing '2.49' works well. Similarly, for your platformer, you will likely want to give a higher cost to jumps and drops.

**Crating the graph**

As the thread How can I implement platformer pathfinding? says, the way you will create your graph depends heavily on how your platformer works - what mobs can actually do and what you would like them to do. Here are a few examples though:

This first example assumes you cannot "jump through" blocks. Meaning you can't jump up through a block to reach a higher level, and can't jump down through a block. The graph can be simplified by removing all non-intersecting nodes (meaning nodes with exactly two ways out). I kept them in the image to contrast it with the next one.

In this graph, jumps to higher platforms are allowed from lower ones.

In this graph, jumps are allowed to lower platforms. Usually games tend to have 'specially marked' platforms, where drops are allowed, so this sort of connection might only be present with a particular kind of platform in your game.

And of course you can also do this so both drops from platforms and jump to platforms are allowed: (just for the sake of completeness)

**Pathfinding events (animations, physics, jumps)**

You will likely want to implement some sort of animation for each of these or some sort of behaviour, which ensures the move actually happens. For example, for jumps you might want to apply some force to the mob. The amount of force to apply you'll need to calculate yourself for your game, or determine through trial and error. What I wanted to mention is that, once the path has been determined and stored in the NPC, and the path is actually being executed (meaning the NPC is following the stored path), you will want to keep track of the next node it's moving towards. Once the node is reached, you trigger some sort of event on the NPC, for example `NPC.OnPathfindingNodeReached(action)`. the parameter `action` can be stored in the nodes for each of their possible exits. For example:

**Movement cost and common errors**

In terms of common non-obvious errors in pathfinding, they mostly have to do with mismatched movement costs. To ensure decent looking pathfinding, you must ensure that shorter paths always have a smaller cost. Depending on whether you manually or algorithmically assign costs, this can be much harder to do properly than it might seem at first and a major nightmare to debug. I recommend that you give a lot of care to assigning costs when doing this and testing everything as you make it.

I hope this post answered at least some of the questions not answered in the linked post. If you need more help, please comment.
> 24 votes

---
Tags: unity, 2d, path-finding, platformer
---


# Question
Title: Box2D fixed timestep updating is twitchy on constant FPS
I'm messing around with libgdx and box2d and I'm trying to implement sidescroller movement with fixed timestep logic according to the famous Fix Your Timestep! tutorial/guide. However, logic updating seems to be twitchy and I'm not exactly sure why.

Here's the render method where the issue lies:

```
public void render() {
    handleCameraInput();
    handleTestBodyInputImpulse();
  //handleTestBodyInputVelocity();

    accumulator += Math.min(Gdx.graphics.getDeltaTime(), STEP);

    int logicStepCount = 0;
    while (accumulator >= STEP) {
        world.step(STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
        accumulator -= STEP;
        ++logicStepCount;
    }

    Gdx.graphics.setTitle("FPS: " + Gdx.graphics.getFramesPerSecond() + ", Logic steps: " + logicStepCount + ", Test body vel: " + testBody.getLinearVelocity());

    cam.update(); // update box2d world camera
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    renderer.render(world, cam.combined); // renders box2d bodies
}

```

From what I've noticed the logic while loop responsible for updating the physics sometimes doesn't execute (counter goes from 1 to 0 for one frame) and that seems to be causing the twitching. This is weird to me since delta time added to the accumulator is clamped and since the FPS is constant 60 on my machine I'd assume that the loop should always execute once. Am I doing something wrong? Is this behavior normal and is it something I am supposed to solve during rendering with interpolation?

Complete minimal example can be found here on Gist and can be run on any LibGdx project with Box2d dependency.

# Answer
> 1 votes
For one, your FPS is not constant; it is being truncated/rounded into an `int`.
It is also probably being averaged over a number of frames.

Most likely, every Xth frame is taking only 16ms to complete (62.5 FPS), instead of 16.66666666666ms (60.0 FPS). Since (16.0 \< 16.66666), no physics update takes place. With an unlocked time-step, this occurs often (adding smaller fractions, more often) which is the reason you are implementing a "semi"-fixed time-step.

So, you want `600` to be `10 * 60`, not `20-5 * 30-120`. It's normal that it varies slightly; the accumulator's job is to make sure that you only spend time doing updates that are "worth it".

Likewise, your computer has other things to do than run your game; frames may occasionally take 17ms (58.8 FPS) to complete. By clamping `deltaTime`, you have thrown away 1ms of real time. If that happens every frame at "60 FPS", that equates to "lost time" of approximately 60ms per second (6%).

Without excessive drag on your CPU:

* If `STEP` is equal to your expected `deltaTime`, you'll *usually* run one update per frame, but occasionally zero or two. This is a frequently desired behavior.
* If `STEP` is less than your expected `deltaTime`, you'll *always* run one update per frame, but may frequently run two (or more). This is desirable if you want to use higher precision for physics updates than graphical updates. If you are careless, this can lead to the "spiral-of-death" and is one symptom of the orginal, "un-fixed", time-step where `STEP` is effectively 0 and the CPU can't catch up.
* If `STEP` is greater than your expected `deltaTime`, you'll spend proportionally more frames accumulating than you do updating. Without optimizing, this method renders many identical frames which is a second symptom of the original, "un-fixed", time-step, where the CPU and/or GPU are forced to work over-time, even when the game is idle.

Newcomers having time-step problems often fail to understand the difference between graphical-FPS and logic-FPS because they are both frequently referred to as "FPS". So, they "fix" problems within `Update()`, by calling `Render()` more often, trying to use all available power to spread the error out thin enough that it won't be noticeable. The problem is that the game produces different results on different computers; many of which are not desirable. That, of course, leads to the "Fix Your Timestep" article.

---
Tags: libgdx, box2d
---


# Question
Title: Cocos2d background sound not playing a second time C++
I'm using cocos2d-x on windows10 UWP project. I use the SimpleAudioEngine to load the music:

`CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("level_music1.wav",true);`

On the close button handler I use the end method: `CocosDenshion::SimpleAudioEngine::getInstance()->end;`

When I run the debugger a second time I get these exceptions:

> Exception thrown at 0x765F3E28 (KernelBase.dll) in MiniGolf.exe: 0x000006BA: The RPC server is unavailable. Exception thrown at 0x765F3E28 (KernelBase.dll) in MiniGolf.exe: 0x0000000E: Not enough storage is available to complete this operation. Assert failed: getFileSize should be override by platform FileUtils Assertion failed!

only if I rename the file to say like "level\_music.wav" it works again but failed again the second time so I have to constantly rename it to work.

# Answer
> 1 votes
this is an old bug which is fixed in cocos2d-x 3.10 and you can read more about it in here:

the bug is caused by a missing getFileSize() method implementation in the winrt file.

to fixe the bug just download the last version of cocos2d-x or add the fixe code manually by yourself by going to cocos2d\cocos\platform\winrt then open up CCFileUtilsWinRT.h and add this method signature to CCFileUtilsWinRT class in the public section:

```
virtual long getFileSize(const std::string &filepath);

```

then in the same directery open up CCFileUtilsWinRT.cpp and add the method implementation like this:

```
long CCFileUtilsWinRT::getFileSize(const std::string &filepath)
{
    WIN32_FILE_ATTRIBUTE_DATA fad;
    if (!GetFileAttributesEx(StringUtf8ToWideChar(filepath).c_str(), GetFileExInfoStandard, &fad))
    {
        return 0; // error condition, could call GetLastError to find out more
    }
    LARGE_INTEGER size;
    size.HighPart = fad.nFileSizeHigh;
    size.LowPart = fad.nFileSizeLow;
    return (long)size.QuadPart;
}

```

---
Tags: c++, cocos2d-x
---


# Question
Title: Manage user input and diffentiate it between the player and the app
I hope the title makes sense. Basically, I am trying to figure out how the app will know I the input I am sending it is meant for the app and not the player, and vice-versa.
(It is very similar to this question, A pattern for a contextual InputState in a Game State Management architecture)

This is an idea I've had, but it's flawed. Any suggestions?

There will be a class to gather input, called `IOManager` Another class will register the IOManager, called `IOHandler`. Various subclasses of the `IOHandler` will handle the output differently. For example, `IOPauseState` will handle input differently than `IOTitleState` or `IOPlayer`

My problem comes with differentiating between the "GameStates" and the "Player" when handling the IO. I could have two separate HandleInput functions in the IOHandler class; one that accepts a reference to a state and another that accepts a reference to the player, but that does not seem right.

How should I go about handling this, when I can't really subscribe them or pass them through because the player and the gamestates are two completely separate classes?

# Answer
As described in the question you linked to, there is a great XNA/C# example project that handles this problem elegantly. It is cleanly written, easy to read and very minimal; it may be helpful in inspiring your own c++ system. Game State Management Sample.

The method employed is that each part of the game is a "screen", including all menus, the game view, and any modal popups. The screens are handled like a stack. The screen manager, which is an exercise of the mediator pattern, takes care to flag each screen as being on top of the stack (or transitioning to/from). By doing this, it can toggle a flag in each screen that checks for updates to the input singleton (like your `IOManager`). If the screen is not on top, it doesn't check the input.

So, no `IOHandler` is required (still perfectly reasonable to have them), because every screen that needs input keeps a reference to the global input. But they only actually check that reference for updates when they are supposed to. This immediately solves the problem of common input between tiered menus, pause screens, loading screens, and gameplay input. Your app only gets input when it is the top-most screen, the player gets input when the gameplay is on top.

**Edit** \- Why the linked topic is asking the wrong question:

I think you are struggling to define a common `IOHandler` base class because inheritance is not the right way to do what you want. Inheritance can be mis-used to create a hierarchy of every single class in a system, but doing so creates the kind of problem you are having. It should be used only when a child class *is* the type it is extending. For menus and players, that's not the case.

The rhetorical example I like best is, "Should `Viewport` inherit from `Rectangle`? They're both rectangular." Well no, it shouldn't. Likewise, you are building a variety of objects that all respond to input. But they should not inherit from an `IOHandler` class. They should contain a reference to `IOManager`.

If you want your various menu screens to all use `IOManager` the same way, by all means give them a uniform update function in a parent class. `Player` should use it in an entirely different way. They should not be part of an inheritance tree.
> 3 votes

# Answer
I have typically handled input specially from the more generic state and event systems.

Input has "controllers" which register themselves. There are implicit priorities where state controllers are run in state stack order. A DOM Events model is used. The input event is delivered to each controller in order until one "consumes" it.

For keyboard and mouse `DOWN` events (a key/button is pressed), the controller that consumes that input is then recorded for that specific key. The corresponding `UP` event is delivered directly to that controller and then the registration is cleared. Also cleared during app focus switch to avoid alt-tab bugs. It can also be handy to clear them when the registered controllers change, so e.g. holding the left arrow doesn't keep moving the player when a menu pops up. If a controller is bound to a key and is removed for any reason than an actual `UP` event, one is synthesized and delivered before the controller is unbound.

For UI elements, a UI controller manages all the complexity of focus, tabbing, etc. UI states like `PausedState` or whatnot is responsible for taking any input messages and forwarding them to the UI. This allows UI elements to be visible while the UI is inactive, which for instance is handy with a layered UI system (e.g. a state for inventory management might keep drawing while a pause screen is active with a small pause menu in the middle of the screen).

The `PlayingState` controller is responsible for player game input rather than a particular game object. The state moves the player avatar rather than the avatar moving itself. It is possible and not all daft to have the objects manage input themselves, especially if you use a heavily component-based object system for menus and complex gameplay features, but I've personally felt that input game logic is much easier if all gameplay input handling is in a single place instead of strewn around a variety of objects, plus it ensures that the player avatar ceases to receive input when menu pops up.

This all works for event-based input. Game logic controllers for player avatar handling should be built specifically for polling input; also for key bindings. The playing state might take all raw input messages and deliver them into a `PlayerInputController` class which looks up keybindings, handles analog vs digital inputs, etc., and then maintains an internal state like `IsMovingLeft` or whatnot. The actual game logic can then receive events from the input controller, if you prefer that method, or it can poll the input controller every frame with something like `if (m_InputController.IsMovingLeft()) move_player_left();`
> 2 votes

# Answer
I know this is an old question, but I have been doing a lot a game engine design recently and wanted to share some of my thoughts on handling input. To me, a pause state, menu state, and player state are all conceptually the same as far as input goes. If I click something in the menu state, I am requesting to select that menu item. If I click somewhere on the game view, I am requesting the player pawn to move to that location (just as an example). So what I do is utilize a screen stacking system like Seth Battin mentioned in his answer, but instead of having references to the IO controller and a flag as to whether or not that particular screen handles IO, I use the chain of responsability/first responder design pattern. Here is some psuedo-code to give an example of what I mean:

```
Interface Screen
{
    public:
    void update();
    void render();
    bool handleIO(InputEvent ie); // Returns true if the input was handled and propagation of this event should stop.
    .
    .
    .
}

class InGameMenu implements Screen
{
    public:
    bool handleIO(InputEvent ie)
    {
        if(ie.type == MouseClick && m_menuItem1.intersects(ie.coordinates()))
        {
            // Handle logic for menu item 1 being selected.

            return false;
        }
        .
        .
        .   // Handle other menu items in a similar way.

        return true;    // The menu state always returns true if nothing important took place
                        // since you don't want that input being handled by other screens while
                        // the menu is up.
    }
}

class UIButton implements Screen
{
    public:
    bool handleIO(InputEvent ie)
    {
        if(ie.type == MouseClick && m_btnGraphic.intersects(ie.coordinates()))
        {
            // Handle logic for ui button being interacted with.

            return true;    // Usually true is the right return type if an event is handled, but
                            // if there is a case where you need Screens below to also handle
                            // the event, you have the option of returning false.
        }

        return false;   // The ui button will return false unlike the menu. This is the case
                        // because you want other screens lower in the Screen stack to handle
                        //  the event in the case where nothing interesting happened.
    }

}

class WorldMap implements Screen
{
    public:
    bool handleIO(InputEvent ie)
    {
        if(ie.type == MouseClick && /* Some other condition is met that needs this input  */)
        {
            // Handle logic input on the map.

            return true;
        }

        return false;
    }

}

```

Then the Screen Manager class might look similar to this:

```
class ScreenManager
{
    public:
    void pushScreen(Screen s)
    {
        screens.push(s);
    }

    Screen popScreen()
    {
        return screens.pop(s);
    }

    void handleIO(InputEvent ie)
    {
        foreach (Screen s in screens)
        {
            bool eventHandled = s.handleIO(ie);

            if(eventHandled)
            {
                break;
            }
        }
    }
}

```

So I think the comments help explain the process, but in your setup you would register your screens with the manager. One example using the above might be:

```
screenManagerInstance.pushScreen(mapScreenInstance);
screenManagerInstance.pushScreen(uiButtonInstance);

```

So now when you have an input, let's say a mouse click, the ui button get first priority to act on the click. If the click was not on the ui button, then the click event is passed on to the map where something interesting may take place if the click was on say a treasure chest or a bad guy. If the click never hits anything of interest by the time it reaches the bottom Screen, it is tossed off into eternity and should be destoryed or garbage collected.

If the another click happens, the process starts all over again. This time, let's say the click hits the ui button which should trigger the opening of the in game menu. Through some messaging mechanism outside the scope of this question, the ui button requests for the in game menu to open. This request would go to a logic controller or current game state that would do the proper state transitions and in the process push a inGameMenuInstance onto the screenManagerInstance:

```
screenManagerInstance.pushScreen(inGameMenuInstance);

```

Now when a click comes in, the inGameMenuInstance gets first priority on the click event and since we designed the in game menu to block all inputs from other Screens until it is closed, the uiButtonInstance and mapScreenInstance never even know that a click event came in. They just sit there until the menu is closed. The closing of the menu or selection of a menu item would probably trigger another state change message like our ui button did earlier. The logic controller or game state would perform the necessary transitions in logic and as part of that, remove the inGameMenuInstance from the screenManagerInstance:

```
screenManagerInstance.popScreen();

```

Now we are back to where we started and input can propagate through all Screens again. It is also worth noting that instead of passing an IO event, you could pass your IO manager that each Screen could query for what input is taking place.

Not the only way to handle IO between multiple components, but a way that has worked for me and is pretty flexible in my opinion.
> 1 votes

---
Tags: c++, game-design, input, design-patterns
---


title: Unity stats framerate vs Time.deltaTime

text:
# Question
Title: Unity stats framerate vs Time.deltaTime
Googling around, a way for calculating framerate and displaying it as text ingame is using `1/Time.deltaTime`. However, comparing this against unity stats FPS shows 2 different FPS. Which of it is incorrect? If `1/Time.deltaTime` is incorrect, how does one go about calculating FPS?

Below is a screenshot of the FPS difference, as seen in the profiler, fps is well below 100 FPS whereas calculated FPS stays around 60.

# Answer
> 5 votes
`1 / Time.deltaTime` is the actual FPS that the *whole Unity window* (or the game after building and running) is running at.

The FPS that the Stats window shows is the reciprocal of *only* the time taken to do the frame update and render the game view, and does not include the time taken in the editor to draw the scene view, inspector and other editor-only processing.

`Time.deltaTime` is (as per the docs) The time in seconds it took to complete the last frame. Or rather, it can also be defined as the difference in `Time.time` (time since start at beginning of frame) in the last frame and the current frame.

Thus, when run in the editor, `Time.deltaTime` *includes* time taken in the editor to draw the scene view, inspector and other editor-only processing, whereas the delta time and FPS in the Stats window *excludes* this time.

In your case, both the calculated FPS and the Profiler window are correct, since you have VSync on for your game. Zoom into the Profiler graph and you'll see that it too shows a relatively steady 60 FPS because of VSync. To actually see the difference, open the Stats window while playing the game and compare the delta time/FPS shown there and your calculated FPS with VSync off.

`Time.deltaTime` minus the delta time shown in the Stats window is the time it took to process and render the Unity editor.

---
Tags: unity, frame-rate
---


# Question
Title: Irrlicht app: Creating STL exception leads to segfault
I'm developing application with C++ language and Irrlicht engine.

When I add `std::runtime_error("err")` expression into my code, I got segmentation fault at address 0 (before entering to main). If instead I use `std::exception()`, app runs fine.

How std::runtime\_error() causes segfault and how to fix it? Thanks!

```
#include <stdexcept>
#include <exception>
#include "irrlicht.h"

int main() {
    irr::IrrlichtDevice* device = irr::createDevice();
    if (!device)
        throw std::runtime_error("err");  //without this run fine
}

```

Compile:

```
g++ -ggdb -Wall -Wextra -std=c++11 -o main main2.cc \
-lIrrlicht -lGL -lXxf86vm -lXext -lX11 -lXcursor

```

Backtrace:

```
(gdb) bt full
#0  0x00000000 in ?? ()
No symbol table info available.
#1  0xb5d88fe1 in init () at dlerror.c:177
No locals.
#2  0xb5d8942e in _dlerror_run          (operate=operate@entry=0xb5d88e10 <dlsym_doit>,     args=args@entry=0xbffff160) at dlerror.c:129
    result = <optimized out>
#3  0xb5d88e98 in __dlsym (handle=0x0, name=0xb7f8afe5  "posix_memalign") at dlsym.c:70
    args = {handle = 0x0, name = 0xb7f8afe5 "posix_memalign", who = 0xb7f674bc, sym = 0xb5d65b20}
    result = <optimized out>
#4  0xb7f674bc in ?? () from /usr/lib/nvidia-   304/libGL.so.1
No symbol table info available.
Backtrace stopped: previous frame inner to this frame     (corrupt stack?)

```

LD debug

```
LD_DEBUG=all LD_DEBUG_OUTPUT=log.txt ./main
tail log.txt.*

   3848:    symbol=__pthread_key_create;  lookup in file=/lib/i386-linux-gnu/libgcc_s.so.1 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/lib/i386-linux-gnu/libc.so.6 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/nvidia-304/tls/libnvidia-tls.so.304.131 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/nvidia-304/libnvidia-glcore.so.304.131 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libXext.so.6 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/lib/i386-linux-gnu/libdl.so.2 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libxcb.so.1 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/lib/ld-linux.so.2 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libXau.so.6 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libXdmcp.so.6 [0]

```

# Answer
> 0 votes
Looks like a bug related to NVidia. I've found workaround on this site: https://bugs.launchpad.net/ubuntu/+source/nvidia-graphics-drivers-319/+bug/1248642

(post #18)

explicitly specifying the path to NVIDIA's libGL using gcc's -L flag:

```
g++ -g -O0 -Wall -Wextra -std=c++11  -o main \
    main3.cc -L/usr/lib/nvidia-304/ -lGL -lglut

```

in this case app runs fine, no segfaults.

---
Tags: opengl, c++, irrlicht
---


# Question
Title: What is an equivalent of Swift's UIScreen.mainScreen().bounds in Unity 2d?
Basically, I am from a Swift SpriteKit background where `UIScreen.mainScreen().bounds` is a CGRect which represents the screen and can be manipulated in various ways like getting the middle of the screen by using

```
var screenCenter = CGPointMake(UIScreen.mainScreen().bounds.width/2, UIScreen.mainScreen().bounds.height/2)

```

What is an equivalent of UIScreen.mainScreen().bounds in Unity (C# Scripting) that can manipulated to get various positions in a similar manner?

# Answer
> 2 votes
Sounds like you want the Screen class:

```
var screenCenter = new Vector2(
                         Screen.width,
                         Screen.height,
                       ) * 0.5f;

```

Note that this will give you the pixel coordinates of the center of the screen, *in screenspace*. To translate this into a position within the world coordinate system, you'll want to use something like Camera.ScreenToWorldPoint.

---
Tags: unity, spritekit
---


# Question
Title: How can I delete parts of a mesh in Unity?
I am trying to make a destructible game environment; I want to delete the vertices (and triangles assorted to them) within some sphere of a given radius with its center at the contact point (in essence, just delete the part of the mesh that would be destroyed by an explosion of a projectile contacting it).

The way I'm trying to achieve it now is: take a mesh, and whenever there is a collision with it, construct a vector from each vertex to the hitpoint and measure its magnitude, if the magnitude is less than a given radius, then I add the vertex to a list (say TaggedVerts). After that I arrange the triangles array into a list of triplets. I take each vertex in TaggedVerts and translate it into its corresponding triangle number (basically its index in the mesh.vertices array) and check each triplet in the triangle list I had built earlier. If any triplet contains the tagged vertex, then I remove the whole triplet from the list. After doing this for all vertices in TaggedVerts, I put the List into an array and set mesh.triangles equal to it.

However, this method only works with a cube, and I am not quite sure it works correctly anyway since it deletes some triangles and some others it leaves intact.

Is there a better way to do this?

# Answer
I'm going to describe solutions in 2D which should be trivial to port to 3D.

**TL;DR** \- (1) You can replace whatever part of a Mesh you want in Unity but you must re-upload the entire mesh; (2) don't run through your entire vertex array(s) and do radius checks - it is prohibitive for larger meshes. (3) Don't use classic CSG as you are... voxels are easier to work with.

**Solutions**

> ...if the magnitude is less than a given radius...

Doing random access on the entire vertex array(s) is a no-no; it will be very slow as the mesh grows, as a (vertex) array is poorly suited to random access. Speculating here, but with `unsigned short` vertex indices Unity uses, we've a max of 64k vertices to sort through for every impact *per mesh* @ minimum 2 meshes per impact = up to 128k vertices to seek through.

Instead, use spatial subdivision.

* Divide your world space up into a grid. We'll call each square a *zone*. Let's say they're 32x32 units each, in a much larger world. This arrangement serves as an occupancy grid. Occupancy is a list of islands currently overlapping a given zone.
* We have a bunch of islands floating about in space - these are our discrete *meshes*. You'll need to limit their maximum bounds in XYZ. In this case let's say that on average, they're the size of a zone (32x32). Some are bigger, some are smaller, and when moving, even a small mesh can overlap up to 4 zones (8 in 3D) if sitting on the corner between these zones.
* Whenever an island moves (typically each tick), you need to update:

+ the occupancy grid - this means getting the bounds of the island and seeing which zones it overlaps, then putting it into the occupancy list for each such zone.
    + for all zones, the set of *all* vertices from *any* island which zone overlaps - different from the list of vertices which each *island* contains; necessary if you plan to store vertices by zone (below); performance impact of this can be reduced by only doing it a few times a second.
* Do a high level collision check using the occupancy grid: run through every zone, look at its set of occupying islands; if there is more than one island in that zone's set, those islands have *potentially* collided - this is only a coarse check i.e. *broadphase collision detection*.
* Do a geometric or voxel-based collision check to see if the finer details within these zones have *indeed* collided; we must compare every island in the zone's set to every other for total O(n^2) checks (but that should be fine if you have sparse islands in a large space).
* Use the results of the last step to resolve geometry destruction appropriately.

As we run through all zones each frame, this resolves all collisions. You may have more details to attend to, e.g. synchronising collisions of the same island across multiple zones.

As for getting the vertex array into its final form for upload to GPU...

* For each zone in the grid, write its vertices into the vertex array. That way as we walk vertex array, we have one zone after another. This affords spatial coherence which is good for CPU performance when it destroys terrain, and good for GPU read performance when rendering triangles.
* Store the start and end vertex indices for each and every zone. Now you can easily get back to that zone and modify it later, if a collision occurs. Sometimes, you will need to re-order / re-compress things. (With OpenGL or DirectX access, you could upload only the changed parts of the array... bummer about Unity!) Eskil Steenberg talks about this briefly here.
* Use a spatial hash function like a Z-curve to decide the best order (performance-wise) to insert your vertices into vertex array(s).

**Conclusion**

Other than this, the only inherent problem with what you're doing is that geometric approaches to destroying geometry can have some serious complications, drawbacks, and corner cases over using voxels - which is much of the reason voxels are now so common. You can stick with what you're doing and use the above to improve your current method, or switch to voxels and you can still benefit by the above improvements. In all, I hope this provides you a full answer.
> 1 votes

---
Tags: c#, unity, 3d-meshes
---


# Question
Title: Editing attached component property in Unity (C#)
This might be more of a general C#/programming query, but since it's game dev related, I'm putting it here.

I am trying to randomise a property in a custom component (C# script) across several Unity game objects.

hostiles is a list of game objects, each with an attached Stats component.

```
foreach (GameObject gO in hostiles)
{
    // Randomise spawn area…
    gO.GetComponent<Stats>().AreaNo = Random.Range(0, 3);
}

```

Perhaps unsurprisingly, all of my objects end up with the same value for AreaNo. It seems as though I’m reassigning some global version of Stats.AreaNo in my loop, rather than the individual instances. What am I missing?

(Sorry in advance for the noobish question!)

# Answer
> 1 votes
My bad. My hostiles list contained references to a prefab, rather than instances of it. Hence I was reassigning the same component property every pass of the loop.

---
Tags: unity
---


# Question
Title: Unable to load two enemies with same pic in sdl2
I have loaded two enemies(with the same pic) into my game. However, when I draw them onto the screen it only draws and animates one enemy, instead of two. I can't seem to figure this out.

Here is my animation class:

```
 Animation::Animation()
{
    sourceRect.x = sourceRect.y = 0;
}
void Animation::Animate(SDL_Texture* texture, int rows, int columns, SDL_Renderer *render, SDL_Rect pRect)
{

    Active = true;
    int textureWidth, textureHeight;

    prevTime = currentTime;
    currentTime = SDL_GetTicks();
    deltaTime = (currentTime - prevTime) / 1000.0f;
    if (Active == false)
        return;

    SDL_QueryTexture(texture, NULL, NULL, &textureWidth, &textureHeight);

    FrameWidth = textureWidth / rows;
    FrameHeight = textureHeight / columns;

    sourceRect.w = FrameWidth;
    sourceRect.h = FrameHeight;

        frameTime += deltaTime;
        if (frameTime >= 0.25f)
        {
            frameTime = 0;
            sourceRect.x += FrameWidth;
            if (sourceRect.x >= textureWidth)
            {
                sourceRect.x = 0;
                sourceRect.y += FrameHeight;
            }
            if (sourceRect.y >= textureHeight)
                sourceRect.y = 0;

        }

    SDL_RenderCopy(render, texture, &sourceRect, &pRect);
}

```

Here is the class for my enemy:

```
    Enemy::Enemy(std::string filePath, SDL_Renderer* render)
{
    //SDL_Texture *animation = LoadTexture(filePath, render);
    Animation enemyAnimation;
    SDL_Rect enemyRect;
    SDL_Surface *surface = IMG_Load(filePath.c_str());
    if (surface == NULL)
        std::cout << "Error " << std::endl;
    else
    {
        enemy = SDL_CreateTextureFromSurface(render, surface);
        if (enemy== NULL)
            std::cout << "Error " << std::endl;
    }
    SDL_FreeSurface(surface);

    enemyRect.x = 700;
    srand(time(NULL));
    //Randomly set y position of enemy
    enemyRect.y = rand() % 60;

    enemyPos.x = enemyRect.x;
    enemyPos.y = enemyRect.y;
    enemyRect.w = enemyPos.w = enemyRect.h = enemyPos.h = 100;
}

void Enemy::Update()
{

    enemyPos.x -= enemyMoveSpeed;

    if (enemyPos.x <= 0 || Health <= 0)
    {
        Active = false;
    }

}
void Enemy::Draw(SDL_Renderer* render)
{
    Animation enemyAnimation;
    enemyAnimation.Animate(enemy, 8, 1, render, enemyPos);

}

```

Here is my main.cpp file:

```
int main(int argc, char* args[])
{
    SDL_Window *window = nullptr;
    SDL_Renderer *gRenderer = nullptr;

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
        std::cout << "video initialization error: " << SDL_GetError() << std::endl;

    window = SDL_CreateWindow("Shooter", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, ScreenWidth, ScreenHeight, SDL_WINDOW_SHOWN);
    gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    ParallaxingBackground mainbg("mainbackground.png", gRenderer);
    /*ParallaxingBackground bg2("bgLayer1.png", gRenderer);
    ParallaxingBackground bg3("bgLayer2.png", gRenderer);*/
    Enemy Enemy1("mineAnimation.png", gRenderer);
    Enemy Enemy2("mineAnimation.png", gRenderer);

    if (window = NULL)
        std::cout << "Window creation Error: " << SDL_GetError() << std::endl;
    bool isRunning = true;
    Player p;
    SDL_Event ev;

    //AddEnemy(gRenderer);
    //Game loop
    while (isRunning)
    {
        p.Draw(gRenderer);
        //Event Loop
        while (SDL_PollEvent(&ev) != 0)
        {
            if (ev.type == SDL_QUIT)
                isRunning = false;
        }

        mainbg.Draw(gRenderer, mainbg.position);

        p.Update();
        p.Draw(gRenderer);

        //Update enemy1 and draw it
        Enemy1.Update();
        Enemy1.Draw(gRenderer);

        //Update enemy2 and draw it
        Enemy2.Update();
        Enemy2.Draw(gRenderer);

        SDL_RenderPresent(gRenderer);
        SDL_RenderClear(gRenderer);

    }
    SDL_DestroyWindow(window);
    SDL_DestroyTexture(p.Draw(gRenderer));
    SDL_DestroyRenderer(gRenderer);
    window = nullptr;
    gRenderer = nullptr;

    SDL_Quit();

    return 0;
}

```

# Answer
> 0 votes
Your problem is that `time` returns an object with second-precision. That results the same seed getting set for both of your enemies, and hence the first calls to `rand` after that will return the same value. You need to change the initial seed to something more accurate, or leave it out completely. You could also just leave seeding in, but move it to a more higher level in the code, such as your `main` function.

---
Tags: c++, textures, sprites, sdl2
---


# Question
Title: How to address a function inside an if condition using C# in unity 3D
I am new to game development and have very limited idea of C# syntax. I was watching unity 3D tutorials of UI and thought of using ModalPanel.cs and TestModalWindow.cs In a quiz game where 3 choices are there of a question and total 5 questions are there

Now suppose in

```
public void TestNYCI ()
{
   modalPanel.Choice(
         " string? ",
         icon,
         TestYesFunction,
         TestNoFunction,
         TestCancelFunction);

   // Here I want to use an if loop
   // if ( condition)
   // where condition means choosing of a function among
   // TestYesFunction, TestNoFunction, TestCancelFunction

   //Statements

   // If suppose TestYesFunction is true I want
   // to increment the count and write it as score
}

```

And will repeat the process in rest of the 5 functions.

Can someone please provide a suitable syntax to address the problem.

# Answer
Firstly, it should be understood that what happens after the modalPanel.Choice() call will not be affected by the choice made in modalPanel.Choice(). The line modalPanel.Choice() line will be run showing the panel although the panel is showing the execution of the TestNYCI() method does not stop. So any if statement dependent on the users choice in the panel would not be gotten. This is where the 3 UnityActions come in. Each one tells the system how to react to its respective button press.

Next, it should be noted that the three UnityActions are already conditional branches. So using you example the TestYesFunction would have some way of incrementing the score. This should be set up before you call the modalPanel.Choice() method. Something like:

```
void TestNYCI(Question question)
{
    var answerChosen = new UnityAction[3];
    for(i=0; i< 3; i++)
    {
        answerChosen[i] = () => {
            var answerIndex = i;
            // check is answer i is correct and score accordingly
        };
// Alternatively
        if(/* check is answer i is correct */)
        {
            answerChosen[i] = HandleCorrectAnswer;
        }
        else
        {
            answerChosen[i] = HandleWrongAnswer;
         }
    }

    modalPanel.Choice(question.Text,
        icon,
        answerChosen[0],
        answerChosen[1],
        answerChosen[2]);
}

```

It is important that if you do it the first way that you create a variable inside the lambda to store the index for each iteration because you will get an error either during compilation or and IndexOutOfRangeException because all 3 answerChosen items will behave as if i = 3
> 1 votes

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


# Question
Title: Why is quad rendered at the center (0,0) instead of top left when using orthographic projection
I have been trying to render a quad(containg a texture) using orthographic camera so that the quad can be rendered using the screen coordinates directly.

I started of by rendering just a triangle with a image. The triangle is rendered but it seems teh center of the screen is 0,0 but using the code below it should have been at top left of the screen.

**Ortho camera matrix code**:

```
// Set the camera position
        var cameraPosition = new Vector3(0.0f, 0.0f, 0.0f);
        var cameraTarget = new Vector3(0f, 0.0f, 1.0f); // Looking at the origin 0,0,0
        var cameraUp = new Vector3(0.0f, 1.0f, 0.0f); // Y+ is Up

        // Prepare matrices
        // Create the view matrix from our camera position, look target and up direction
        // direct X uses left hand co-ordinate system
        m_viewMatrix = Matrix.LookAtLH(cameraPosition, cameraTarget, cameraUp);

        // Initialize the world matrix
        m_worldMatrix = Matrix.Identity;
        var scalingMatrix = Matrix.Scaling(720, 576, 1);
        var translationMatrix = Matrix.Translation(new Vector3(0, 0, 0));
        var rotationMatrix = Matrix.RotationZ(0);
        m_worldMatrix = translationMatrix * scalingMatrix * rotationMatrix;

        m_worldMatrix = translationMatrix * scalingMatrix * rotationMatrix;
        var worlViewMatrix = Matrix.Multiply(m_worldMatrix, m_viewMatrix);
        m_projectionMatrix = Matrix.OrthoOffCenterLH(0, 720, 576, 0, 1f, 1000.0f);
        m_perObject.WorldViewProjection = Matrix.Multiply(worlViewMatrix, m_projectionMatrix);

```

**Vertices code:**

```
stream.WriteRange(new[]
            {
                new VertexPositionTexture(
                    new Vector4(720, 576, 0.5f, 1.0f), // position bottom-right
                    new Vector2(1024,576)
                ),
                new VertexPositionTexture(
                    new Vector4(0, 0, 0.5f, 1.0f), // position top-left
                    new Vector2(0, 0)
                ),
                new VertexPositionTexture(
                    new Vector4(720, 0, 0.5f, 1.0f), // position top-right
                    new Vector2(1024, 0)
                ),
            });

```

**Shader code:**

```
float4x4 WorldViewProj;

struct VertexShaderInput
{
 float4 Position : SV_Position;
 float2 TextureUV : TEXCOORD0;
};

VertexShaderOutput VSMain(VertexShaderInput input)
{
 VertexShaderOutput output = (VertexShaderOutput)0;
 //output.Position = input.Position;
 output.Position = mul(input.Position, WorldViewProj);
 output.TextureUV = input.TextureUV;
 return output;
}

```

**Screenshot of image rendered**:

Now I can't seem to figure out why the center of the screen is 0,0 and not top left ? Also as a part of this if I do not use a scaling matrix the triangle is not rendered.

The main reason behind the above attempt is to draw a quad/triangle using screen co-ordinates so that i can place exactly where i want without the need to calculate the vertices all the time when ever i wish to place my quad/triangle.

This issue has left me baffled for last couple days. Any help or suggestion would be really helpful.

**Note:** I am using Directx11 with sharpdx and still learning directx learner.

# Answer
> 1 votes
There are a few things going on. This is probably important to know, even if you never use GL.

---

These aren't the same anywhere, anytime:

```
"translationMatrix * rotationMatrix * scalingMatrix" //translate then rotate then scale
"scalingMatrix * rotationMatrix * translationMatrix" //scale then rotate then translate

```

---

**On top of that:**

GL is like an RPN-calculator using the *last* value provided, *first* (post-multiply):

```
 translationMatrix * rotationMatrix * scalingMatrix ==
"scalingMatrix * rotationMatrix * translationMatrix" //scale then rotate then translate

[R2] translationMatrix
[R1] rotationMatrix
[R0] scalingMatrix
[op] * //(replaces scaling and rotation matrices with (scalingMatrix, then rotationMatrix)
[op] * //(replaces [result] with ([result], then translationMatrix)

```

DX is like a "normal" calculator (pre-multiply):

```
 scalingMatrix *  rotationMatrix  * translationMatrix ==
"scalingMatrix *  rotationMatrix  * translationMatrix" ==
(scalingMatrix * (rotationMatrix) * translationMatrix) //() wherever you want

     scalingMatrix * rotationMatrix    = [immediate result] //scale, then rotate
[immediate result] * translationMatrix = [immediate result] //then translate

```

Both are correct for their respective API's and both produce the same results:

```
scaling then rotation then translation

```

---

I'm not an oracle, but all of my DX code looks like this (although I use the built-in matrix methods??):

```
world = scale * rotation * translation;
viewProj = view * proj;
//HLSL defaults to column-major but DX is row-major, so Transpose()
//(or don't use the defaults)
SendToGPU(world.Transpose());
SendToGPU(viewProj.Transpose());

//in the shader
worldPosition = vertex * world * viewProj;
"worldPosition = vertex then S then R then T then V then P"

```

You can step through this in the debugger with known input. Right after you create your world matrix, transform Vector3.Up by it and breakpoint. If you translate to {0,1,0} then scale by 2.0, you should be at {0,2,0}. If you end up at {0,1,0}, you are scaling, then translating.

---

**Don't work so hard:**

Generally, we try to re-use geometry. If you create a quad, centered at {0,0,0} whose length and width equal 1.0, then you can easily `ModelMatrix` that one quad to any size and place you want (including full screen). Using `Identity` for the `MVP`, you draw directly in clip-space, which centers a quad constructed as such in the screen by default. Clip-space has a fixed range of -1 to 1 on all axes (length/width/height == 2), so you could just scale the unit-quad by 2 and forget all the camera stuff.

---
Tags: c#, 2d, rendering, directx11, sharpdx
---


# Question
Title: Alternative to System.Drawing for breaking an image into separate tiles in Unity
As far as I can tell, `System.Drawing` namespace is not available in unity. I there an alternative library to load and manipulate or generate images on the fly?

Example: Imagine you want to make a jigsaw puzzle game and want to load and chop random images to use as textures or such.

EDIT: specifically I want to crop images and draw patches from one image onto another image. Or overlay images with grids.
Ultimately all the resulting images need to end up as textures on game objects. If need be, I can use `texture.EncodeToPNG` to save a copy for other purposes or for as a cached result.

EDIT AGAIN: Let's stick to a concrete example.
Player selects a photo from their iPhone library. It is chopped into pieces and appears on 9 cubes. the player need to arrange the cubes in the correct way to recreate the original image.

# Answer
> 3 votes
Quoting my first comment as requested:

> Since one of the largest responsibilities of a game engine is rendering, this functionality is found in quite a few different classes - Texture2D, RenderTexture, Material, Camera, Graphics, Renderer... You're unlikely to find a 1:1 replacement for the way you'd do it in GDI+, but if you give more details about your specific use case we can suggest Unity-friendly ways to achieve it

In this case, it sounds like we won't need to do any image modification or generation to get this outcome in Unity. We can use the existing texture scaling & offset capabilities of the built-in shaders.

Here's an example of one image split across 9 quads:

Here all I've done is create a material instance for each piece. I've set the tiling x & y to 1/3, and used a different offset for each piece (every unique x-y combination of 0, 1/3, 2/3)

All of the materials are referencing the same single texture in memory, with no need to modify it or duplicate it into separate sections.

You can either prepare these materials ahead of time in the editor, and assign their texture to reference the one the user selected at runtime, or you can create these materials wholly at runtime and align their texture sections using the Material.mainTextureScale and Material.mainTextureOffset setters.

The same trick works for cubes (you just need to be careful of the face orientation)

(This does result in one draw call per piece, but for such a small number of pieces this isn't anything to worry about. If you were dealing with much more complex scenes, you could instead create a mesh where each quad's UVs reference only the part of the texture it needs, then render the whole mesh with one material, but that's overkill for a small puzzle)

---
Tags: unity, image-processing
---


title: How to find a point on a plane?

text:
# Question
Title: How to find a point on a plane?
I'm using Unreal Engine 4. Currently I ray trace to a surface in game and I'm trying to find the location of the point relative to the surface instead of the world.

I have the world position of the origin of the surface and the world position of the impact point. I also have the X,Y,Z bounds of the object What I would like to find out is how to get X',Y' position of the hitpoint relative to the upper left corner. I've tried rotating the hitpoint around the origin to calculate the hitpoint based on refernce Roll, Pitch, and Yaw like so:

```
FVector RotatePointAroundPivot(FVector hitpoint, FVector pivot, FRotator angles) {
FVector dir = hitpoint - pivot;
FQuat quat(angles);

dir = quat*dir;
hitpoint = dir + pivot;

return hitpoint;
}

```

But it changes based on the rotation of the plane no matter what I do.

I also tried a very limited technique like so which just assumes it's in one of the correct orientations:

```
if (actorRotation.Yaw >= 0) {
    xpos = (actorBounds.Y - clickPosition.Y) / (actorBounds.Y * 2) * compscale.X * 1000;
    ypos = (actorBounds.Z + clickPosition.Z) / (actorBounds.Z * 2) * compscale.Y * 1000;
}
else {
    xpos = (actorBounds.Y + clickPosition.Y) / (actorBounds.Y * 2) * compscale.X * 1000;
    ypos = (actorBounds.Z + clickPosition.Z) / (actorBounds.Z * 2) * compscale.Y * 1000;
}

```

But it's flawed. All I want is to be able to use the surface like a screen.

Any help would be appreciated.

# Answer
Don't work so hard. Just take the top-left model-space vertex {-1, 0, -1} (or whatever) and project it into world-space.

Subtract. Done. :D

Alternatively, you could take the raycast one step further by un-projecting the world-space hit into the object's model-space and doing the math there. The hit would be relative to the object's model-space origin at the original, model-space scale.
> 1 votes

---
Tags: unreal-4, geometry
---


# Question
Title: Unity3D-2D: Setting Time.timeScale to 0 for a certain public prefab until positioned?
So I have a button in my game which spawns a "tower" at a given location. The tower, when spawned, acts normally and I can drag it around using my drag script.

I wonder how can I set the Time.timeScale to 0 when I first spawn the tower (*only* for that prefab) UNTILL I click again to set it's position.

# Answer
> I wonder how can I set the Time.timeScale to 0 when I first spawn the tower (only for that prefab) UNTILL I click again to set it's position.

You can't, because Time.timeScale is a static variable, so it's globally accessible and not set per-instance. However, stopping time is probably not necessary for what you want to accomplish anyway. Here are two better ways to do what you want:

1. Instantiate a TowerPlaceholder prefab instead of a Tower. A TowerPlaceholder "looks" like a Tower, but does not have the same logic and so does not need to be paused while spawning.
2. Add a flag to Tower that specifies whether it has "spawned" or not yet, and use that to control what updates are applied per frame:

```
public class Tower : MonoBehaviour
{
    bool has_spawned;

    ...
    // called once an object is placed in the world
    public void Spawn()
    {
        has_spawned = true;
    }

    void Update()
    {
        if(has_spawned)
        {
            // whatever your tower does normally
        }
        else
        {
           // whatever your tower should do when it's being dragged into position
        }
    }
}

```
> 1 votes

# Answer
At start you could disable its Rigidbody component or the script that is moving the tower. Then re-enable it when ever you want.
> 0 votes

# Answer
Set the behaviors that you want delayed as disabled in the source object. It will spawn (on first click) with logic in place, but not running. Then, when you click the second time to "plop" it, enable the script. This doesn't require polling within `Update()` and is event-like (especially when combined with `EventTrigger` components).

```
class Tower
{
  void OnPlop() //Preferably called by an EventTrigger
  {
    GetComponent<DraggableObjectBehavior>().enabled = false; //Disallow further dragging
    GetComponent<ActiveTowerBehavior>().enabled = true; //Enable "tower logic"
  }
}

```
> 0 votes

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


# Question
Title: How to optimize my random terrain generation and usage?
I'm new to Unity. I've created an algorithm to procedurally generate a circle-shaped tunnel made of primitive cubes GameObjects. The problem is that the game is very laggy and I can understand why: there are thousands of objects to render.

What I'd like to know is if there's a better approach to this. For example, would be better if instead of rendering the single cubes I create a ring custom component and use that instead?

Are there any other solutions?

I'm using Unity 5.3.4f1.

**EDIT**

Here's what I've done so far. This works the way I want but the game is really laggy because (I assume) there are lots of objects to render.

```
public class TerrainGenerator : MonoBehaviour {

private static int MAX_RING_NUMBER = 1000;

private static int TUNNEL_SLOPE = 5;

// Use this for initialization
void Start () {
    int y = 0;
    for (int z = 0; z < MAX_RING_NUMBER; z++) {

        createRing(0, y, z, 10);
        // Every TUNNEL_SLOPE cubes the tunnel goes down a block.
        if (z % TUNNEL_SLOPE == 0)
            y--;
    }
}

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

}

private void createCube(int x, int y, int z){
    GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
    cube.transform.position = new Vector3 (x, y, z);
    cube.GetComponent<Renderer>().material.color = new Color(Random.Range(0,255),Random.Range(0,255),Random.Range(0,255));
}

// Midpoint circle alghoritm.
void createRing( int x0, int y0, int z, int radius){
    int x = radius;
    int y = 0;
    int decisionOver2 = 1 - x;   // Decision criterion divided by 2 evaluated at x=r, y=0

    while( y <= x )
    {
        createCube(x + x0,  y + y0, z); // Octant 1
        createCube(y + x0,  x + y0, z); // Octant 2
        createCube(-x + x0,  y + y0, z); // Octant 4
        createCube(-y + x0,  x + y0, z); // Octant 3
        createCube(-x + x0, -y + y0, z); // Octant 5
        createCube(-y + x0, -x + y0, z); // Octant 6
        createCube(x + x0, -y + y0, z); // Octant 7
        createCube(y + x0, -x + y0, z); // Octant 8
        y++;
        if (decisionOver2<=0)
        {
            decisionOver2 += 2 * y + 1;   // Change in decision criterion for y -> y+1
        }
        else
        {
            x--;
            decisionOver2 += 2 * (y - x) + 1;   // Change for y -> y+1, x -> x-1
        }
    }
}

}

```

# Answer
Yes, performance will be much better with fewer objects. I'd recommend making one gameobject for a single ring (using the info in Philipp's excellent answer), and saving it as a prefab. Then instantiate copies of the prefab as needed.

If you want a quick and dirty way to create the prefab from a runtime object, you can use the method in Joe-2's answer here: http://answers.unity3d.com/questions/21666/creatingsaving-prefabs-during-runtime.html

Once that's done, the next significant optimization (assuming you're continually destroying and creating rings - ignore if you're not) will be to pool and reuse them instead of creating new ones all the time.
> 1 votes

# Answer
Unity allows you to generate 3d models procedurally using C# scripts.

The key for this is the component Mesh.

1. Set `mesh.vertices` to to an array of 3d coordinates in form of `Vector3`'s. These are all the corner-points of your 3d model.
2. If you want the 3d model to have textures, set `mesh.uv` to provide a list of the same number of 2d coordinates in form of `Vector2`'s to set the UV mapping (aka texture coordinates) for each vertex.
3. Set `mesh.triangles` to define which of the coordinates you provided via `vertices` are the corners of each polygon. A block of 3 integers defines one polygon.
4. After you set up everything, call `mesh.RecalculateNormals()` and `mesh.RecalculateBounds()`.
5. When you want to use a shader with a normal map, you also need to set `mesh.tangents` to a list of `Vector4`'s. Unfortunately Unity can not do that for you, and you have to calculate the tangents yourself. In my current project I am using s C# port of this function even though I got to admit that I don't fully understand it.

To get that 3d mesh into the game, create a new game object with a `MeshFilter` and a `MeshRenderer` component (and optionally a `MeshCollider` if you want collision checking) and assign your home-made mesh to the `.sharedMesh` property of the mesh filter.

All of this does of course assume that you actually need procedural generation. When the mesh always looks the same, it might be far easier to just create it with your favorite 3d modeling program and import it. Unity supports a very wide variety of 3d model formats.
> 1 votes

---
Tags: rendering, unity, performance
---


title: Camera Control Techniques in Games

text:
# Question
Title: Camera Control Techniques in Games
I am an MPhil student in Computing Science working on the problem of camera control in graphics. Though the literature of camera control dates back to the end of 1980s, the majority of them (up to my knowledge) is mainly academic and rarely used in games.

Now part of my thesis should be dedicated to camera control methods used in games. But the problem is that I have not implemented all the games in the world, so I can't speak about them. But I suppose there are some references that game developers usually use.

Can anybody help me with this? Even if it is from your own experience rather than a book.

# Answer
I'm going to go ahead and suggest Real-time Cameras. It appears to cover the topics you require.

Honestly, though, you should go code some 3D cameras and figure out what works and doesn't :) That's the fun part, anyway.
> 6 votes

# Answer
While a 2D camera is quite simple to implement, a camera in 3D can become really complicated quite fast.

First person perspective or a fixed camera like in a RTS are probably the easiest ones, while a good third-person camera can be a huge challenge. I recently saw a presentation of a game-camera research project which looked really good: Visibility Transition Planning for Real-Time Camera Control (you'll find a link to a PDF at the bottom of the page or check out this video to see it in action).
> 4 votes

# Answer
*NB: I'm assuming here you're talking about cameras in third-person games such as Tomb Raider. Even then, some games may have sections, for instance when in cover, when a completely separate camera system is used to the main walking-around sections of the game.*

This is a very complex area to get right. The simple naive approach is to lock the camera to a position above and behind the player, and if raycasts intersect level terrain then to move the camera back towards the player until clear of intersections.

This quickly gets complicated as you add in smoothing, lookahead prediction, more ray casts to steer clear of trouble, gimbal lock, etc. And despite all that you'll still find the camera staring at the walls every now and again.

It might be easier to get a list of games where the camera works well, and try to figure out what they're doing special.
> 2 votes

# Answer
If you're looking for something "sourceable", try looking through the GDC Vault archives. You have access to slides from talks. Doing a search for "camera" lead to some results that might be useful. http://gdcvault.com/free
> 2 votes

# Answer
There is a great section about all types of game camera's documented in Scott Roger's Level Up book. This really helped me to understand them: https://books.google.com.au/books/about/Level\_Up.html?id=8w\_ETFmHrewC&redir\_esc=y
> 0 votes

---
Tags: camera, control
---


title: How to combine depth and stencil tests?

text:
# Question
Title: How to combine depth and stencil tests?
I have a continuous height-mapped mesh to represent landscape. I use the stencil test to create holes in the mesh. I draw holes to the stencil buffer and then use it to discard mesh fragments. Everything works fine except that my holes are visible through the mesh even if they are occluded by higher ground.

Is there any way to apply depth testing to a hole, keeping my mesh drawn in a single call to glDrawElements?

# Answer
The easiest way to do this is to render the holes as geometry first (a simple quad is ok), with color writes off and depth writes on. This allows terrain in front of the hole to draw over it and terrain behind the hole will fail the depth test. That leaves a \[clear color\] hole in the terrain that you can render through.

This is often done to clip the water plane out of the interior of a boat's hull.
> 2 votes

# Answer
I would advise you to consider using glStencilOp function.

In particular, you can use different operation if the stencil test passes but not the depth test.

See that reference page for additional details.

Hope it helps.
> 0 votes

---
Tags: opengl, depth-buffer, stencil
---


# Question
Title: How to use collision masks and overlap_area in pygame?
So, I've been prototyping a game, and I've been using sprite collision, and it's not cutting it any more. I read up on the documentation about masks and overlap area: https://www.pygame.org/docs/ref/mask.html#pygame.mask.Mask.overlap\_area

How exactly do I use this? The documentation says "This can be used to see in which direction things collide, or to see how much the two masks collide. An approximate collision normal can be found by calculating the gradient of the overlap area through the finite difference."

I don't quite follow this description. How can I tell the direction of the collision? What does the return value actually contain? How would I implement this collision for two Pygame Sprites with images and transparency?

Is there a more in-depth explanation (preferably with sample code) anywhere? I can't find anything more detailed than the documentation.

# Answer
> `overlap_area()`
> Returns the number of overlapping 'pixels'.

Let's see an example with a sprite collision of 2 sprites 3x3 (black and white)

**Sprites colling on pixel (3,3) from black and (1,1) from white**

Now, how pygame docs suggests, lets calculate the gradient of the overlap area with

```
dx = Mask.overlap_area(othermask,(x+1,y)) - Mask.overlap_area(othermask,(x-1,y))
dy = Mask.overlap_area(othermask,(x,y+1)) - Mask.overlap_area(othermask,(x,y-1))

```

One by one:
`Mask.overlap_area(othermask,(x+1,y))` = 0
`Mask.overlap_area(othermask,(x-1,y))` = 2
`Mask.overlap_area(othermask,(x,y+1))` = 2
`Mask.overlap_area(othermask,(x,y-1))` = 0

`dx` = 0 - 2 = -2
`dy` = 2 - 0 = 2
(-2,2) indicates that the collision came from left (`dx` \< 0) and up (`dy` \> 0) of `othermask`

However this is not a very good way to determine the direction of collision. Pygame implements masks using Bitmask 1.7 (a pixel-perfect collision detection library) which, although very fast, may be redundant if your sprites have a common form (and you can detect the direction of the collision simply taking the difference of the coordinates)
> 1 votes

---
Tags: collision-detection, sprites, collision-resolution, pygame
---


# Question
Title: LibGDX--constant high score in top corner
I'm currently programming a game using LibGDX and box2D. I have a sprite (player) that moves up the screen, kind of like doodle jump.

I'd like to have my camera to be centered around the player at all times--the sprite will be in the center of my screen as they move up, or as they fall down.

I'd also like to have a high score panel that is always at the top left corner of the screen.

As of now, I have this done, to an extent. As long as the player doesn't move to far up the screen at a time, it will remain centered, and the high score will generally be in the top. Sometimes it'll move off the screen, but it will come back as the player falls down.

Most of my confusion lies from the LibGDX coordinate system, so if you could explain that, that would enhance my understanding of the problem.

Here is the code I have:

```
//Access the world's reference to Player, and update the position of it's sprite with respect to the body
  world.getPlayer().updatePosition();
  world.getBlock().updatePosition();

  //Have the camera follow the player, but only in the y position
  batch.setProjectionMatrix(camera.combined);
  camera.position.set(camera.position.x, world.getPlayerSprite().getY() - 75, 0);
  camera.update();

  //Begin batching sprites here. This will include blocks and the player
  batch.begin();

  debugMatrix = batch.getProjectionMatrix().cpy().scale(100f,
        100f, 0);

  //Render the Player sprite here
  batch.draw(world.getPlayerSprite(), world.getPlayerSprite().getX(), world.getPlayerSprite().getY(),world.getPlayerSprite().getOriginX(),
        world.getPlayerSprite().getOriginY(),
        world.getPlayerSprite().getWidth(),world.getPlayerSprite().getHeight(),world.getPlayerSprite().getScaleX(),world.getPlayerSprite().
                getScaleY(),world.getPlayerSprite().getRotation());
  batch.draw(world.getPlatformSprite(), world.getPlatformSprite().getX(),
          world.getPlatformSprite().getY(),world.getPlatformSprite().getOriginX(),
          world.getPlatformSprite().getOriginY(),world.getPlatformSprite().getWidth(),
          world.getPlatformSprite().getHeight(),world.getPlatformSprite().getScaleX(),
          world.getPlatformSprite().getScaleY(),world.getPlatformSprite().getRotation());
  batch.draw(world.getBlockSprite(), world.getBlockSprite().getX(),
          world.getBlockSprite().getY(),world.getBlockSprite().getOriginX(),
          world.getBlockSprite().getOriginY(),world.getBlockSprite().getWidth(),
          world.getBlockSprite().getHeight(),world.getPlatformSprite().getScaleX(),
          world.getBlockSprite().getScaleY(),world.getBlockSprite().getRotation());

  Gdx.app.log("Position", "" + camera.position.y + " " + world.getPlayerSprite().getY() + " " + (camera.position.y - 275));
  font.draw(batch, "Score:" + (int)Math.ceil(22-world.getPlayerBody().getPosition().y), 0, camera.position.y - 275);

  batch.end();

```

# Answer
You should not use the same `SpriteBatch` for drawing your game elements (players, paltforms etc.) as for drawing your HUD.

What are you are doing here is applying the camera matrix to your sprite batch, which means that everything rendered using this sprite batch will be affected by the camera.

```
batch.setProjectionMatrix(camera.combined);

```

What you can do:

* Use another sprite batch for your HUD (and do not apply the camera projection matrix on this one)
* Use Scene2D for your HUD (that's what i would do)

I would not use Scene2D for gameplay rendering but i think that using it for HUD is a very elegant solution. It will help you separate your gameplay logic from your HUD logic and will handle really nice things for you like screen resizing etc.
> 1 votes

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


# Question
Title: Gameobject not destroyed OnCollisionEnter
I have this GameObject with the tag coin I am trying to destroy when the player collides with it using this code located in a player script attached to the player

```
    public void OnCollisionEnter(Collision col){
        var hit = col.gameObject;
        if(hit.tag == "Coin"){
            Destroy(hit.gameObject);
        }
    }

```

However upon collision nothing is happening

# Answer
> 2 votes
First you must check:

1. **collider** =\> IsTrigger =\>false
2. **Rigidbody** =\> IsKinematic =\>false
3. you mentioned 3d so check their gameObjects **z position**
4. finally you check your **tag name** into corresponding to their gameobject

# Answer
> 1 votes
I figured out the issue the problem was in order to use `OnCollisionEnter` at least one of the objects must have a `rigidbody` component attached

# Answer
> 0 votes
Few things you have to keep in mind.

* Rigidbody must attached to either `Gameobject`
* Make sure that your script attached to the `GameObject` is **not** `isTrigger` checked.
* Verify if the `OnCollisionEnter` is being executed, by breakpoints or logs.
* Make sure the tag of other `GameObject` (col.gameObject)
* And you don't need to destroy `hit.gameObject` as `hit` is already a `GameObject`.

You can do it like

```
void OnCollisionEnter(Collision col){

    var hit = col.gameObject;

    Debug.Log("In collision enter");

    if(hit.tag == "Coin"){
        Debug.Log("In destroy check");
        Destroy(hit);
    }
}

```

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


# Question
Title: Making the player Jump in like a Upper - Right manner in Unity
Ok so I'm new to Unity and I am trying to make this simple ball game. Now in a situation I want the ball to jump in a diagonal manner (i.e W + D ). Script that I have makes the ball jump only up and not in like a upper right direction. Can some one please suggest some change in the following script:

```
using UnityEngine;
using System.Collections;

public class BasicMovement : MonoBehaviour {

    public float rotation_Speed = 100;
    public float jump_Height = 1;

    private bool Falling = false;

    void Update ()
    {
        // FOR ROTATION
        float Rotation = Input.GetAxis ("Horizontal") * rotation_Speed * Time.deltaTime; // USING FORMULA DISTANCE = SPEED * TIME
        GetComponent<Rigidbody> ().AddRelativeTorque (Vector3.back * Rotation);  // APPLYING TORQUE TO THE BALL

        if (Input.GetKeyDown (KeyCode.W) && Falling == false )
        {
                GetComponent<Rigidbody> ().velocity = new Vector3 (1, 10, 0) * jump_Height;
                Falling = true;
        }
    }

    void OnCollisionStay()
    {
        Falling = false;
    }
}

```

# Answer
Couple of things you are doing in more expensive way actually. Well, you should just apply force on `Rigidbody` instead of setting velocity explicitly.

You can improve your script as,

```
using UnityEngine;
using System.Collections;

public class BasicMovement : MonoBehaviour {

    public float rotation_Speed = 100;
    public float jump_Height = 1;

    private bool Falling = false;

    Rigidbody _rb;
    float _jumpXRatio = 1;
    float _jumpYRatio = 10;

    void Start()
    {
        _rb = GetComponent<Rigidbody> (); // it will keep reference
    }

    void Update ()
    {
        // FOR ROTATION
        float Rotation = Input.GetAxis ("Horizontal") * rotation_Speed * Time.deltaTime; // USING FORMULA DISTANCE = SPEED * TIME
        _rb.AddRelativeTorque (Vector3.back * Rotation);  // APPLYING TORQUE TO THE BALL

        if (Input.GetKeyDown (KeyCode.W) && Falling == false )
        {
                // Now set ratios and axes according to your needs
                _rb.AddForce (new Vector3 (_jumpXRatio, _jumpYRatio, 0) * jump_Height);
                Falling = true;
        }
    }

    void OnCollisionStay()
    {
        Falling = false;
    }
}

```
> 0 votes

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


# Question
Title: How can I reduce the draw calls in a split screen game?
I am working on a split screen game with one camera per player. It appears that the number of draw calls is multiplied by the number of cameras I have, which makes perfect sense. More cameras means more drawing means more draw calls.

So for every player, there is effectively a new instance of the game that must be rendered.

What do developers do when presented this problem? Do they scale down their game? Or are there practices I am unaware of to where this should not be an issue?

(I am using Unity, if it is relevant.)

How can I improve rendering performance in a split screen game?

Example:

# Answer
> 5 votes
> What do developers do when presented this problem? Do they scale down their game?

Yes, it's not unusual for a game running splitscreen to use simpler LOD (level-of-detail) versions of some assets & effects, or even omit certain decorative props/non-essential lights to keep the game running smoothly - particularly if the game was made to push the platform's rendering capabilities as far as they'd go in single-player mode. Sometimes the only way to make multiple views fit in your time budget is to leave some things out.

Usually the developers will do everything they can to **optimize the rendering in each view** to stave off cutting back on detail (and this helps both single-player and split screen efficiency). If you can combine 5 draw calls in single player (saving 4), then you've saved 8 in 2-player splitscreen, 16 in 4-player, etc. Every little saving for one view stacks up, so this is probably the first place you should look for efficiency.

Unfortunately there's relatively little heavy-lifting work that can be shared when rendering two completely separate views of the scene. We could potentially have a completely different subset of the geometry, textures, lights, and effects visible in each view.

One thing to consider is that in splitscreen, while the number of passes you do over your objects may multiply, the **total pixel count you need to fill remains constant. That means the work done by screenspace effects scales somewhat more gradually** as you increase the number of views. You may find deferred rendering helps you take advantage of this (especially tiled rendering approaches, if your tiles align with the splitscreen bounds) by partly decoupling your lighting complexity from the number of distinct views shown.

---
Tags: unity, rendering, performance, batching
---