# Question
Title: HLSL Shader Optimilation with MAD(m,a,d)
I understand that the expression `x = m*a+d` is most efficiently written as `x = mad(m,a,d)` because at the assembly level only one instruction is needed rather than a multiply and add separately. My question regards optimally writing this expression: `x += m*a`. **Should this be written as `x = mad(m,a,x)` or `x += m*a`?** The difference is too subtle to profile but I'm wondering if anyone can see the difference at the assembly level. (I don't know how to view the assembly code.)

# Answer
It will probably be exactly the same output code, the HLSL compilers are now intelligent enough to optimize those operations.

Plus if you think about the micro code, it will probably look like :

```
mad regx, regm, rega, regx

```

with regx regm and rega being the respective registers of m a and x
> 1 votes

---
Tags: directx11, hlsl
---


title: Efficient UI for RTS units

text:
# Question
Title: Efficient UI for RTS units
I was wondering how I should approach the runtime changes on the game UI when selecting different types of units in a RTS.

For example, in Starcraft, each unit type has its own portrait, attributes, buffs and command cards displayed in the UI. Selecting another unit will update all of these.

I can see two possible solutions:

1. Each unit type has its own UI panel created (in memory), and selecting another unit disables the current UI panel and enables the new one.
2. There is only one UI panel, and selecting a unit fills the portrait, attributes, command cards, etc. dynamically.

Both solutions seem inefficient. The first may consume too much memory, and the second makes no caching at all. Maybe the way to go would be something in-between, or completely different.

I'm working with Unity, but I think the discussion should stay pretty high level.

# Answer
Do not prematurely optimize: it will introduce bugs for sure or make code hard to maintain which will result in more bugs anyway.

And because you are working in Unity all graphics caching is efficiently handled by the engine(yes, you can hint the engine by referencing required data in scripts)

The whole problem should be taken in the most logical approach which you see as the most flexible one. Personally, I would select option 2 as it keeps state clean on every reselection event and is more data driven. While option 1 will introduce clutter in hierarchy and possible problems like in case two or more will stay(due to exception preventing the proper flow of switching). Actually everything which doesn't clean its state asks for trouble.
> 2 votes

# Answer
Option 2 is most common method. If you concern about the update efficiency, you could do more property compare in the ui update function, and only update properties really changes.

```
// a single state cache for current ui sheet
preState = stateCache[stateKey];
// or you can retrieve from ui element to save memory and keep it simple
// preState = uiElement.getValue();
if (preState != unit.state) {
   uiElement.apply(unit.state);
}

```

In most case, most part of ui stay unchanged, as selecting between similar units. Finally, the selecting is not a frequent action as per-frame action, it will not be the bottleneck usually.
> 1 votes

---
Tags: rts, memory, gui
---


# Question
Title: Updating children nodes in a game engine
I am writing my own small game engine (thin layer based on SDL2) in C++. My base class is Node (contains information on an entity's position, scale, rotation, etc.), And I've got two special subclasses, Layer and Scene.

```
Node
|_SpriteNode
|_RectNode
|_...
|_Layer
  |_Scene

```

A layer can have `Node` children. Each time the loop runs, I call the `update(int timeInterval)` method on the scene being rendered, and the method loops through the `vector<Node*>` field containing my children. Layers propagate that call to their children, etc.

This works well until I start adding/removing children during the update. My first implementation of `Layer` had those two methods:

```
void Layer::addChild(Node* child)
{
    if(!child) return;
    _children.push_back(child);
}

void Layer::removeChild(Node* child)
{
    _children.erase(child)
}

```

This is, of course, stupid, since removing a Node from the vector would cause a null pointer error when the update loop ( `for (auto child: _chidren)` ). Using an iterator instead could fix this, but when a Node calls `_parent.removeChild(this)`, it does not know about the iterator being used for that frame.

The solution I use at the moment is having an addition and a deletion buffer in the Layer, to which new and deleted nodes are added during the frame update. Once the frame has been rendered, the Layer performs the actual insertions and deletions from its children array. It works, and I've made a Game Jam game with this, but is seems more than sketchy to me.

I have looked through Cocos2D-X source code, and they use a simple `push_back()` or `erase()` call, which makes me think I'm missing a bigger point, or some trick that prevents the iterator issue. Is there something obvious (or not) that I missed?

Sorry if the question is dumb or missing a point. I hope I documented everything enough :)

# Answer
> 1 votes
The simplest thing to do is make a copy of the `Node *` container before iterating over it.

```
void Layer::update() {
    auto children = _children;
    for(auto child : children) {
        child->update();
    }
}

```

If you want to avoid this copy, you can defer the additions and removals until after the update loop finishes.

```
std::vector<Node *> _additions;
std::vector<Node *> _removals;

void Layer::addChild(Node *child) {
    _additions.push_back(child);
}

void Layer::removeChild(Node *child) {
    _removals.push_back(child);
}

void Layer::update() {
    for(auto child : _children) {
        child->update();
    }

    for(auto child : _additions) {
        _children.push_back(child);
    }
    _additions.clear();

    for(auto child : _removals) {
        _children.erase(child);
    }
    _removals.clear();
}

```

---

EDIT: It seems I didn't read your question thoroughly enough to realize that you've already tried the deferral method. Keep doing that.

# Answer
> 0 votes
As long you are not using threads/multi-core you have nothing to worry about - your code won't be executed "in parallel".

If you do use it, one solution is to implement child's queues for insertion and deletion, and to process them in the same thread - before or after your looping through children.

---
Tags: c++, game-loop, scene-graph
---


# Question
Title: SDL2: Unable to get center of screen when drawing more than one texture?
so I've been trying for the last four hours to get this to work and although I can get to the center of the screen when printing one texture using:

```
TextureManager::getInstance()->drawTexture("block_brown",
    SDL_GetWindowSurface(Game::getInstance()->getPrimaryWindow())->w / 2 - 101 / 2,
    SDL_GetWindowSurface(Game::getInstance()->getPrimaryWindow())->h / 2 - 171 /2,
    101,
    171,
    Game::getInstance()->getPrimaryRenderer(),
    SDL_FLIP_NONE);

```

I get the following result:

I can keep the center of up to two textures in a row and after that it gets out of hand and I completely lose it. I'm using the following for the two:

```
for (int i = 0; i < 2; i++) {
    for int j = 0; j < 2; i++) {
        TextureManager::getInstance()->drawTexture("block_brown",
            SDL_GetWindowSurface(Game::getInstance()->getPrimaryWindow())->w / 2 - i * 101,
            SDL_GetWindowSurface(Game::getInstance()->getPrimaryWindow())->h / 2 - 171 / 2,
            101,
            171,
            Game::getInstance()->getPrimaryRenderer(),
            SDL_FLIP_NONE);

```

which produces the following result:

As you can see, it looks to be in the center of the window, but if I try to add more than two in a row or more than one in a column, I then have to start fighting it to keep it in the center.

So my question is, how would one manage to get the textures to stay central, no matter how many I add?

EDIT:

This is the final result I'm ultimately looking for:

When I start trying to add layers I then have to start fighting it again to keep it central?

This the result I'm having right now:

The more I think about this, the more I think I'm going completely the wrong way and doing it completely wrong.

# Answer
There's nothing to do with SDL in this; it's just a maths question.

General strategy for centering a group of objects: Get the full size of the group and center that, instead of trying to position each element separately.

Off the top of my head, here's some extremely simple pseudocode for this specific situation:

```
// First, a few constants, giving semantic names in order to remove some
// repeated magic numbers in the code.
const int c_imageWidth = 101;
const int c_imageHeight = 171;

// Set these to whatever values you want, to control how many rows and
// columns get drawn.
int rows = <number of rows you want>;
int columns = <number of columns you want>;

// Now, let's figure out how large the complete set of images are.
int fullWidthOfARowOfImages = columns * c_imageWidth;
int fullHeightOfAColumnOfImages = rows * c_imageHeight;

// And to make the centering maths easier to read, let's define a
// few named variables telling us the half-dimensions of the full set.
int rowHalfWidth = fullWidthOfARowOfImages / 2;
int columnHalfHeight = fullHeightOfAColumnOfImages / 2;

// find the center of the screen, assuming that the coordinate system
// used by our rendering is orthographic, and precisely matches the
// window's own coordinate system.
int screenCenterX = Game::getInstance()->getPrimaryWindow())->w / 2;
int screenCenterY = Game::getInstance()->getPrimaryWindow())->h / 2;

// now let's define a centered 'origin' for where we're going to start
// drawing our rows and columns of images, such that the whole group will
// end up centered.
int rowOriginX = screenCenterX - rowHalfWidth;
int rowOriginY = screenCenterY - rowHalfHeight;

for ( int row = 0; row < rows; row++ )
{
    for ( int column = 0; column < columns; column++ )
    {
        TextureManager::getInstance()->drawTexture("block_brown",
            rowOriginX + (column * c_imageWidth),
            rowOriginY + (row * c_imageHeight),
            c_imageWidth,
            c_imageHeight,
            Game::getInstance()->getPrimaryRenderer(),
            SDL_FLIP_NONE);
    }
}

```
> 1 votes

---
Tags: c++, sdl2
---


# Question
Title: Move 2d tank with independently controlled treads
I have made a tank object that knows its position, speed, rotation, and a double value ranging from 1.0 to -1.0 for each tread. I want it to move base on those values. For example, if the value for the left tread is 1.0 and the value for the right tread is 0.5 the tank should follow a clockwise circular path. However, the closest I have come is when the left tread turns forward (positive) and/or the right tread turns backward (negative), the tank spins CCW and moves down the screen, while the reverse is true if the left tread turns backward and/or the right tread turns forward.

This is my code for moving the tank, where `lts` is the left tread speed and `rts` is the right tread speed:

```
rotation += speed * (rts / 12);
rotation -= speed * (lts / 12);
location.x += speed * (Math.cos(rts / 12) * 14.5);
location.x -= speed * (Math.cos(lts / 12) * 14.5);
location.y -= speed * (Math.sin(rts / 12) * 14.5);
location.y += speed * (Math.sin(lts / 12) * 14.5);

```

# Answer
> 2 votes
The equations of motion for a *differential drive* machine are as follows, where `x`, `y`, `θ`, and `l` are the 2D position, orientation, and drive shaft length (distance between wheels) respectively:

While a tank is not quite an ideal differential drive machine, this should be a sufficient approximation.

Translating this into code using a simple Euler integration:

```
// "speed" must be expressed in units per second
float velocityR = rts * speed;
float velocityL = lts * speed;

// "width" must be expressed in units
rotation += (velocityR - velocityL) / width * dt;
location.x += 0.5 * (velocityR + velocityL) * Math.cos(rotation) * dt;
location.y -= 0.5 * (velocityR + velocityL) * Math.sin(rotation) * dt;'

```

To make this work without a variable time step, you can keep your current `speed` value and remove the multiplication by `dt` (delta time). However, I strongly suggest that you move to a time step that is refresh-rate-agnostic.

---
Tags: 2d, movement
---


# Question
Title: How to change an int value in the Unity editor
The player of my game can collect logs and can use them for hold on the fires. Each fire has its own status. So one is off and the other one is for 50% on.

I created a `public int` inside my script that is linked to my gameObject. Because it is public, I can change the value also in the Unity editor. See image:

The int is linked to a `int` parameter of "Intensity". And use this as follow:

```
public Animator anim;
public int campfireStatus;
public float timer;
public float beforeDecrease; // timer for campfires
bool inTrigger = false;

// Use this for initialization
void Start () {

    anim = GetComponent<Animator>();

}

void OnTriggerEnter2D(Collider2D other) {
    if (other.gameObject.tag=="Player"){
        inTrigger = true;
    }
}

void OnTriggerExit2D(Collider2D other) {
    if (other.gameObject.tag=="Player"){
        inTrigger = false;
    }
}

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

    anim.SetInteger("Intensity", campfireStatus);
    //Debug.Log (campfireStatus);

    if(inTrigger && Input.GetKeyDown(KeyCode.E)) {
        if (WoodBehaviour.count > 0) {
            campfireStatus++;
        }
    }

    timer+= Time.deltaTime;

    if (timer > beforeDecrease) {

        timer = 0;

        if (campfireStatus !=0){
            campfireStatus--;
            Debug.Log ("Decrease");
        }

    }

}

```

But the added value inside the Unity editor will not be use by the script. It will start from the default state, as you can see here:

Each transition, like the one is selected, will have the condition: `intensity` is equals to 1 till 4.

So I look for a solution, so that I am be able to change which start animation should fired for that object, by changing the Campfire Status inside the Unity editor with the values of 1 till 4.

Look out for some advice!

# Answer
> 1 votes
According to what evaluated in the comment section, your problem was that you had to set transition conditions to be greater then some\_value instead of equal.

---
Tags: unity, 2d
---


# Question
Title: Handling collision with LWJGL rectangles
I'm testing collision with other rectangles so I can implement it into my current project. The problem is the rectangle starts at the right x and y, but I'm not sure where exactly they are. I'm pretty sure they're starting from the x and y point and the height is going either up and down. My current ortho makes the y axis start from the bottom of the screen but I'm not sure how their rectangle calculates. How can I improve this class so for each side the bottom rectangle touches, it turns a certain color to identify collision.

```
public class a {

    static int playerX = 400;
    static int playerY = 400;

    static int enemyX = 100;
    static int enemyY = 100;

    public static void main(String[] args) {
        try {
            Display.setDisplayMode(new DisplayMode(640, 480));
            Display.setTitle("collision");
            Display.create();
        } catch (LWJGLException e) {
            e.printStackTrace();
            Display.destroy();
            System.exit(1);
        }

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, 640, 0, 480, 1, -1);
        glMatrixMode(GL_MODELVIEW);

        Rectangle rl = new Rectangle(playerX, playerY, 10, 20);

        Rectangle r2 = new Rectangle(enemyX, enemyY, 200, 10);

        float c2 = 0;//color

        while (!Display.isCloseRequested()) {
            glClear(GL_COLOR_BUFFER_BIT);
            rl.setX(playerX);
            rl.setY(playerY);

            r2.setX(enemyX);
            r2.setY(enemyY);

            if(rl.intersects(r2))
            {
                c2 = 1f;
            } else if(!rl.intersects(r2))
            {
                c2 = 0f;
            }

            if(Keyboard.isKeyDown(Keyboard.KEY_A))
                playerX -= 1;
            if(Keyboard.isKeyDown(Keyboard.KEY_D))
                playerX += 1;
            if(Keyboard.isKeyDown(Keyboard.KEY_W))
                playerY += 1;
            if(Keyboard.isKeyDown(Keyboard.KEY_S))
                playerY -= 1;

            System.out.println(playerY-100);

            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

            glColor3f(0, 1, 0);

            //PLAYER

            //l
            glBegin(GL_QUADS);
            glVertex2f(playerX, playerY     -10      );
            glVertex2f(playerX + 10, playerY    -10  );
            glVertex2f(playerX + 10, playerY - 100    );
            glVertex2f(playerX, playerY      - 100    );
            glEnd();
            //r
            glBegin(GL_QUADS);
            glVertex2f(playerX + 100, playerY   -10           );
            glVertex2f(playerX + 110, playerY        -10      );
            glVertex2f(playerX + 110, playerY - 100            );
            glVertex2f(playerX + 100, playerY      - 100       );
            glEnd();
            //top
            glBegin(GL_QUADS);
            glVertex2f(playerX + 10, playerY     -9               );
            glVertex2f(playerX + 100, playerY       -9       );
            glVertex2f(playerX + 100, playerY - 20          );
            glVertex2f(playerX + 10, playerY      - 20           );
            glEnd();
            //bot
            glBegin(GL_QUADS);
            glVertex2f(playerX + 10, playerY          -90          );
            glVertex2f(playerX + 100, playerY    -90          );
            glVertex2f(playerX + 100, playerY - 101        );
            glVertex2f(playerX + 10, playerY      - 101         );
            glEnd();

            glColor3f(c2, 1, 0);
            //ENEMY
            glBegin(GL_QUADS);
            glVertex2f(enemyX, enemyY);
            glVertex2f(enemyX + 200, enemyY);
            glVertex2f(enemyX + 200, enemyY - 10);
            glVertex2f(enemyX, enemyY - 10);
            glEnd();

            Display.update();
            Display.sync(60);
        }
        Display.destroy();
        System.exit(0);
    }

}

```

I just made it so OpenGL set its position to the rectangle instead of the rectangle to OpenGL.

# Answer
If you say that y starts at bottom, I'm going to assume that +y moves upward on the screen. If this is the case, the rectangle would build "upward". So x,y of the rectangle would be in the bottom left corner, and the bounds of the rectangle would extend upward and to the right. `x + width; y + height`

To find the location of each corner, just need to add the width and height to the player's location. To find the bottom left corner, you just need to check the against playerX/playerY. To find the opposite end, you would do `playerX + r1.width; playerY + r1.height;`

To do collision detection, compare each corner of both rectangles to see if it's less-than or greater-than the edge to see if they intersect. For example, to check the left edge you would check if the enemy `enemyX+r2.width` coordinate is bigger than the `playerX` and less than `playerX + rectangleWidth` for each corner of the other rectangle. You'll want to implement the loop such that you're not checking each pair twice, and even don't compare rectangles who are too far away from each other. This method would break if the rectangles have different sizes, a fix may be by checking the mid point between two edges.
> 1 votes

---
Tags: opengl, java, collision-detection, lwjgl
---


# Question
Title: In Unity, how do I make the camera follow a character?
When my character moves, I want the camera to follow them, such that the character always stays in the middle of the view. How do I do that in Unity?

---

Here's my code right now:

```
using UnityEngine;
using System.Collections;

public class CharacterControll : MonoBehaviour {

    public float speed = 3f;

    private Animator animator;
    private Vector2 screenSW;
    private Vector2 screenNE;
    private float wrapPadding = 1f;
    public GameObject gameObject;

    // Use this for initialization
    void Start () {
        animator = this.GetComponent<Animator> ();

        screenSW = Camera.main.ScreenToWorldPoint (new Vector2(0, 0));
        screenNE = Camera.main.ScreenToWorldPoint (new Vector2(Screen.width, Screen.height));
    }

    // Update is called once per frame
    void Update () {
        float horizontalInput = Input.GetAxis ("Horizontal");
        float verticalInput = Input.GetAxis ("Vertical");

        if (horizontalInput == 0) {
            animator.speed = 0;
            animator.SetInteger("Direction", 0);
        }

        else if (horizontalInput < 0) {
            animator.speed = 3;
            animator.SetInteger("Direction", 1);
        }

        transform.Translate (Vector2.right * horizontalInput * Time.deltaTime * speed);
        transform.Translate (Vector2.up * verticalInput * Time.deltaTime * speed);

        if (transform.localPosition.x < screenSW.x - wrapPadding) {
            transform.localPosition = new Vector2(screenNE.x, transform.localPosition.y);
        }

        else if (transform.localPosition.x > screenNE.x + wrapPadding) {
            transform.localPosition = new Vector2(screenSW.x, transform.localPosition.y);
        }

    }

    void OnTriggerEnter2d(Collider2D other){

    }
}

```

# Answer
Just make the main camera a child of the player object in the hierarchy, then move it to where you want it in the scene view with the translate/rotate tools. Don't make it overly complicated with code.

Or apply the same control scripts and colliders to the camera as to the player object.
> 1 votes

# Answer
Ok, so I'll tell you what I came up with in my project.

attach a script to your Main camera object, declare a player like

```
public GameObject player;

```

initialize it in the `Start` function (be sure you set your character tag to "Player" in this case) like

```
player = GameObject.FindGameObjectWithTag ("Player");

```

and then in the `Update` (assuming your character is moving in the xy plane) just put

```
if(player != null)
        {
            transform.position = new Vector3 (player.transform.position.x, player.transform.position.y, -10);
        }
else
{
    Debug.Log("Player not set correctly. Please check if tag is set correctly.");
}

```

Adjust the Z position to where you want the camera to be away from player (see if you need positive or negative values)
> 0 votes

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


title: Why is rotation not applied instantly?

text:
# Question
Title: Why is rotation not applied instantly?
I am working though the Space Shoot tutorial and I have just applied tilt to the player object. One of the things that I have noticed is that the tilt is not applied instantly but instead the player object can be seen to rotate to the new rotation position. Why does the rotation appear to applied over time (1/2 second maybe) instead of instantly?

My expectation would be that when I set an attribute the value is changed instantly, not over time. I understand that instantly snapping to a position might not be very desirable, but I can't find anything in the unity documentation that explains the behavior I am observing. My desire is to understand this behavior so that I can account for it and take advantage of it, so please provide a link to any supporting documentaion.

Sample code that exhibits this behavior.

```
using UnityEngine;
using System.Collections;

public class PlayerControler : MonoBehaviour {
    void FixedUpdate(){
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        rigidbody.velocity = new Vector3 (moveHorizontal, 0.0f, moveVertical);

        rigidbody.rotation = Quaternion.Euler (0, 0, rigidbody.velocity.x);
    }
}

```

# Answer
Try: `Debug.Log(moveHorizontal)`, and that sheds a lot of light on what's happening. If you're using a keyboard, what happens when you press `d`, is not that moveHorizontal snaps from 0.0f to 1.0f. It gradually increases. It goes from `0.0f`, to `0.1f`, then maybe `0.3f`, and so-forth, until it eventually becomes `1.0f`. The final value of it being fully pressed.

What this means, is that your **velocity** is gradually changing. Your rotation is based on your velocity, so that means that your rotation changes gradually, rather than instantly.

If you want it to snap to a rotation and velocity, rather than move gradually, try:

```
move = move > 0.0f ? 1.0f : (move < 0.0f ? -1.0f : 0.0f);
/* equivilant to:
 * if (move > 0.0f) move = 1.0f;
 * else if (move < 0.0f) move = -1.0f;
 */

```

To cite a piece of documentation: The Unity input manager, scroll down to the `Properties` and `Function` table. You can see in that table:

```
Negative Button     The button used to push the axis in the negative direction.
Positive Button     The button used to push the axis in the positive direction.

```

As stated there, pressing a key "pushes" that axis in a direction. It doesn't set an axis, it gradually changes it. This results in something similar to what it would be on a joystick. In order to put a joystick to the right, you have to push it all the way there. On the keyboard, they emulate that pushing action. Resulting in something consistent across input systems.
> 2 votes

---
Tags: unity, rotation
---


title: Unity C# 2D Platformer Enemy Patrolling

text:
# Question
Title: Unity C# 2D Platformer Enemy Patrolling
I'm setting up a basic mario-like 2D platformer and I'm trying to give 'enemies' a patrolling path on a platform. (just like the turtles in Super Mario Bros). All they do is patrol from left to right and back. \<---\>

Currently my game object is walking to left and right in the middle of my scene. Despite me positioning my game object as far left as I can, at first it walks to the center of the scene and continues acting out his patrol in the center of my scene.

What I can't seem to figure out is adjusting the position where he patrols. I don't want him to patrol in the center of the scene.

I think I should use the `originalX` position in the `Update` function but I'm not sure how (I could be wrong)?

This is the script that is linked to my enemy gameobject.

```
using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {
    public float walkSpeed = 1.0f;      // Walkspeed
    public float wallLeft = 0.0f;       // Define wallLeft
    public float wallRight = 5.0f;      // Define wallRight
    float walkingDirection = 1.0f;
    Vector2 walkAmount;
    float originalX; // Original float value

    void Start () {
        this.originalX = this.transform.position.x;
    }

    // Update is called once per frame
    void Update () {
        walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;
        if (walkingDirection > 0.0f && transform.position.x >= wallRight) {
            walkingDirection = -1.0f;
        } else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) {
            walkingDirection = 1.0f;
        }
        transform.Translate(walkAmount);
    }
}

```

# Answer
It looks like `wallLeft` and `wallRight` are absolute positions--they aren't relative to your AI's initial position. So the AI starts wherever, and then walks towards it's absolutely positioned bounds, and then patrols in there.

I would try something like this:

```
void Start () {
    wallLeft = transform.position.x - 2.5f;
    wallRight = transform.position.x + 2.5f;
}

```
> 0 votes

# Answer
Try this:

```
void Update () {
    walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;
    if (walkingDirection > 0.0f && transform.position.x >= originalX + wallRight) {
    walkingDirection = -1.0f;
    } else if (walkingDirection < 0.0f && transform.position.x <= originalX - wallLeft) {
    walkingDirection = 1.0f;
    }
    transform.Translate(walkAmount);
}

```

It seems forgot to use the original position of the character, when checking for patrolling limits.
> 0 votes

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


# Question
Title: Creating procedural mesh with orientation
I am working on creating a procedural cylinder mesh with Unity C#. I have everything working but there is one thing I would like to implement in my existing code is to define a vector3 halfAxis which determines the height and direction of the cylinder. So if halfAxis is (0,1,0), the center of the cylinder coincides with the y-axis if the cylinder is at the origin in world space and length would be 2 since its a half axis.

Currently all my code does is generate the cylinder based on a height factor only in the y direction. There is capResolution which determines the smoothness of the cylinder and a radius to define cylinder radius

Below is my code. How would I modify it to add the halfAxis vector and determine its orientation

```
public Vector3 halfAxis = Vector3.up;
public float radius = 3f;
public int capResolution = 3;
public int height = 2;
private const int MAX_CAP_RES = 3;
private const int MAX_RADIUS = 1;

void ComputeCylinder(out Vector3[] vertices, out Vector2[] uvs, out Vector3[] normals, out int[] faces)
    {

        if (capResolution < MAX_CAP_RES) capResolution = MAX_CAP_RES;
        if (radius < MAX_RADIUS) radius = MAX_RADIUS;

        //define total columns and rows
        int noOfColumns = capResolution + 1;
        int noOfRows = height + 1;

        //total number of vertices that make up the cylinder
        int noOfVertices = noOfColumns * noOfRows;

        //no of normals for each vertex
        int noOfNormals = noOfVertices;

        //uvs are always equal to no of vertices in a mesh
        int noOfUvs = noOfVertices;

        //side faces (tris) without the top and bottom caps
        int noOfSideFaces = capResolution * height * 2;

        //cap faces (2 caps bottom and top)
        int noOfCapFaces = capResolution - 2;

        //initialize all the arrays
        vertices = new Vector3[noOfVertices];
        normals = new Vector3[noOfNormals];
        uvs = new Vector2[noOfUvs];
        faces = new int[(noOfSideFaces + noOfCapFaces * 2) * 3];

        //angle step for each column for side tris
        float step = Mathf.PI * 2 / capResolution;

        /*
           first for loop computes all the side faces of the cylinder
           second loop computes tris for top and bottom caps
         */
        for (int i = 0; i < noOfRows; i++)
        {
            for (int j = 0; j < noOfColumns; j++)
            {
                float angle = j * step;

                //folding from the first and last vertex
                if (j == noOfColumns - 1) angle = 0;

                //compute vertices, uvs and normals for each row and column offsets
                vertices[i * noOfColumns + j] = new Vector3(radius * Mathf.Cos(angle),i * height,radius * Mathf.Sin(angle)); //build a cylinder with an upwards orientation
                uvs[i * noOfColumns + j] = new Vector2(j * 1 / radius, i * 1 / halfAxis.y);
                normals[i * noOfColumns + j] = new Vector3(0, 0, -1.0f);

                /*
                   To create faces, we ignore the first row and the last column
                   for every other vertex we create two triangle faces at the same time in one loop
                 */
                if (i != 0 && j < noOfColumns - 1)
                {
                    //offset the initial space for storing tris for bottom cap
                    int index = noOfCapFaces * 3 + (i - 1) * capResolution * 6 + j * 6;

                    //create the first face
                    faces[index + 0] = i * noOfColumns + j;
                    faces[index + 1] = i * noOfColumns + j + 1;
                    faces[index + 2] = (i - 1) * noOfColumns + j;

                    //create the second face
                    faces[index + 3] = (i - 1) * noOfColumns + j;
                    faces[index + 4] = i * noOfColumns + j + 1;
                    faces[index + 5] = (i - 1) * noOfColumns + j + 1;
                }
            }
        }

           /*drawing top and bottom caps
           we need the firstIndex, midIndex and lastIndex as vertices for cap tris and store it in the faces array*/

        int firstIndex = 0;
        int midIndex = 0;
        int lastIndex = 0;
        int topCapOffset = noOfVertices - noOfColumns;

        for (int i = 0; i < noOfCapFaces; i++)
        {
            //we get the bottom index to populate faces for bottom cap
            int bottomIndex = i * 3;

            //top cap tris will be stored in the empty end location of faces array
            int topIndex = (noOfCapFaces + noOfSideFaces) * 3 + i * 3;

            //get the three index for each vertex to make a cap tri
            if (i == 0)
            {
                firstIndex = 1;
                midIndex = 0;
                lastIndex = noOfColumns - 2;
            }
            else
            {
                midIndex = lastIndex;
                lastIndex = lastIndex - 1;
            }

            //populate triangle vertices for bottom cap
            faces[bottomIndex + 0] = lastIndex;
            faces[bottomIndex + 1] = midIndex;
            faces[bottomIndex + 2] = firstIndex;

            //populate triangle vertices for top cap
            faces[topIndex + 0] = topCapOffset + firstIndex;
            faces[topIndex + 1] = topCapOffset + midIndex;
            faces[topIndex + 2] = topCapOffset + lastIndex;
        }
    }

```

# Answer
You could rotate every single point after you created them like this:

```
    var rotation = Quaternion.FromToRotation(Vector3.up, axis.normalized);
    var rotatedPoint = rotation * point;

```

But I still think that rotating the object node is a more elegant way.
> 1 votes

---
Tags: c#, unity, procedural-generation, graphics-programming
---


# Question
Title: Transparent diffuse fails to render from all viewing angles
I'm rendering this chunk as a Unity mesh and I have just one material (with alpha) which is applied over all the mesh.

Everything in the chunk is automatically generated at runtime, so it's not possible to prepare anything in advance, even the materials.

Here the model is rendering correctly (from a specific point of view which works):

The problem is this:

And here you see that it works if the mesh isn't rendering on itself.

When the material is applied, if you watch on the transparent section you will see it semi-transparent (which is the correct and expected behaviour), or you will see it just in part, because the transparency gets overlapped by the parts of the mesh which are behind the transparent part.

In some cases it even disappears or make anything that is on it disappear.

Does anyone know a good shader that can fix this problem and that is a diffuse? I tried to modify zTest in the shader, but nothing changes, or the render gets even worse.

Here are the two shaders:

This is the one the material uses

```
Shader "Custom/Diffuse" {
Properties {
    _Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
}

SubShader {
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    LOD 50

CGPROGRAM
#pragma surface surf Lambert alpha

sampler2D _MainTex;
fixed4 _Color;

struct Input {
    float2 uv_MainTex;
};

void surf (Input IN, inout SurfaceOutput o) {
    fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
    o.Albedo = c.rgb;
    o.Alpha = c.a;
}
ENDCG
}

Fallback "Custom/VertexLit"
}

```

And here is the second, which the first refers to.

```
Shader "Custom/VertexLit" {
Properties {
    _Color ("Main Color", Color) = (1,1,1,1)
    _SpecColor ("Spec Color", Color) = (1,1,1,0)
    _Emission ("Emissive Color", Color) = (0,0,0,0)
    _Shininess ("Shininess", Range (0.1, 1)) = 0.7
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
}

SubShader {
    Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
    LOD 100

    Alphatest Greater 0
    ZWrite Off
    ZTest Always
    Blend SrcAlpha OneMinusSrcAlpha
    ColorMask RGB

    // Non-lightmapped
    Pass {
        Tags { "LightMode" = "Vertex" }
        Material {
            Diffuse [_Color]
            Ambient [_Color]
            Shininess [_Shininess]
            Specular [_SpecColor]
            Emission [_Emission]
        }
        Lighting On
        SeparateSpecular On
        SetTexture [_MainTex] {
            Combine texture * primary DOUBLE, texture * primary
        }
    }

    // Lightmapped, encoded as dLDR
    Pass {
        Tags { "LightMode" = "VertexLM" }

        BindChannels {
            Bind "Vertex", vertex
            Bind "normal", normal
            Bind "texcoord1", texcoord0 // lightmap uses 2nd uv
            Bind "texcoord", texcoord1 // main uses 1st uv
        }
        SetTexture [unity_Lightmap] {
            matrix [unity_LightmapMatrix]
            constantColor [_Color]
            combine texture * constant
        }
        SetTexture [_MainTex] {
            combine texture * previous DOUBLE, texture * primary
        }
    }

    // Lightmapped, encoded as RGBM
    Pass {
        Tags { "LightMode" = "VertexLMRGBM" }

        BindChannels {
            Bind "Vertex", vertex
            Bind "normal", normal
            Bind "texcoord1", texcoord0 // lightmap uses 2nd uv
            Bind "texcoord1", texcoord1 // unused
            Bind "texcoord", texcoord2 // main uses 1st uv
        }

        SetTexture [unity_Lightmap] {
            matrix [unity_LightmapMatrix]
            combine texture * texture alpha DOUBLE
        }
        SetTexture [unity_Lightmap] {
            constantColor [_Color]
            combine previous * constant
        }
        SetTexture [_MainTex] {
            combine texture * previous QUAD, texture * primary
        }
    }
}

}

```

# Answer
> 1 votes
It's a problem with sorting order of the objects. Why are both shaders in "Transparent" queue? You could just change the ground shader's queue to "Geometry" and fix the problem. Do you use transparency on the ground objects?

If you really need the transparent queue, you could set the queue to things like "Transparent+1" to force it render later than other transparent objects:

http://docs.unity3d.com/Manual/SL-SubshaderTags.html

---
Tags: unity, shaders, rendering
---


# Question
Title: Trying to extract file icons and use as a sprite texture
I'm trying to extract file icons from the files inside a folder (eg: Program Files), and have them set as my Sprite's texture. I extracted the file icons, converted them to Bitmaps and then to byte array, and call the LoadImage(byte\[\] byte) function in my Sprite object. But when I test, the textures become the image belows. Any idea how to fix this? I just want to set my sprites texture as the extracted file icon, I'm creating something similar to a file explorer.

this is the result that i get

this is what I should get if I navigate to the notepad++ folder (eg : "C:\Program Files(x86)\Notepad++\\")

this is my settings for the texture (supposedly, later being replaced with the extracted icons)

Here's my code

```
public UnityEngine.UI.Image targetImg;
public void Load(string directory)
{
    Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(directory);
    Bitmap bmp = icon.ToBitmap();
    targetImg.sprite.texture.LoadImage(ImageToByte(bmp));
}

public static byte[] ImageToByte(Bitmap img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

```

# Answer
As far as I know, for accessing bitmap's pixel data, you should use LockBits() function:

https://msdn.microsoft.com/en-us/library/5ey6h79d(v=vs.110).aspx

Something like this:

```
var bitmapData = scaledBitmap.LockBits(...);
var length = bitmapData.Stride * bitmapData.Height;
byte[] bytes = new byte[length];
// load image
targetImg.sprite.texture.LoadImage(ImageToByte(bmp));
scaledBitmap.UnlockBits(bitmapData);

```
> 1 votes

---
Tags: unity, textures
---


# Question
Title: How can I access LWJGL's Keyboard from a thread other than the graphics thread?
I'm loving LWJGL, but have been running into a number of odd problems with it. Most of it seems to deal with the fact that OpenGL is a state-machine and was only ever meant to be accessed from a singular thread.

However, I'm dealing with OpenAL and input as well, and they are both bound pretty tightly into LWJGL. In spite of the fact that they are entirely independent of graphics, I have been getting an `IllegalStateException` every time I try to access `Keyboard.isKeyDown` outside of the graphics thread. It's hard to emphasize how important it is to me that I have a new thread for each feature of this project; the classic game loop will not do the job.

How do I accomplish this? There must be a way.

# Answer
> 2 votes
One solution (and probably the easiest) would be to create a small wrapper class around the LWJGL input system. Check all the key states, and save them in an ArrayList. Then, somewhere at the beginning of your game loop, update your Input class once, and use that information you stored for future reference.

Code example: *click*

This also has the benefit of you being able to seperate pressed, hold and released keys. The example also includes the same system for the mouse.

# Answer
> 1 votes
The way I did it is simply calling Keyboard.create() in all the threads that I need to use Keyboard.isKeyDown(int key). I know this sounds sloppy, but it has been working perfectly for me so far.

# Answer
> 0 votes
So, after some helpful comments and a little digging through decompiled jars, here's my conclusion. In a word "no," but generally that's just because LWJGL operates (once again) through state machines.

I would like it very much if there was a way to separate those without rewriting the library, but in the mean time, I've established a single thread as an LWJGL thread but kept my original architecture and interfaces around. The LWJGL thread is simply compatible for audio, input, and video all at once. If I want to direct audio to a new AL thread, or get input from a new Input thread, I can do that in the future.

The main idea was to separate model, view, and control from the old school game loop; and I think it's working pretty well.

---
Tags: lwjgl, input, multithreading, keyboard
---


# Question
Title: How do I convert an image into a tile map?
I am working on a game in Pygame/Python, and I'd like to turn an image into a map.

The idea is simple: Pixels in the image are colored by tile type. When the program loads the image, I want the color (e.g. `#ff13ae`) to be matched to a certain grass tile, and the color (e.g. `#ff13bd`) to a different tile.

I know that I may have to convert from hexcodes to RGB, but that is trivial. I just want to know the way I to go about loading an image file, mainly because all my other games don't do anything of this sort.

# Answer
> 0 votes
I did this once by drawing maps in GIMP and saving them out to portable pixmap format (PPM), because PPMs are really easy to parse.

A PPM-parsing library (or a parser for a more complex image format, actually) might exist for Python already, but to keep this maximally useful for everyone, I'll explain the concepts.

Just to get an idea of what we want, here's one of my levels, converted to PNG format:

There's a tiny little yellow pixel in a room to the left indicating the player's start position. Green are lit-up "sky" tiles, white is "ground", blue is "water" and red is a "finish line". (The level ends when you jump off the floating island at the top there.)

PPM files are plain text. They look like this:
<sup>(stuff after `|` are my commentary, not part of the format)</sup>

```
P3         | "magic number", always the same
200 120    | image width and height, in pixels
255        | maximum value of a colour channel
128        | red value   of first pixel
128        | green value of first pixel
128        | blue value  of first pixel
0          | red value   of second pixel
0          | green value of second pixel
0          | blue value  of second pixel
           | ... and so on for every pixel, and that's it

```

The pixels' values are recorded left-to-right and top-to-bottom. Here, the very top-left pixel has an RGB value of `128, 128, 128` (grey). The pixel one to the right of that is `0, 0, 0` (black).

Pay attention to the specified maximum value though. It's `255` in this example, so the first pixel's values are `128/255 = 0.5`, which results in grey. If the maximum had been `128`, the values would be `128/128 = 1`, giving white! (GIMP seems to always set the maximum value to 255. It's pretty sensible.)

To parse such a file, you'll want to

1. check that the first line is `P3` (just in case),
2. record the image's width and height from the second line, and
3. keep reading three lines at a time, recording pixel values

At the end you can check just in case that you got `width * height` many pixels.

As you read the pixels, convert them to your chosen tile meanings, and store them however you like. (For example, your colour `#ff13ae` corresponds to a pixel of RGB-values `255, 19, 174`.)

---
Tags: tilemap, python, pygame, image, file-format
---


title: AS3 random events using a timer

text:
# Question
Title: AS3 random events using a timer
I'm making a game for an assignment at university. The game I am making requires random household appliances around a house to "turn on" at random times. The player must run around the house turning this off.

I am confident with the rest of the code for the game, but the random turning on is what I'm not sure on.

I am thinking the solution would be to use an array with all my appliances pushed into into, then create a timer event. From this a random time would be picked from the timer, and then a random appliance would be picked from the array. The appliance on animation would then be displayed until the player clicked on it to turn it off.

Only problem is i'm not sure how to start this.

Also worth mentioning, I am only able to use flashdevelop and AS3 for this project, so no Adobe Flash.

Thanks in advance,

Job4aCowboy

# Answer
Before you read the code provided make sure you understand the pseudo code.

```
// Assumptions:
// Appliance objects provide the turnOn() function.
// We have a collection of appliances we can access somehow.

Pseudocode:

// Constructor
    // Gather our appliances...
    // Kickoff the randomized start function

// Randomized Start Function
    // Start a random appliance
        // Select an appliance at random
            // Get a random number
            // Use that number as the selected appliance
            // Start the selected appliance
    // Call this function again after a random delay
        // Get a random number
        // Use that number as the random delay
        // Reset the timer to 0
        // Set the timer to 'go-off' after the random delay
        // Set the timer to call this function when it goes off
        // Start the timer
// END

var static const MAX_DELAY:uint = 10;
var static const MIN_DELAY:uint = 1;

var appliances:Array = new Array();
var timer:Timer = new Timer(0, 1);

// Constructor
public function ApplianceGhost():void{
    // Gather our appliances... from somewhere?
    for (var cur:Appliance in applianceCollection) {
        appliances.push(cur);
    }

    startApplianceAndLoop();
}

function startApplianceAndRecurse():void {
    // Start a random appliance
    startRandomAppliance();

    // Call this function again after a random delay
    var randomDelay:Number = randomFromRange(MIN_DELAY, MAX_DELAY);
    timer.reset();
    timer.delay = randomDelay
    timer.addEventListener(TimerEvent.TIMER_COMPLETE, startApplianceAndLoop);
    timer.start();
}

function startRandomAppliance():void {
    // Select an appliance at random
    var applianceToStart:int = randomFromRange(0, appliances.length);

    // Start the selected appliance
    appliances[applianceToStart].turnOn();
}

// Return n such that:   min <= n <= max
public function randomFromRange(min:Number, max:Number):Number {
    return (Math.floor(Math.random() * (max - min + 1)) + min);
}

```

Disclaimer:

1. I wrote this code in Sublime Text so it hasn't been exposed to autocomplete or a compiler.
2. I probably won't offer suggestions on syntax errors or 'A won't compile because X' (practice solving these; they are a surprisingly large part of being a Software Engineer).
3. This algorithm starts the first appliance immediately, you might need to start the first appliance after a delay.
4. Random from range is borrowed from here.
> 1 votes

---
Tags: actionscript-3, random, timer
---


# Question
Title: Gravity Simulation failing at short distances
I have a 2D space simulation with gravity acting on three bodies (e.g. sun and 2x planets). The simulation seems pretty stable with RK4 (was unstable with Euler). The problem arises if the orbit of one of the planets get VERY close to the sun (or other planet), it is liable to shoot off towards alpha-centuri.

I think the problem is due to the asymmetric nature of numerical integration in this situation; if a planet is VERY close to a sun in one time step, it will experience huge acceleration and end up (next update) on the far side of the sun, much further away with much weaker gravity (1/r^2), which won't counteract the huge acceleration experienced in the previous update.

Implementing RK4 had improved the situation over Euler, but not eliminated the problem. The game I am working on requires bodies to fly very close to other bodies and still behave correctly.

Any potential solutions?

**Edit**

One the the answerers, @Thelvyn suggested using fixed elliptical orbits, but that is not an option here as the planets can interact gravitationally. Also, yes I am using a fixed timestep.

# Answer
You could consider breaking down a single physical frame based on the absolute magnitude of the acceleration vector for any body in the simulation. Essentially, you could map the number of digits in the acceleration magnitude to the number of iterations per each physical frame:

```
timeSlicesRequired = ceil(log10(maximumMeasuredAcceleration))
adjustedTimeStep = 1 / timeSlicesRequired
for (i = 0; i < timeSlicesRequired; i++) {
    advanceSimulationBy(adjustedTimeStep)
}

```

That way, you're still keeping real time, but calculating more smaller steps inside a single physical frame, hopefully mitigating most of your problems (but not all, extremely close orbits will still cause problems due to precision).
> 2 votes

# Answer
For stuff like this I would use elliptic orbits, this guaranties stability by definition.

Due to limited precision of floating point numbers you will reach a point where you will lose stability I guess. This often no big deal in physics engines because you have energy loss at each bounce so you're convergent.

Do you really need integration here ?

Edit: One last remark, if you use integration ensure that you use a fixed time step.
> 0 votes

---
Tags: physics, integration, numerical-methods
---


# Question
Title: In a collision detection loop, when do I apply the velocity?
I'm writing a really basic collision detection system (AABB vs AABB, AABB vs Circle, Circle vs Circle), and I've just got to the point of writing the actual loop which iterates the objects and checks for collisions.

My question is when do I apply the velocity to each object? Do I move all objects by `vel * dt` before I even start colliding? Do I apply the velocity as I iterate? If so, do I apply it to both objects I'm testing, or just the first, and then apply the velocity to the second when I check collisions against that one?

Also presumably I should do the whole collision check recursively (as the act of responding to one collision might cause another), but that obviously effects how and when the velocity is applied.

My suspicion is that I should move all the objects by their velocity before I begin, and then recursively detect and respond to collisions until nothing is colliding (or until some loop limit).

# Answer
> 1 votes
The way I would go about it (did it in a few small games) would be to first move all objects, then detect and possibly correct collisions, and then draw.

If you collide as you move the objects, you will end up with inconsistent states: if A has been moved and B has yet to be moved, you might detect and collision between A and B to does not actually exist once B has been moved.

If you correct collisions first, you might have an issue: You are, effectively, correcting collision that were drawn one frame ago, meaning that the player might actually see objects overlapping during one frame before disappearing.

If you move (apply velocity), then collide and correct, and finally draw, you make sure that no overlapping/invalid state is drawn to the screen.

Hope it helps :)

---
Tags: collision-detection, response
---


# Question
Title: Unity3D Directional lights vs Draw calls
I need 2 light sources looking at a different direction as per my design. This means, I cannot flag one of them as 'not-important'! I found that because I'm using 2 directional lights, drawcalls are aggrevated. Can somebody provide me a direction.

With one DL: 7 draw calls. With 2 it goes to 60 odd. It is the same case if I switch them vice versa.

# Answer
The first question is, which `RenderingPath` do you use? You can choose a path at `PlayerSettings|OtherSettings|RenderingPath`. There are some pros and cons of each and you can read more about them and their differences, especially in performance, here.

Second important thing are your light quality settings, especially the pixel lights count. Flagging light as 'not-important' means that it could use vertex lighting instead of pixel lighting.

> Since pixel lights are much more expensive than vertex lights, Unity will only render the brightest lights at per-pixel quality. The actual number of pixel lights can be set in the Quality Settings for webplayer and standalone build targets.
>
> You can explicitly control if a light should be rendered as a vertex or pixel light using the Render Mode property. By default Unity will classify the light automatically based on how much the object is affected by the light.

You can check `RenderMode` property on each light you use.

Another good place to look at is how many textures are you using on your objects, how many vertices they possess and how complicated are shared you are using. All these three factors are relevant, when it comes to use built-in `dynamic batching` unity feature.

Also, you can experiment with point light instead of second directional light, the point light could be also attached to the camera. Can't say anything better without more knowledge of your specific case, hope that these information will give you any help.
> 0 votes

# Answer
I have to insist on Vertex lighting for most games, I can only speak for my game and my experience though. What shaders are you using on your objects, try to stick with diffuse, and other low shaders.

Are your textures optimised? I think that could well be a problem; do you have static batching (Unity Pro)? Have you created a texture atlas?

All the above can help/ruin your DrawCall count.

(I can not comment, not enough reputation).
> 0 votes

# Answer
You could always write a shader to render objects in one single pass for multiple lights:

http://en.wikibooks.org/wiki/Cg\_Programming/Unity/Multiple\_Lights http://kylehalladay.com/blog/tutorial/bestof/2013/10/13/Multi-Light-Diffuse.html

What about shadows? Because they also add more passes, and as I remember correctly dynamic batching won't work on the shadow pass. I suggest to test your code on the device you're targeting, maybe the framerate is acceptable even with lots of draw-calls.
> 0 votes

---
Tags: unity, lighting, optimization
---


title: Unity Render Texture Artifacting

text:
# Question
Title: Unity Render Texture Artifacting
I'm having weird black artifacts appear on my render textures when they are transformed while the game is running.

I am using a ScrollRect as a scrolling container for buttons (the buttons are just textured quads with the same render texture applied to them). When I translate the quads while the game is running, strange black artifacts will appear on the quads themselves.

Is there a way to fix this?

Edit: Interesting to note, setting every quad inactive except for one fixed the artifacting on the only visible quad: https://i.stack.imgur.com/H5uUC.png

The intensity of the artifacting seems to be related to the number of objects on-screen that use the same render texture. 5 quads active with the same render texture has a really pronounced artifacting, 3 is more subtle, 1 is visibly non-existent.

# Answer
This may seems crazy, but the artifacts look like shadowing artifact! Are you sure the shadows are turned off?
> 1 votes

---
Tags: unity, gui
---


# Question
Title: Algorithm that always returns the same pseudorandom output if given the same input of seed, x and y?
I've been trying to find an algorithm that will take in an *x* value, a *y* value, and a *seed* value and then spit out a number between 0 and 255 (or an int that I can cut up into bytes). I want to be able to feed in the tile a player is standing on during some ingame event and get the same value for the same tile any time the player is in that level. I don't want to use a linear PRNG because I just want to check a few tiles at any one time, not go though several of them to get a sequence.

I tried modifying an Xor Shift PRNG, but I just end up making patterns like below:

```
ubyte Xor( int wx, int wy, ulong seed ){
    int result = wx ^ (wx >> 7) ^ wy ^ (wy >> 9) ^ seed ^ (seed << 6);
    return cast(ubyte)result;
}

```

My input values are likely to be 0-32000 for x and y, and seed can be any ulong value. I'd like to avoid floating point math as it's not deterministic between machines (so it would screw up some multiplayer stuff). I just need to not get a repeating pattern, and have each seed produce a distinctly different output. Can anyone point me in the right direction?

# Answer
What you are looking for is a hash algorithm. You'd concatenate your 16 bit x and y position into a 32 bit number and then hash that to get what is effectively a pseudo random number out. The size of the hash output depends on what algorithm you use, but you could easily just use the lowest 8 bits of whatever the output is to get your 0-255 value. It will have the properties that you want: neighboring tiles will usually have very different values, but the same tile will always give you the same result. For use in a game scenario I would recommend murmurhash. Its not quite cryptographic quality, which is fine for your usage case, and is very fast while giving very nice pseudo random distribution (avalanche effect).

Murmurhash3 source code can be found here: https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp

(:
> 3 votes

# Answer
Why not a PRNG, actually? It looks like a simple and good tool to me.

Some pseudocode using `srand`/`rand` that you should be able to adapt to any other PRNG:

```
int shuffle(int seed, int x, int y)
{
    int tmp;
    srand(seed); tmp = rand();
    srand(tmp + x); tmp = rand();
    srand(tmp + y); tmp = rand();
    return tmp;
}

```

This can actually be very fast. Using one of C++’s standard PRNGs, the following function compiles to just shuffling instructions (no std library calls) and can execute 80 million times a second (5 times faster than Murmurhash).

```
#include <random>

int shuffle(int seed, int x, int y)
{
    std::minstd_rand r;
    r.seed(seed); r.seed(r() + x); r.seed(r() + y);
    return r();
}

```
> 0 votes

---
Tags: 2d, random
---


# Question
Title: Everything black except where there's a light
I have a camera in my scene with a map created at runtime:

As you can see everything can be seen. Now I want the map to be invisible (black as the background) except where there are lights. How can this be achieved in Unity3D?

# Answer
one solution is to remove the directional light and relay only on other lights; then set ambient light near to dark.
> 1 votes

---
Tags: unity, camera, view
---


# Question
Title: Is there a centralized database of game names and IDs?
Given two games with very similar names:

Alien Shooter II - Vengeance

Alien Shooter: Vengeance

Is there some place that I can go to get an ID or the 'canonical' name for these games? I suspect that they are the same game, but it's very hard to say for certain.

# Answer
No, there is no single, central, comprehensive source for this information.

There's MobyGames; I'm not sure how they aggregate all their data, it's not completely accurate but it may be your best bet. There's also the US Patent and Trademark Office or the copyright office, via which you may be able to wade through trademark or copyright filings to find "official" names. Not all of those would correspond to actual shipped titles, though, and you probably won't find the smaller titles on any of those sites.
> 11 votes

# Answer
Something like that exists for emulators called GoodTools. It's a suite of applications each containing a database of all "known games" and identifying ROMs via checksums to rename the files to a canonical scheme. Unfortunately I'm not aware of anything similar for the PC platform.
> 2 votes

# Answer
As Josh mentioned there's MobyGames however it doesn't provide an API. There are a few systems out there that scrape the mobygames pages but nothing official (or reliable as screen scaping is just ugly). MobyGames mentions they want to build an API but that has yet to surface.

TheGamesDb.net has an API documented here. They have +25k games however very little activity since 2013 (at least on the blog). They suffer from a lot of SPAM on the forums and the API is pretty awkward (case sensitive PHP urls, XML format only, not RESTful at all, etc.)

GiantBomb has +45k games listed. It's more of a Wiki and covers games, characters, etc. It's very similar to ComicVine and offers an API here (you just need to apply for an API key). It's very active and pretty up to date.

Finally IGDB promises to be an Internet Movie DB like system but for games. However it's in closed beta (and has been for some time) so its doubtful anything will come of this. You can check out their Facebook page here to track them down and see if anything is going on with the site as they do have FB updates.

Hope that helps.
> 0 votes

---
Tags: game-industry
---


title: How to play Sound of a Destroyed Object

text:
# Question
Title: How to play Sound of a Destroyed Object
So I have implemented grenades, and thats working fine. Now I want some explosion sound, but the problem is that the sound is still playing when the grenade is explode and I Destroy the grenade. Does someone have an idea how to circumvent this? I mean I could disable all Components on the nade so that it's invisible etc. and destroy it after the sound is done playing, but I feel like that's a bit weird.

# Answer
You have a few options.

1. Disable the render component, and delay the destruction of the grenade until the sound/(particle/visual effect?) are done. Destroy takes an optional parameter for a time delay: `GameObject.Destroy(yourGrenadeObject, timeToWaitToDestroy);`
2. You can create a new object in place of the grenade that plays the sound, does the visual effect, does collision checks for damage, etc. This explosion object would destroy itself when the sound or effects have come to an end.

Personally, I'd likely go with the second option as the explosion object could be used in other situations than just grenades, so you're saving yourself some work. I should say, on the topic of destroying game objects like this, it's probably best to be using some kind of object pool to re-use these game objects. That means disabling them after they're done and re-enabling them when they're to be used again. This saves on allocating and garbage clean-up of memory.
> 3 votes

---
Tags: unity
---


# Question
Title: Unity C# 2D Platformer Main Camera should stop on sides of level
I've been working on a 2D Platformer and i succeeded in setting up a script for my Main Camera to follow my Player gameobject using transform positions.

Now when my character is near the sides (or ends) of my level, it's showing dead space, blue space if you will. I want my camera to stop when it reaches the edges of my background sprite(end of level).

Here's my script that is attached to the Main Camera so far:

```
using UnityEngine;
using System.Collections;

public class CameraSmoothFollow : MonoBehaviour
{

public GameObject cameraTarget; // object to look at or follow
public GameObject player; // player object for moving

public float smoothTime = 0.1f;    // time for dampen
public bool cameraFollowX = true; // camera follows on horizontal
public bool cameraFollowY = true; // camera follows on vertical
public bool cameraFollowHeight = true; // camera follow CameraTarget object height
public float cameraHeight = 2.5f; // height of camera adjustable
public Vector2 velocity; // speed of camera movement

private Transform thisTransform; // camera Transform

// Use this for initialization
void Start()
{
    thisTransform = transform;

}

// Update is called once per frame
void Update()
{
    if (cameraFollowX)
    {
        thisTransform.position = new Vector3(Mathf.SmoothDamp(thisTransform.position.x, cameraTarget.transform.position.x, ref velocity.x, smoothTime), thisTransform.position.y, thisTransform.position.z);
    }
    if (cameraFollowY)
    {
        // to do
    }
    if (!cameraFollowX & cameraFollowHeight)
    {
        // to do
    }

}

```

}

# Answer
> 1 votes
In your Update Function, You need limit transform.position.x range, like this:

```
void Update() {
    float targetX =  Mathf.Max(levelMinX, Mathf.Min(levelMaxX, cameraTarget.transform.position.x));
    float x = Mathf.SmoothDamp(thisTransform.position.x, targetX, ref velocity.x, smoothTime);

}

```

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


title: DirectX11 Shader issue

text:
# Question
Title: DirectX11 Shader issue
I am currently having issues with HLSL shaders. I am trying to implement point lights but I am getting unusual data when debugging the shader in Visual Studio.

I have read on several sites that say that the data stored in CBuffers should be aligned to 4 bytes, thus I added padding where it was needed (is this correct?).

When I set the data in c++, some of it comes through alright but other data is not. For example the color comes through alright but the range is being displayed as NaN in the VS graphics debugger.

Is there something wrong with the code below? (All structs are the same as those in c++ structs)

Please ask if there is anything else you would like to see code wise. Thanks!

**PointLight Code:**

```
float4 calcPointLight(PointLight pointLight, float3 normal, float3 worldPos0, float4 specularMap, float4 diffuseTex)
{
    float3 lightDirection = worldPos0 - pointLight.pos;
    float distanceToPoint = length(lightDirection);

    //  if (distanceToPoint > pointLight.range)
   //   return float4(0, 0, 0, 0);

    lightDirection = normalize(lightDirection);

    float4 color = calcLight(pointLight.base, lightDirection, normal, worldPos0, specularMap);

    float attenuation = pointLight.atten[0] +
    pointLight.atten[1] * distanceToPoint +
    pointLight.atten[2] * distanceToPoint * distanceToPoint +
    0.0001;

    return color / attenuation;
}

float4 calcLight(BaseLight base, float3 direction, float3 normal, float3 worldPos0, float4 specularMap)
{
    float diffuseFactor = (dot(normal, -direction));

    float4 diffuseColor = float4(0, 0, 0, 0);
    float4 specularColor = float4(0, 0, 0, 0);

    if (diffuseFactor > 0.0f)
    {
        diffuseColor = base.color * base.intensity * diffuseFactor;
        diffuseColor = saturate(diffuseColor);

        float3 directionToEye = normalize(cameraPos - worldPos0);
        float3 reflectDirection = normalize(reflect(direction, normal));

        float specularFactor = dot(directionToEye, reflectDirection);
        specularFactor = pow(abs(specularFactor), specularPower);

        if (specularFactor > 0)
        {
            specularColor = base.color * 1.0f * specularFactor;
        }
        if (specularMap.a > 0.0f)
            specularColor = specularColor * specularMap;
    }

    return saturate(ambient + diffuseColor + specularColor);
}

```

**Structs**

```
struct BaseLight
{
    float4 color;
    float intensity;

    float3 padding3; //TEST
};

struct DirectionalLight
{
    BaseLight base;
    float3 direction;
};

struct PointLight
{
    BaseLight base;
    float3 atten;
    float padding;
    float3 pos;
    float range;
};

```

**CBuffers**

```
    cbuffer MatrixBuffer : register(b0)
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

cbuffer LightingBuffer : register(b1)
{
    float4 ambient;

    float specularPower;
    float3 padding3;

    PointLight pointLight;
    //DirectionalLight light;

 };

 cbuffer CameraBuffer : register(b2)
{
    float4 cameraPos;
};

```

# Answer
Verdict: One of the cBuffers was set to the incorrect stage.

Edit: I'll leave this here because it was irrelevant, but not entirely worthless in the future.

If your structs are cbuffers, they should be of type cbuffer.

```
cbuffer cbBaseLight : register(b0) //16*2=32-bytes
{
    float4 color;
    float4 intensity;
};
cbuffer cbDirectionalLight : register(b1) //16*3=48-bytes
{
    cbBaseLight base;
    float4 direction;
};
cbuffer cbPointLight : register(b1) //16*5=80-bytes
{
    cbBaseLight base;
    float4 atten;
    float4 pos;
    float4 range;
};

```

Pay attention to the registers; I'm assuming only one of PointLight/Directional will be set at a time.

**NAN**

"NAN", within PIX, means the GPU believes the value is constant and unused and is, therefore, not worth calculating (even to show you the value).

```
UV *= 1; //For a variable/vertex value
output.XXX = float4(UV, 0, 0); //For a constant value

```

will make the value appear. You just need to "use" the value.
> 1 votes

---
Tags: directx, graphics, directx11, hlsl, graphics-programming
---


# Question
Title: Make a triangular mesh from of a map defined by points that follow the coast lines
I have a set of points which follow the coast lines of a world map. I would like to triangulate it so that I can render the continents filled in. The points seem to be in order so that if you render as lines, the only issue is when a land mass starts and ends you get lines you shouldn't have between them.

Does anyone know of a good way to go about making a triangular mesh out of this data?

# Answer
> 2 votes
If this is dynamic, a radial sweep algorithm to collect the points into clumps of non-overlapping triangles. A geometry shader would generate a triangle fan from the clumps using the calculated radial point for each.

If this is static, I'd render it as a LINESTRIP, save the rendertarget to disk, and flood-filling the shape in Paint. You can use the result as a stencil and draw the LINESTRIP for borders.

Here is an image of a big red quad drawn with a stencil of Texas. The right-most portion of the stencil was erased to reveal the quad.

---
Tags: mesh, triangulation
---


# Question
Title: How and where to handle collisions? [Java]
Okay, so in my game I have a Level class, which hold an ArrayList of entities. In addition to this, I store the Player here (naturally enough). In my Entity class, I have a method which checks for collisions. This method looks like this:

```
public boolean collision(Entity other) {
     return cBox.intersects(other.cBox);
}

```

Now, in my Level class, under the update() method, I check for collisions like this:

```
for (int i = 0; i < entities.size(); i++) {
    if (entities.get(i).collidable() && entities.get(i).collision(player)) {
        player.notifyCollision();
    }
}

```

The notifyCollision() method simply ticks a boolean named collision to true in the player class.

This leads me to the question: If I have, say a Chest, an Enemy and some Spikes, where all of them are entities on a map (every entity except for the player is part of the entities ArrayList under the Level class), how would I handle the collisions, and where would I do this?

Say that I want to open a chest if the player is standing in front of it, or hurt the player if it collides with an enemy etc. Would I simply go with the notifyCollision() method, and then have another method named handleCollisions() in the Player class, which would be called if a collision were notified? Or would I have a handleCollision() method under the Chest, Enemy and Spike class, and handle them from here?

Because, the question is really how and where to handle the collisions.

# Answer
> 0 votes
Basically objects should define by themselves what happens to them when collision happens and the parent object owning colliding objects should check the collisions and notify the objects colliding each other by calling the collision handler routines.

If your game is simple, you may not even need a specific collision checking interface. For example when player comes near a chest its more intuitive to call an openChest() function than calling handleCollision() function. For your question where the distance between objects should be checked, its a matter of opinions. I would do it the upper way, meaning that the player and the chest would be responsible for their own actions when opening the chest (animations, sounds when opening...) and the level would be responsible between the interaction between the two.

---
Tags: java, collision-detection
---


# Question
Title: 2d Collision detection response equation doesn't work
I am currently doing some game engine programming as a hobby. I have been working on getting the collision detection working for a while now, and I'm at my wits end with it.

I started with this guide. If you scroll down the the picture of the character sprite, you will see that she uses points on the character instead of a bounding box to do the collision. That is what I currently have implemented, but I'm having a ridiculously hard time making it work perfectly.

I started with axis aligned, but moved to separating axis theorem so that I can implement collision boxes that are at an angle. The collision response I'm trying to use when a collision occurs on the bottom of the character is this horrible thing:

```
nextY = (bottomColl.getY1() + bottomColl.getCenterY() + (currHeight() / 2) +
        (nextX + collisionPoints[currState][currFrame][4][0] - bottomColl.getCenterX() + (currHeight() / 2) * tan(angle / 2)) * tan(angle));

```

Y1 being top left corner and collisionPoints 4 being the bottom right point. (This is for an incline as opposed to a decline. The decline would use point 5, the bottom left point.)

This, however, doesn't work, and updates the character position to slightly lower than he is supposed to be. This has little effect, unless the frame rate is really high, in which case, the jump animation does not move the character out of the collision box and the character gets pushed way far away.
I realize the code is probably hard to decipher out of context, but I'm pretty damn sure the algorithm should be right, yet it doesn't work properly.

Would it be better to switch to using a bounding box for the character and figure out collision response for that, or does anyone know what the proper equation is for setting the character height on an incline given an X position?

Edit: Here is a picture of me showing the equation works in CAD. The calculator shows me using my equation from above to get the same number as is indicated on the sketch.

# Answer
> 1 votes
Everything is green, so I can't tell what is is a player, what is a block, and what "2" means or is supposed to mean.

I did make you this, however:

The diagram can be mirrored and/or rotated and, with a tweak to the math, match any orientation of collider and collidee. Let me know if this isn't what you need and I'll try again.

These triangles are all in the same proportions; I think the left-most hollow point is a "collision point" so you are given the red, blue, and magenta for that small triangle. If you make blue twice as long, pink will be twice as long, etc.

---
Tags: c++, 2d, collision-detection
---


# Question
Title: Calling an android method from Unity3D with a JAR plugin
I am developing a game with Unity only for Android platform and I am requiring to share content of my game through an intent so I have implemented a JAR plugin according to several tutorials with this code:

```
package a.b.c;

import android.content.Intent;
import android.os.Bundle;

import com.unity3d.player.UnityPlayerActivity;

public class UnityBridge extends UnityPlayerActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void callShareIntent() {
        Intent shareIntent = new Intent (Intent.ACTION_VIEW);
        startActivity(shareIntent);
    }
}

```

The JAR is located at Assets/Plugins/Android with an AndroidManifest file which override the file created by unity, this is its code:

```
<?xml version="1.0" encoding="utf-8"?>
<manifest android:theme="@*android:style/Theme.NoTitleBar" android:versionCode="1" android:versionName="1.0" android:installLocation="auto" package="a.b.c"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" />
    <application android:label="@string/app_name" android:icon="@drawable/app_icon" android:debuggable="false">
        <activity android:label="@string/app_name" android:name="com.unity3d.player.UnityPlayerNativeActivity" android:launchMode="singleTask" android:screenOrientation="portrait" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|fontScale">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
            <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />
        </activity>
        <activity android:name=".UnityBridge"></activity>
    </application>
    <uses-feature android:glEsVersion="0x20000" />
</manifest>

```

I just copied the manifest created by Unity and added this line:

```
<activity android:name=".UnityBridge"></activity>

```

... as you can see.

In the other hand, I have created a C# file in order to launch the share method of the plugin, this is its code:

```
using UnityEngine;
using System.Collections;

public class BotonCompartir : MonoBehaviour {

    AndroidJavaClass androidClass;

    // Use this for initialization
    void Start () {
        if (Application.platform == RuntimePlatform.Android) {
            AndroidJNI.AttachCurrentThread ();
            androidClass = new AndroidJavaClass ("a.b.c.UnityBridge");
        }
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown (0) && Application.platform == RuntimePlatform.Android) {
            androidClass.Call("callShareIntent");
        }
    }
}

```

... and I have attached it to a gameobject.

When I deploy the apk to an android device nothing happens, so What am I doing wrong? Any other suggestion?

Thank you very much

# Answer
> 1 votes
Since you're overriding the Main UnityPlayerActivity your AndroidManifest should look like :

```
<?xml version="1.0" encoding="utf-8"?>
    <manifest android:theme="@*android:style/Theme.NoTitleBar" android:versionCode="1" android:versionName="1.0" android:installLocation="auto" package="a.b.c" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="true" android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" />
<application android:label="@string/app_name" android:icon="@drawable/app_icon" android:debuggable="false">
    <activity android:label="@string/app_name" android:name=".UnityBridge" android:launchMode="singleTask" android:screenOrientation="portrait" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|fontScale">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-feature android:glEsVersion="0x20000" />
</manifest>

```

And to successfully call "callSharedIntent" method from Unity you should get the instance of the Activity first and not only its Class as this is not a static call to a static method. Try this :

```
package a.b.c;

import android.content.Intent;
import android.os.Bundle;

import com.unity3d.player.UnityPlayerActivity;

public class UnityBridge extends UnityPlayerActivity {

public static Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
}

public void callShareIntent() {
    Intent shareIntent = new Intent (Intent.ACTION_VIEW);
    startActivity(shareIntent);
}
}

```

And from Unity :

```
using UnityEngine;
using System.Collections;

public class BotonCompartir : MonoBehaviour {
   #if !UNITY_EDITOR && UNITY_ANDROID
   AndroidJavaClass androidClass;
   AndroidJavaObject androidActivity;

// Use this for initialization
void Start () {
        AndroidJNI.AttachCurrentThread ();
        androidClass = new AndroidJavaClass ("a.b.c.UnityBridge");
        androidActivity = androidClass.GetStatic<AndroidJavaObject>("context");
}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown (0)) {
        androidActivity.Call("callShareIntent");
    }
}

void OnDestroy(){
     if (androidClass !=null) androidClass.Dispose();
     if (androidActivity !=null) androidActivity.Dispose();
}
#endif
}

```

---
Tags: c#, unity, android, eclipse, social
---


title: 2D Box Collision Trouble

text:
# Question
Title: 2D Box Collision Trouble
Hello I am trying to handle some simple box collision (axis-aligned) in my top-down 2d game, but running into a problem.

My game is running at a fixed time step, and checks for player-wall collision on each iteration. It retrieves some collision data (if it collided & what side of the bounding box) and adds some offset (dir) to the players position depending on the overlap amount.

```
// Check player with walls
        CollisionData col = testBoxCollision(m_player->getCollider(), wall.getCollider());
        if (col.isCollided){
            Vec2f dir(0.0f, 0.0f);
            if (col.left)
                dir.x -= (m_player->getCollider().getPosition().x + m_player->getCollider().getHalfSize().x) - (wall.getPosition().x - wall.getHalfSize().x);
            else if (col.right)
                dir.x += (wall.getPosition().x + wall.getHalfSize().x) - (m_player->getCollider().getPosition().x - m_player->getCollider().getHalfSize().x);
            if (col.top)
                dir.y -= (m_player->getCollider().getPosition().y + m_player->getCollider().getHalfSize().y) - (wall.getPosition().y - wall.getHalfSize().y);
            else if (col.bottom)
                dir.y += (wall.getPosition().y + wall.getHalfSize().y) - (m_player->getCollider().getPosition().y - m_player->getCollider().getHalfSize().y);

            m_player->GameObject::setPosition(m_player->GameObject::getPosition() + dir);
        }

```

The testBoxCollision function:

```
CollisionData testBoxCollision(const Collider& a, const Collider& b)

```

{ CollisionData c{ false, false, false, false, false };

```
float w  = a.getHalfSize().x + b.getHalfSize().x;
float h  = a.getHalfSize().y + b.getHalfSize().y;
float dx = a.getPosition().x - b.getPosition().x;
float dy = a.getPosition().y - b.getPosition().y;

if (abs(dx) <= w && abs(dy) <= h)
{
    c.isCollided = true;

    float wy = w * dy;
    float hx = h * dx;

    if (wy > hx)
    {
        if (wy > -hx)
            c.bottom = true;
        else
            c.left = true;
    }
    else
    {
        if (wy > -hx)
            c.right = true;
        else
            c.top = true;
    }
}
return c;

```

}

**The Problem**

When two walls produce a corner, and I push my player up to the corner, the player goes through the wall. Not Ideal!

Clearly I've overlooked something and another set of eyes would be very helpful. Thanks.

Below is a snapshot of what's happening.

EDIT: I'm led to believe this is a math error, because it only happens on some corners at a consistent frame rate.

# Answer
Ok so I found the solution, and thanks for you replies.

The line`m_player->GameObject::setPosition(m_player->GameObject::getPosition() + dir);` was only updating the gameobjects position variable, this variable only took effect on the gameobjects update. Which why of course it worked when there was only one wall. But with a second wall, it would override the objects new position determined by the first wall. So I simply update the players position immediately.
> 1 votes

# Answer
A *possible* explanation for this is unrelated to the corners: to determine whether it's colliding left or right, or if it's colliding up or down, instead of checking how far inside the player's hitbox is within the wall you should *check the direction of the player's movement*.

It would go more along these lines:

```
    CollisionData testPlayerCollision(const Player& player, const Wall& wall) {
        CollisionData c{ false, false, false, false, false };

        if (player.getCollider().intersects(wall.getCollider())) {
            c.isCollided = true;

            if (player.isMovingRight()) {
                c.left = true;
            }
            else c.right = true;

            if (player.isMovingDown()) {
                c.up = true;
            }
            else c.down = true;
        }

        return c;
    }

```
> 1 votes

# Answer
```
if (col.left)
   dir.x += (wall.getPosition().x + wall.getHalfSize().x)
   - (m_player->getCollider().getPosition().x - m_player->getCollider().getHalfSize().x);
else if (col.right)
   dir.x -= (m_player->getCollider().getPosition().x + m_player->getCollider().getHalfSize().x)
   - (wall.getPosition().x - wall.getHalfSize().x);

```
> -1 votes

---
Tags: c++, collision-detection, game-design, mathematics, sfml
---


# Question
Title: How to get the MonoGame Templates working with Visual Studio C# 2013 Express?
I've been looking around forever, and I can't seem to find a way to install the MonoGame C# Templates for Visual Studio 2013 Express. These include things like "SpriteFont", etc. that pop up in the templates menu when you click "Add New Item" in the solution menu. I've installed every last MonoGame related thing I can find on the internet and NOTHING has solved my problem.

To clarify, I have all the *project* templates that come with MonoGame:

but I'm missing all the item templates:

There should be templates in the list there labelled "SpriteFont" and other miscellaneous MonoGame related templates.

So how do I get the MonoGame templates?

**EDIT:** For the record, I have already tried following the advice given here, here, here, here, here and here. I also learnt from the 5th link that apparently I don't have the MonoGame template projects for things like "Empty Content Project" either.

**EDIT 2:** This didn't work either.

**EDIT 3:** I've also followed the advice here, yet again to no avail (what a surprise!).

# Answer
> 2 votes
You have to download the templates for the Monogame content project. You have to install the XNA game studio 4.0 because Monogame content pipeline uses the XNA pipeline under the hood.

The file `XNA Game Studio 4.0.vsix` is the template installer for visual studio 2013.

---
Tags: monogame
---


# Question
Title: How to quickly create meshes that have cutouts of other meshes?
I have a mesh and I would like to quickly create planes (or boxes) that have cutouts in the shape of the silhouette that mesh, but rotated at various angles. I would like to have a system to which I can feed any mesh and it will output these cutout planes, either for random or predefined rotations of the mesh.

In the game I'm making, you have a 3D object, like a chess piece, that you rotate and translate to try to fit it in a hole in a wall that has the shape of the object. But the hole can be in the shape of any rotation of that object. For instance, in the case of a pawn, the hole can look like an upright pawn, so you wouldn't have to rotate the pawn at all; or it could just be a circle the size of the base of the piece, so you would have to rotate the pawn so it either goes in feet or head first. I want a program to procedurally generate walls with these kinds of holes for any mesh I give it.

# Answer
What you are describing is performed by the GPU every time 3d geometry is drawn onto the screen. The 3d points must be translated to 2d positions. You can do this translation manually, and then construct a mesh from the resulting points.

1. Multiply each vertex position from the object by a projection matrix. This will yield all the points within a 2d plane.
2. Filter the set of points to only those that make up the convex hull of their outline.
3. Generate a "hole" mesh from the outline points. Details for implementing this step depend entirely on your goals for project.

You could carry out this procedure for a predefined or random set of rotations by constructing the projection matrix for those rotations. You could implement this procedure in any language you choose. And because you only have to generate the mesh once rather than every frame, you conceivably could do it at runtime within your game (for example, in a loading screen).
> 1 votes

---
Tags: 3d-meshes
---


title: SFML drawing Tiles low fps

text:
# Question
Title: SFML drawing Tiles low fps
```
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!");
sf::VertexArray Tquad(sf::Quads, 40*40*4);
int size{ 20 };
int width{ 40 };
for (int x = 0; x < width; x++)
{
    for (int y = 0; y < width; y++)
    {
        sf::Vertex* quad = &Tquad[(x + y * width) * 4];
        quad[0].position = sf::Vector2f(x, y);
        quad[1].position = sf::Vector2f((x+1)*size, y);
        quad[2].position = sf::Vector2f((x+1)*size, (y+1)*size);
        quad[3].position = sf::Vector2f(x, (y+1)*size);
    }
}

while (window.isOpen())
{
    sf::Event event;

    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }

    window.clear();
    window.draw(Tquad);
    window.display();
}

return 0;

```

}

Hello , im getting very low fps with only 40x40 tiles, in release mode i get 21 fps. If i disable the window.draw i get 2000+- fps.

# Answer
> 1 votes
found the solution. quad\[0\].position = sf::Vector2f(x, y); quad\[0\].position = sf::Vector2f(x*size, y*size);\* now fps is like 1100

---
Tags: c++, graphics, performance, tilemap, sfml
---


# Question
Title: XNA game publishing help with incompatibilities via content built at runtime
MY XNA game is finally complete, but I'm having difficulty getting it to run on other Windows computers. I've read similar other stackexchange topics here, here, and here, but I'm still gonna need help on the specifics of my particular program.

I'm using XNA 4.0 in Visual Studio 2010 on a Windows 7 Professional 64-bit machine. The game was done in C#. I've made release builds on my machine and they work great.

I don't care about Windows XP or Windows Vista. I'm only targeting Windows 7 and Windows 8, 32- and 64-bit. **I could not get my game to run properly on them.** The game always crashes at startup, either silently or with a crash message.

So I discovered that the ClickOnce publisher/installer will supposedly ensure that the prerequisites (such as .Net 4.0 and XNA Redistributable) get put on the target machine. However, I found that microsoft says here: "Also, the XNA Framework Redistributable file does not contain the Content Pipeline Build Runtime. Building content at run time is supported only when XNA Game Studio has been installed on the Windows-based development computer."

This leads to a problem. I'm pretty sure my game does in fact build content at runtime because there is only one music resource that loads different music files at different times. Here is the code.

```
public void scr_play_song(byte s)
{
    if (SEI_MSC != null)
        SEI_MSC.Stop();

    if (s == 1)
    {
        System.IO.FileStream fs = new System.IO.FileStream(@"Music\msc01_Legend.wav", System.IO.FileMode.Open);
        TG.MUSIC = SoundEffect.FromStream(fs); // TG.MUSIC is a SoundEffect class
        fs.Dispose();

        SEI_MSC = TG.MUSIC.CreateInstance(); // SEI_MUSIC is a SoundEffectInstance class
        SEI_MSC.IsLooped = true;
        SEI_MSC.Volume = vol_music;
        SEI_MSC.Play();
    }
    else if (s == 2)
    {
        // same stuff for other music files, etc
    }
}

```

However, I could be mistaken, so: **is this actually building content at runtime? Or is it just loading/streaming into an already-existing resource?**

Before you ask, yes I'm using .wav files for music because .mp3 files are proprietary that charge an absurd license fee ($2,500 last I checked). Sadly in addition, I cannot let my .wav music files be normal resources that turn into .xnb files, because they total over 300 MB, which is too big of a download. Therefore, my installer will come with ogg vorbis files that then get decompressed into .wav files.

(BTW ive come across "solutions" where you can get .ogg natively working in XNA, but they were some real "hack" jobs in my experience and I have serious concerns that such "solutions" will add another layer of incompatibility.)

**If someone has a better idea how to go about music, please let me know.**

OK so now let me list all the references in my game:

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Storage;
using System.IO;

```

And from the References tree in my game project, there's also:

Microsoft.Xna.Framework Microsoft.Xna.Framework.Avatar Microsoft.Xna.Framework.Game Microsoft.Xna.Framework.GamerServices Microsoft.Xna.Framework.Graphics Microsoft.Xna.Framework.Net Microsoft.Xna.Framework.Storage Microsoft.Xna.Framework.Video Microsoft.Xna.Framework.Xact mscorlib System System.Core System.Net System.Xml System.Xml.Linq

(I may need to remove some of these tho. I can't imagine where Framework.Video came from cuz i'm not using any video files at all. I've also heard bad incompatibility things about Framework.GamerServices. My game does NOT use the internet at all.)

Based on this list, **can someone confirm that the only things my target machines will need are .Net 4.0 and XNA Redistributable?**

Besides loading music at runtime, the only other "special" thing my game does is read/write to a file for the purposes of saving level progress. Here's the code:

```
    public void scr_load_progress()
    {
        if (File.Exists("Progress") == false)
        {
            scr_save_progress();
            return;
        }

        LevelData = File.ReadAllLines("Progress");

        for (int i = 0; i < ASZ; i += 1)
        {
            LevelDones[i] = LevelData[i].ElementAt(0) - '0';
        }
    }

    public void scr_save_progress()
    {
        File.WriteAllLines("Progress", LevelData);
    }

```

My game does not do anything else "special" as far as I know. It does not use the internet at all.

There's one more undesirable thing about ClickOnce publishing. It looks like I can't insert my own EULA (the legal agreement you have to accept) in it. This is why I'm using InnoSetup and would prefer to continue with it. I suppose I could use both and just let the Inno Installer call the setup.exe from ClickOnce, but that still doesn't get me around the other issue about building content at runtime.

At this point, I've considered moving this game to Mono or MonoGame (i have no idea what the difference is), but my deadline is fast approaching and I've never touched Mono and have no idea how difficult it will be to port my game. Plus i've already come across Mono topics about similar troubles with exactly what prerequisites are needed on target machines and how to get them installed.

Sorry for the many paragraphs but there were a lot of specifics I needed to list. I hope someone can help. **To summarize:**

**Does my music code actually build content at runtime, or does it just load/stream?**

**Based on my list of references, will a ClickOnce setup.exe ensure the necessary prerequisites are installed?**

Thanks in advance. I really miss the good old days where programs only ever called external .DLLs so you could just copy them in the same folder as the .exe, which has the added benefit of letting the developer (and user) easily see EXACTLY what dependencies there are. Oh well.

# Answer
The following worked for Monogame. You can copy the .dlls to your game folder (the content folder is probably a better choice), then reference them and delete the old references, like I do below. You can take the exact same logic and apply it for `Microsoft.Xna.Framework.dll`, and every other Xna related .dll you are referencing. For Xna, all the .dlls are in this path for me `C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\`.

I copied the game folder, double clicked the .exe and my game opened on a fresh installed windows 7 64-bit computer.
> 1 votes

---
Tags: xna, xna-content-pipeline
---