# Question
Title: Sprite disappears after adding a material to it
I have background which is FirsLayer, order in layer 0 and platform over it which is FirstLayer, order in layer 1.

Once I add a material to the platform, the layer doesn't seem to change but it gets rendered behind the background.

The material that I add:

1)Why do I get such results?

2) How can I add the material to the platform and still keep it above the background?

P.S. For further clarification if somebody didn't understand, I expected the sprite to stay on its original position(i.e. not to go behind the background when a material is being added to it)

# Answer
1) Because if you want to use the sorting layers in unity, you can't use many of the materials that are available but only a few.

2) You're limited to only a few materials, which work in harmony with unity's sorting layers.

Cheers!
> -1 votes

---
Tags: unity, sprites, materials
---


# Question
Title: Why is OnCollisionEnter2D called when it's layer's collisions are being ignored?
I'm sure this is down to my lack of understanding of the unity physics system.

I'm trying to implement a simple one-way platform for a 2d game and have got stuck on creating a reliable way to let the character 'drop down' from a platform on pressing the down arrow.

While trying to debug and whittle down the code, I've found myself with this strange debug script:

```
using UnityEngine;
using System.Collections;

public class DebugPlatform : MonoBehaviour
{

    void OnCollisionEnter2D(Collision2D other)
    {
        if(Physics2D.GetIgnoreLayerCollision (other.collider.gameObject.layer, this.gameObject.layer))
            print ("ERROR: How does this happen?!!");
        else
            print("This is normal.");
     }
 }

```

When I place this on my one way platform and mess about in game, sometimes the character refuses to drop down on command, and the error message is printed.

From what I understood, GetIgnoreLayerCollision returned whether the collisions between the layers were being ignored or not.

So my questions are:

* Why is OnCollisionEnter2D being called even though the layers are supposed to be ignored?
* Is this ignore value just a request, not absolute? Maybe some collision optimization that I have to override?
* I can't imagine this is some multi-threading issue, as the error appears regularly, after I do a normal jump on the platform.
* Am I doing something completely wrong?

EDIT: Extra info: The one way platform is two parts, first an if else in FixedUpdate in the player script:

```
// Don't collide with platforms if flag is set or we are moving up:
if (ignorePlatform || transform.rigidbody2D.velocity.y > 0f)
    Physics2D.IgnoreLayerCollision (PlayerLayerID, PlatformLayerID, true);
else if(transform.rigidbody2D.velocity.y <= 0f)
    Physics2D.IgnoreLayerCollision (PlayerLayerID, PlatformLayerID, false);

```

The platform has an EdgeCollider2D on the top and a child with a Collider2D trigger underneath. A script then resets the player's ignorePlatform to false on exit. This is to make sure the player only falls through one platform when the down arrow is pressed.

# Answer
> 1 votes
Unity 5 adds the PlatformEffector2D component, which I think solves this same question.

If you add a collider and attach it to this effector, you should be able to create the one-way platform with less fuss, which would simplify the code for dropping down, as well.

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


# Question
Title: How to make legacy animations run in Unity in unscaled time? (Pause game related)
I'm relatively new to Unity, and I've been having a very difficult time getting the legacy animations to run in unscaled time. I need to pause my game, and as soon as it pauses, I need to have my boxes for the pause screen come in from the side. This sort of works if I use an IEnumerator, but I have to hard-code exactly how long it will take for the animation to come in (.333f seconds) and the game will not pause until the animation fully shifts in.

The major problem with this is that I need to use more moving animations while the game is paused that will be called using the onClick() methods in the pause game's buttons. Think of my pause menu as somewhat like an old-school RPG's menu like Final Fantasy but with moving GUI animations. Now, I know that unscaled time is the key to solving this issue, but every explanation I've found online seems to involve the Animator which refuses to work with the legacy? animations. Either that, or the code they're using makes little sense to me because it may be above my level of comprehension. Here is what I have as it stands (\*note that I have some deltaTime and \_lastframetime code but I have no idea how to make use of it):

```
// Update is called once per frame
void Update () {
    deltaTime = Time.realtimeSinceStartup - _lastframetime;
    _lastframetime = Time.realtimeSinceStartup;

    //Press T or Tab to pause the game
    if (Input.GetKeyDown(KeyCode.T) || Input.GetKeyDown(KeyCode.Tab)) {
        //If not currently paused, then stop time and show the GUI
        if (!pauseGame) {
            Debug.Log("Tab/T properly pressed to pause game.");
            pauseGame = true;
            showGUI = true;
            StartCoroutine(Wait(.333f)); //IEnumerator Wait, then stops
        }else if (pauseGame){
            Debug.Log("Tab/T properly pressed to UNpause game.");
            Time.timeScale = 1;
            pauseGame = false;
            showGUI = false;
        }

        //If we are to show the GUI, play the start animation; otherwise, the exit one
        if (showGUI == true) {
            //startMenuCanvas.animation.
            startMenuCanvas.animation.Play ("pause_menu_anim1");
        } else {
            startMenuCanvas.animation.Play ("pause_menu_anim1_exit");
        }
    }
}

IEnumerator Wait(float seconds){
    Debug.Log ("Waited for " + seconds + " seconds.");
    yield return new WaitForSeconds(seconds);
    Time.timeScale = 0;
}

```

Ideally, I want to remove the IEnumerator and be able to call the Play animations using unscaled time. Is there any simple way to do this that I am missing?

# Answer
I've faced similar issue, and after digging around I found this. Hopefully, its useful for you

ref: http://answers.unity3d.com/questions/217351/animations-ignore-timescale.html
> 1 votes

# Answer
Use Finite State Machine to switch between various states. Easy way around is to create a flag to control what things are updated when game is paused. Alternatively if you want to use Time.timeScale you can set up your own custom deltaTime by taking difference of previously recorded Time.realtimeSinceStartup from the current one.
> 0 votes

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


# Question
Title: Observer pattern for clickable 2D Elements?
So i am currently thinking about the best way to handle and implement clickable 2D menu elements in a very simple DirectX Game. I very much like the idea of having subscribers to a event where they are getting notified (e.g. the mouse click).

My question now is: Where and how do i determine which subscriber gets notified by a mouse click? Does the publisher know about all the positional data of the subscribers? Should the publisher just notify all 2D menu elements, so that they need to handle this event (check if the clicked position intersects with their own dimension)? Is this even a good idea?

As already stated, this will be a very basic game, so performance should not be any real issue yet. Still i always like to use some of the best practices, so i will at least learn some part of it (thus i will not implement a complete GUI system, only the subscriber part).

Thank you!

# Answer
Some informal thoughts, specifically about clickable menu items...

1. You're 100% correct to not worry much about performance here.
2. Menus are typically stateful, navigating a tree of states. So it may make more sense to alert a "menu node" which which of the several choices they made. At the individual button/item level, they could know their 2d boxes, and sure asking each one "was it you, at xy?" is just fine. Since you'll have probably \< 100 menu items to click on at any time.
3. Often at the end of a menu is something more interactive, like "enter your name" or the game starts playing or such.

For clickable areas that aren't menus, if there's not many, it's probably still fine to ask each one for each click, "would you like to handle this click?".

On the other hand, to handle clicks on thousands of quickly-moving sprites, a different approach would be indicated.
> 1 votes

---
Tags: directx, design-patterns, menu
---


title: Map building grid to planet

text:
# Question
Title: Map building grid to planet
I'm trying to build a space game and one of the key parts is building on spherical planet. I want the buildings to be build on a grid (some building are 1x1, some 6x4,..., kinda like StarCraft). My problem is, I can't seem to find a way to build the buildings near poles, while maintaining properly oriented grid.

I think that joining cells near poles is a bad idea, because there will be parts, where 1 cell is continued by 2 cells and it will be impossible to build over these parts.

Any ideas how to solve this? Should I forget about the grid and just check, if the building collides with other buildings?

# Answer
> 3 votes
I can suggest to use a quad sphere

# Answer
> 1 votes
Introduce polar caps where there is no square grid and player can't build. Buildable areas will be ring-shaped alike in Civilization.

Topological representation:

# Answer
> 1 votes
The quad sphere is good, but I'd like to throw another suggestion in the ring. Let's say you want a hex grid on a planet. Hex grids are all sorts of useful for strategy games. How do you do that?

In the same way that a cube, subdivided, then projected to a sphere gives you a square grid on the surface of the sphere, you can take an icosahedron, subdivide it, and project it to the surface of a sphere. There'll be some pentagons in the mix, but otherwise it has all the properties of a hex grid.

It's called a Geodesic Grid and it's used a lot in climate science. It's annoyingly more complicated, but hex grids are cool :)

There's some good resources at the BUGS site.

---
Tags: grid, planet
---


title: Free camera rotation in 3D space

text:
# Question
Title: Free camera rotation in 3D space
I'm using a view matrix to do camera movement and rotation.

```
viewMatrix = new Matrix4f();
viewMatrix.setIdentity();
Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), viewMatrix, viewMatrix);
Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), viewMatrix, viewMatrix);
Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), viewMatrix, viewMatrix);
Matrix4f.translate(new Vector3f(x * (-1), y * (-1), z * (-1)), viewMatrix, viewMatrix);

```

I'm manipulating the rotation values around each axis here:

```
//left and right
public void rotateY(float amount)
{
    ry += amount;
}

//Up and down
public void rotateUp(float amount)
{
    rx += amount;
    if(rx < -90)
        rx = -90;
    if(rx > 90)
        rx = 90;
}

```

This all works fine. Now i'm trying to create a more "free" camera so that i always turn left an right and don't simply rotate around the Y-Axis.

For the rotation up you simply remove the if-cause. But for the rotation sidewards you need to calculate the parts for the x- and the z-axis using sin and cos. That's where i get confused. How can i rotate sidewards correctly?

# Answer
Generally, whether you rotate around "local Y" or "world Y" depends on the order you apply the rotations.

If you're "free flying", then your variable `ry` no longer has a specific meaning, because all the moves are cumulative.

You can keep a matrix, and apply successive rotations and translations to it to fly around. After a long while, there can be cumulative arithmetic errors, and you may need to renormalize the matrix, which is to make sure that the upper 3x3 rotation portion has 3 unit basis vectors at right angles to each other. (This is what I'm doing currently in my project.)

You can also represent rotations as quaternions, which is more stable but introduces a small handful of other math to also understand.
> 1 votes

---
Tags: opengl, camera, rotation, lwjgl
---


# Question
Title: GLFW / OpenGL location and size in pixels
I'm using GLFW to create a little game. (and by little, I mean: small, nonprofit)

After a while of puzzling, I found out that this draws a texture (from an image, for instance) to the screen:

(the syntax is in Go, but the library is the same as the C/C++ version)

```
gl.BindTexture(gl.TEXTURE_2D, tex)
gl.Color4f(1, 1, 1, 1)

gl.Begin(gl.QUADS)

gl.Normal3f(0, 0, 0)

gl.TexCoord2f(1, 1)                     // top right
gl.Vertex3f(1, -1, 0)

gl.TexCoord2f(0, 1)                     // bottom right
gl.Vertex3f(-1, -1, 0) // = location

gl.TexCoord2f(0, 0)                     // bottom left
gl.Vertex3f(-1, 1, 0)

gl.TexCoord2f(1, 0)                     // top left
gl.Vertex3f(1, 1, 0)

gl.End()

```

This draws the texture perfectly. There is just one downside: as my screen is 16:9, the texture also gets rendered/displayed as 16:9. But as this is a square image (32 by 32 pixels), **how do I get it to draw just those pixels, instead of defining it relative to the screen ratio**? (values between -1 and 1)

My first assumption was that I can compute what the values should be, by comparing it with the actual screen size, but this feels like it's not the way to go.

# Answer
> 2 votes
**CLARIFICATION**

`glViewport` will set the size of your viewport you are rendering to. This answer assumes that you were doing something along the lines of this:

```
glViewport(0, 0, 1920, 1080);

```

Which would give you a 16:9 aspect ratio. Setting it to something like:

```
glViewport(0, 0, 800, 600);

```

Would give you the correct aspect ratio (and hopefully answers your question). It would be incorrect to do something along the lines of:

```
glViewport(0, 0, 32, 32);

```

As this will only render to a small portion of the screen. If this is what you actually want then that's fine.

If you want to render the 32x32 texture to part of the screen, for example as a character sprite that can run around, then you need to look into using transform matrices.

Using matrices mean instead of trying to calucate where the sprite should be in relative to the screen size, you just apply a transform that moves the sprite 'into the background'.

This is all covered in the tutorial site I linked.

P.S Please try to stay away from using deprecated features such as `glLoadIdentity`, `glTranslatef`, `gl.Vertex3f`, etc.

---

**ORIGINAL**

Your solutions is `glViewport`.

You can specify the last two arguments with size of the viewport.

As for your comment GLFW only supplies you with a window with a OpenGL context. Doing anything more that requires something like rendering in different aspect ratios requires you to use OpenGL.

I highly recommend this OpenGL tutorial site to get you started on modern (3.3+) OpenGL, and as a bonus it uses GLFW too!

# Answer
> 1 votes
You want to draw a 32x32 sprite, right?

If so, **Don't do what @Soapy said and don't call `glViewport()` to draw each sprite in your game!**

It probably will be very slow and it is not how you should make your graphics. It's like buying a new hammer each time you want to hammer a nail.

Yes, it may work, but it's not the good way. You can't rotate sprites with this technique, you can't make 3D with it, you can't draw triangles with it.

You should call `glViewport()` **once** every time your window is resized to provide the new window size to OpenGL.

---

What you should do instead is to read about `glLoadIdentity()`, `glScale()`, `glTranslate()` and similar functions. They will allow you to do what you want. For example, if you call this set of functions once

```
gl.LoadIdentity();
gl.Translatef(-1,-1,0);
gl.Scalef(2.0f/WindowWidth,-2.0f/WindowHeight,0);

```

then you can use

```
gl.Begin(gl.QUADS)

gl.TexCoord2f(0, 1)                     // top right
gl.Vertex3f(0, 32, 0)

gl.TexCoord2f(1, 1)                     // bottom right
gl.Vertex3f(32, 32, 0)

gl.TexCoord2f(0, 1)                     // bottom left
gl.Vertex3f(0, 32, 0)

gl.TexCoord2f(0, 0)                     // top left
gl.Vertex3f(0, 0, 0)

gl.End()

```

to draw a 32x32 square in a top-left corner of your screen. Makes more sense that computing coordinates relative to the screen each time, isn't it?

Tell me if something from my answer does not work, I will try to help.

---
Tags: opengl, glfw
---


# Question
Title: Game networking, limiting amount of movement packets
I have been developing a server/client model for a game project I am working on. Everything works great, client side prediction works, server reconciliation works. Basically, the character can move smoothly without any hiccups.

However, the problem is that I am currently not using frame independent movement, it doesn't rely on the elapsed time between updates. Every time a movement packet is received, it will move the character x amounts of pixels. The packets are gathered on the client with a certain rate.

If someone were to modify the rate so that it would gather it faster, that means it would send more packets and make it move faster. Essentially, they would be speed hacking.

How would I go about preventing this behavior. If I try to add frame independent movement, server reconciliation doesn't work any longer since it doesn't know how much to move it after the server correction was received. Is the best way to just limit how many movement packets that can be received server side per second?

I have been reading the source networking article, but they do not mention anything about this as far as I can see.

By the way, when I send these packets, I do not send them as they are gathered, rather I send them bunched together at another rate, to reduce bandwidth.

Edit: I think I was a little bit unclear about my packets. My packets contain user commands that holds the current state of the keyboard, mouse and whatever else is collected. The server receives the packet, which can hold MORE THAN 1 user command, as it sends the pakcets at a slower rate than the commands are collected. This is exactly what is described in the source networking article. The server receives the packet and handles ALL user commands as soon as it is received, thus if the packet contains a lot of user commands (the client modified the rate of which it collects them, or duplicated them) the server will move it more than intended. Modifying how often it sends the packets doesn't matter, but the gathering of the user commands does.

Let's say the server sends the packets every 100ms, and collects the commands every 50ms. That means every packet will hold 2 user commands. But if someone modifies the collection rate to, say every 10ms. Every packet will contain 10 user commands which would move the character further since the server moves it for every user command.

# Answer
I would suggest making a separate buffer for each player that is responsible for squashing commands together.

Basically, it should reduce a set of network packets into an approximation of user's input, which is sampled **only once** per game update that should result in equally significant change for every player.

The question is, what should be sampled from the state and what strategy to use for squashing commands together.

For instance, if the player were to send one of WASD events, you could build up a vector of his movement and sample its direction, resetting the vector back to 0 after that to accept new input. Like, having received DDWSWW the sampler would output `pi/4` degrees as a direction of vector `(2; 2)`, and you would move the player in the given direction, same distance for everyone. Of course, this example is primitive and suits hardly any game, but the pattern is quite generic.

You can employ more sophisticated strategies with squashing commands, like leaving a tiny fraction of the previous input sample to apply further incoming commands on top of it, much like smoothing the movement. There's a lot to play with there.
> 2 votes

# Answer
Your game shouldn't depend on the speed at which the packets are sent as it will vary depending on your internet connection regardless of what rate you attempt to send them.

Instead your server should move the character depending on the user actions (e.g. while they are pressing (sending) W move them forward, or if you are counting mouse clicks then send how many times they clicked since the last packet was sent).

Depending on how many movement packets a client has sent is simply too unreliable.
> 1 votes

---
Tags: networking, movement, synchronization, packet
---


# Question
Title: LibGDX collision with rectangle and circle
I have 2 objects, A and B, both are classes with only values, so positions and dimensions are only values (float posX,posY).

I have a render class which render A and B with shapeRenderer; A is rendered as a rectangle and B as a circle, how could check if there is a collision ?

**edit:** I have a rectangle coming from up, when it hits the circle I have to stop the game

# Answer
This is what I use to check collision between circle / rectangle. Note that this doesn't do `continuous collision detection`. Which means that if both of the *shapes are unproportionally small* or the objects are colliding with *really high speeds* (because you have too low fps and you use Delta Time to calculate the velocity for example), then the collision won't be detected.

```
static public Boolean CircleRectCollision(Vector2 circleCenter, Vector2 rectCenter,
    float radius, float width, float height)
{
    float distanceY = Math.Abs(circleCenter.Y - rectCenter.Y);
    if (distanceY > (height / 2 + radius)) return false;

    float distanceX = Math.Abs(circleCenter.X - rectCenter.X);
    if (distanceX > (width / 2 + radius)) return false;

    if (distanceX <= (width / 2)) return true;
    if (distanceY <= (height / 2)) return true;

    float a = distanceX - width / 2;
    float b = distanceY - height / 2;
    float cSqr = a * a + b * b;
    return (cSqr <= (radius * radius));
}

```
> 1 votes

---
Tags: libgdx, collision-detection
---


# Question
Title: how to detect same keyboard key press only once
I am designing a keyboard class that can detect the keyboard key press only one time but I still cannot figure out the way to do it. My goal is just check and perform the action only once when the same key is keep pressing or keep holding and no action performed when 2 action keys are pressed at the same time. For example, when I keep pressing or holding key A, action 1 is only perform once. Then I keep pressing or holding another key B, action 2 is also perform once. I cannot peform any action if I press key A and B at the same time.

There is two class inside KeyboardClass header and cpp file i.e. KeyboardClientClass and KeyboardServerClass.

```
////////////////////////////////////////////////////////////////////////////////
// Filename: KeyboardClass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _KEYBOARDCLASS_H_
#define _KEYBOARDCLASS_H_

////////////////////////////////////////////////////////////////////////////////
// Class prototype
////////////////////////////////////////////////////////////////////////////////
class KeyboardServerClass;

////////////////////////////////////////////////////////////////////////////////
// Class name: KeyboardClientClass
////////////////////////////////////////////////////////////////////////////////
class KeyboardClientClass
{
public:
    KeyboardClientClass( const KeyboardServerClass& KeyboardServer );
    ~KeyboardClientClass();
    bool KeyIsPressed( unsigned char keycode ) const;
    bool KeyIsPressedOnce( unsigned char keycode );

private:
    unsigned char tempKeyCode;
    const KeyboardServerClass& server;
};

class KeyboardServerClass
{
    friend KeyboardClientClass;

public:
    KeyboardServerClass();
    ~KeyboardServerClass();
    void OnKeyPressed( unsigned char keycode );
    void OnKeyReleased( unsigned char keycode );

   private:
        static const int nKeys = 256;
        bool keystates[ nKeys ];
        bool isKeyDown;
    };

    #endif

////////////////////////////////////////////////////////////////////////////////
// Filename: KeyboardClass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "KeyboardClass.h"

KeyboardClientClass::KeyboardClientClass( const KeyboardServerClass& KeyboardServer )
: server ( KeyboardServer )
{
    tempKeyCode = 257;
}

KeyboardClientClass::~KeyboardClientClass()
{}

bool KeyboardClientClass::KeyIsPressed( unsigned char keycode ) const
{
    return server.keystates[ keycode ];
}

bool KeyboardClientClass::KeyIsPressedOnce( unsigned char keycode )
{
    if ( tempKeyCode != keycode )
    {
        tempKeyCode = keycode;
        return server.keystates[ keycode ];
    }
    else
    {
        return false;
    }
}

KeyboardServerClass::KeyboardServerClass()
{
    for ( int x = 0; x < nKeys; x++ )
    {
        keystates[ x ] = false;
    }
}

KeyboardServerClass::~KeyboardServerClass()
{
    isKeyDown = true;
}

void KeyboardServerClass::OnKeyPressed( unsigned char keycode )
{
    keystates [ keycode ] = true;
    isKeyDown = false;
}

void KeyboardServerClass::OnKeyReleased( unsigned char keycode )
{
    keystates [ keycode ] = false;
    isKeyDown = true;
}

```

Firstly, I create the a KeyboardServer object to keep track of the keyboard messgae from Windows Procedure.

```
LRESULT CALLBACK SystemClass::MessageHandler( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch ( msg )
    {
        //************ KEYBOARD MESSAGES ************ //

        // Check if a key has been pressed on the keyboard
        case WM_KEYDOWN:
        {
            if ( wParam == VK_ESCAPE )
                PostQuitMessage( 0 );

            // If a key is pressed send it to the KeyboardServer object so it can record the state
            m_KeyboardServer.OnKeyPressed( wParam );
            break;
        }

        // Check if a key has been released on the keyboard
        case WM_KEYUP:
        {
            // If a key is released then send it to the KeyboardServer object so it can unset the state for that key
            m_KeyboardServer.OnKeyReleased( wParam );
            break;
        }

        // ************ END KEYBOARD MESSAGES ************ //
}

```

Then, I create a KeyboardClient object at Game class to check whether a key has been pressed or not and perform the action based on key pressed.

```
if ( m_Keyboard.KeyIsPressed( KEY_B ) )
    // Do action A
else if ( m_Keyboard.KeyIsPressed( KEY_N ) )
    // Do action B

```

# Answer
Pseudo code:

```
currentKeyboardState
previousKeyboardState

void UpdateInput()
    store currentstate to previousstate
    get new state to currentstate

```

Now that we have stored the last state and we know the current state, we can check if key was NOT pressed in last frame and is now pressed. So we know if key was pressed down just now.

```
if(currentKeyboardState.KeyIsPressed( KEY_B ) && !previousKeyboardState.KeyIsPressed( KEY_B ))

```

We can also detect if key is being held down, by checking if it was down last frame and now.

```
if(currentKeyboardState.KeyIsPressed( KEY_B ) && previousKeyboardState.KeyIsPressed( KEY_B ))

```

Checking if key was down last frame, but is not anymore, we can say that it was released.

```
if(!currentKeyboardState.KeyIsPressed( KEY_B ) && previousKeyboardState.KeyIsPressed( KEY_B ))

```

With these, i think you can create what you need.

**TL;DR;**

Store previous keyboard state, so you can compare current state to previous state and determine if something fishy is going on.
> 1 votes

# Answer
When you detect the WM\_KEYDOWN message, you can use the bits in the LPARAM argument in your message handler to determine if the key stroke is **repeated** and also what the key's **previous state** was.

Store if the key is **repeated** as well as **pressed/released**. When you keep pressing or holding key A, only perform action 1 if the **repeat count** is 0.

```
if ( m_Keyboard.KeyIsPressed( KEY_A ) && !m_Keyboard.KeyIsRepeated( KEY_A ) )
    // Do action A

```

*Note*: If the keystroke is held long enough, multiple messages are sent which might change the repeat count.

To cancel out keys A and B, you can add up a count of the number of keys pressed that you want to be exclusive of each other in your keyboard client and only perform the action if there is a total of 1 key pressed.
> 0 votes

# Answer
What you can do is store boolean values for if the key was down or released and create some simple getters, a setter, and a "resetter" like so:

```
struct Key
{
    bool down;
    bool released;
    bool pressed;
};
bool KeyInput::IsKeyDown(uint32 keyCode)
{
    return s_keys[keyCode].down;
}

bool KeyInput::WasKeyPressed(uint32 keyCode)
{
    return s_keys[keyCode].pressed;
}
bool KeyInput::WasKeyReleased(uint32 keyCode)
{
    return s_keys[keyCode].released;
}

void KeyInput::SetKey(uint32 keyCode, bool isDown, bool isReleased, bool isPressed)
{
    s_keys[keyCode].down = isDown;
    s_keys[keyCode].released = isReleased;
    s_keys[keyCode].pressed = isPressed;
}

void KeyInput::ResetKeys()
{
    for (int i = 0; i < NUM_KEYS; i++)
    {
        s_keys[i].released = false;
        s_keys[i].pressed = false;
    }
}

```

Then in your WM\_KEYDOWN and KEYUP handles:

```
case WM_KEYUP:
{
    bool wasDown = ((lParam & (1 << 30)) != 0);
    KeyInput::SetKey(wParam, false, wasDown, false);
}
break;
case WM_KEYDOWN:
{
    bool wasDown = ((lParam & (1 << 30)) != 0);
    bool isDown = ((lParam & (1 << 31)) == 0);
    KeyInput::SetKey(wParam, isDown, false, !wasDown && isDown);
}
break;

```

And then finally before you handle the messages you call the reset function, and everything after your message handling would be your game loop, so something like:

```
        while (g_running)
        {
            KeyInput::ResetKeyReleased();

            MSG message;
            while (PeekMessage(&message, 0, 0, 0, PM_REMOVE))
            {
                if (message.message == WM_QUIT)
                    g_running = false;
                TranslateMessage(&message);
                DispatchMessageA(&message);
            }

            if (KeyInput::IsKeyDown('W'))
                OutputDebugStringA("W is down\n");
            if (KeyInput::WasKeyReleased(VK_SPACE))
                OutputDebugStringA("SPACE was just released\n");
            if (KeyInput::WasKeyPressed('G'))
                OutputDebugStringA("G was just pressed\n");
        }

```

Hopefully this helped someone!
> 0 votes

---
Tags: c++, directx, keyboard, winapi
---


title: Mining cubes out of marching cubes

text:
# Question
Title: Mining cubes out of marching cubes
I originally built the start of my game world with a fully minecraft style structure: chunks, only visible faces rendered, noise, etc. Too blocky. I implement marching cubes. Looks great, horrible to work with:

The problem is when you try to add or remove blocks to the marching cubes as... exactly as they are supposed to... everything gets smoothed. It becomes difficult to raycast on a neighbor and if you do all the blocks around him get changed. Obviously.

I see a lot of marching cubes/metaball looking games that implement area based organic molding. You don't place "blocks" you shape an area or deshape it like Landmark mining etc.

On the otherhand Blockscape and Landmark seem to be a blend of the two? The land starts out marching but you can cut clear square chunks out of it and place square cubes onto it.

How can you make straight corners with marching cubes? Or is it a combination of two entirely different systems?

(UPDATE): There is probably more than one answer to this, does anyone have any experience trying to do this though? I can think of a couple of possible approaches:

1. Separate player built objects into a separate mesh/object per chunk keeping terrain as terrain. Run smoothing (marching cubes or others) algorithms and normal calculations only on terrain. Would probably need some sort of a half-transparent cube highlighter showing what the cursor is currently selecting. I can see a number of benefits to this system, though feel as if there are some downsides I'm just not thinking of immediately that would crop up if I started coding it...?
2. Define a "smooth" bool per cube, only assigned at initial calculation of the mesh on any surfaces (floor/ceiling/etc). Any built/added/removed blocks are not re-labelled as "smooth" when generating the mesh use different math for smooth cubes than for blocky cubes. This is what I'm currently working with and it works, but it's still only about a third as smooth as a full marching cube approach would be. Basically I'm average each vertices y value with its surrounding four cubes height(noise) values while never letting it go beneath 0 or above 1 (to stay within the cube). I also had to re-write the raycast click detection to use the surface normals.
3. Re-code the marching cubes algorithms to work only on the cells I want them to/do what I want them to. This seems like the most difficult but possibly most visually rewarding approach.

or ??

# Answer
I would suggest using Dual Contouring instead of Marching Cubes, for the following reasons:

* It supports both smooth and sharp features
* It works well with level-of-detail methods
* It requires no lengthy lookup tables

The one big caveat is that it is not as simple to parallelize for the GPU, if you are interested in that.

PS: You may get stuck trying to figure out the QEF solver - all it is is an algorithm that finds the point with the lowest sum-of-squared-distance-to-planes. I found a particle-based approach with a fixed number of iterations, which can be unrolled in a GPU kernel/shader, worked quite well.
> 3 votes

---
Tags: terrain, voxels, perlin-noise, marching-cubes
---


# Question
Title: How to move an 2D character(with animation) to mouse click position in C#?
i am going to develop a simple game called waste collection.In which if i click on a waste the character needs to walk to certain waste and collect it. Startingly the character is in the middle position of the screen.when we click on the left side of the character,animation left walk needs to play.On the other hand,when we click on the right side of the character the animation right walk needs to play.How the clicked position is taken in this application and how the character animates to that clicked position

public class mousepos : MonoBehaviour {

```
private Animator anim;
public float speed = 1.5f;
private Vector3 target;

void Start () {
anim = GetComponent<Animator>();
 target = transform.position;
}

void Update () {
if (Input.GetMouseButtonDown (0)) {

                **// not working why**
        if (Input.mousePosition.x <=transform.position.x) {
            Debug.Log ("haiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
                            target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                            target.z = transform.position.z;
                            transform.localScale = new Vector3(1, 1, 1);
                            anim.SetInteger ("Direction", 1);

        }

        else if (Input.mousePosition.x >=transform.position.x) {
            Debug.Log ("pooooooooooooooooooooooiiiiii");

                            target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                            target.z = transform.position.z;
                            transform.localScale = new Vector3(-1, 1, 1);
                            anim.SetInteger ("Direction", 1);
                    }

            }
 transform.position = Vector3.MoveTowards(transform.position, target,speed * Time.deltaTime);
}
}

```

# Answer
You should convert you mouse position first using ScreenToWorldPoint before you compare it with transform position

Remember that Input.mousePosition returns your cursor position on screen(Vector2), not on world point(Vector3)

you might find your answer here: http://www.raywenderlich.com/61532/unity-2d-tutorial-getting-started on "Controlling Sprites" section
> 1 votes

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


# Question
Title: How to procedurally generate Mountains that Looks more natural
My Terrain was looking a bit plain so to freshen it up a bit I decided to add mountains to the terrain generation. Unfortunately the Mountains don't look very natural with the surrounding terrain.

I generate the mountains currently by:

1.start at a random spot on the map that is above sea level

2.raise that to the highest point and have surrounding blocks staircase up to it using a radial noise pattern

3.move a certain number of blocks away and repeat until the mountain reaches the coast

here is the code for extra clarification:

```
void generateMountains()
{
    //Find Starting Location
    int startingX = Random.Range(0, grid.columns);
    int startingY = Random.Range(0, grid.rows);
    RidgedMultifractal noise = new RidgedMultifractal();
    noise.Frequency = .01;
    noise.OctaveCount = 8;

    while (grid.FindTile(startingX, startingY).elevation < -3)
    {
        startingX = Random.Range(0, grid.columns);
        startingY = Random.Range(0, grid.rows);
    }
    //createMiddle highest point
    Grid.Tile middlePoint = grid.FindTile(startingX, startingY);

    //how many mountainBlocks to be generated
    while(middlePoint.elevation > SEALEVEL)
    {
        var tilesAroundMid = grid.getNeighborhood(middlePoint, false, 25);

        for (int i = 0; i < tilesAroundMid.Count; i++)
        {
            //setting the distance away from mid
            float distanceToCenter = Mathf.Sqrt(Mathf.Pow(middlePoint.x - tilesAroundMid[i].x, 2) + Mathf.Pow(middlePoint.y - tilesAroundMid[i].y, 2));

            if (tilesAroundMid[i].elevation + Mathf.RoundToInt(((float)noise.GetValue(tilesAroundMid[i].x, tilesAroundMid[i].y, .1) * 10 - distanceToCenter) + 15) >= tilesAroundMid[i].elevation)
            {
                tilesAroundMid[i].elevation += Mathf.RoundToInt(((float)noise.GetValue(tilesAroundMid[i].x, tilesAroundMid[i].y, .1) *10 - distanceToCenter) + 15);
            }
        }
        middlePoint = grid.FindTile(middlePoint.x + Random.Range(10,15), middlePoint.y + Random.Range(10,15));

    }

}

```

How would I change my code so that the mountains generated looks more natural and realistic with the surrounding terrain?

# Answer
I wouldn't seperate the mountain generation from the general terrain generation but combine them.

Today the usual approach to generating landscapes is using 2D or 3D noise functions like perlin or simplex. By combining several amplitudes and octaves you can add both general height (like mountains and valleys) and some detail. You'll probably need to experiment with the values for the number of different noises and their octave/amplitude values to a natural looking result.

2D noise might be fine for you since you basically get a heightmap which seems like what you're going for. 3D noise has the added benefit of being able to generate overhangs and caves which probably won't work out great in your case which looks like only 16 height levels.

Another and simpler approach to creating a realistic heightmap is called diamond-square in which you basically start a small grid with only 4 random heights at the corner and interpolate the gaps (with some random deviation) in a row of two-step rounds.
> 2 votes

# Answer
How are you making the differences in height on your more flat terrain? It looks like you've already got something along the lines of concentric rings going on so why not grab the center of one of the rings and push it up, push each ring around it up, and then radio noise between the smaller vertical distance of each ring?
> 0 votes

---
Tags: c#, unity, procedural-generation, terrain
---


# Question
Title: Coordinate System - Movement from A to B
I've got the following code snipped :

```
 var distanceFromDestinationSquared = (
                    Math.pow(this.orders.to.x - this.x, 2) +
                    Math.pow(this.orders.to.y - this.y, 2));
                if (distanceFromDestinationSquared < Math.pow(this.radius / game.gridSize, 2)) {
                    this.orders = { type: "float" };
                } else {
                    this.moveTo(this.orders.to);
                }

```

**Summary :**

* x and y are always integers (-1, 0, 1, 2, .. )
* The x and y coordinates of the destination and starting point get subtracted from each other, then the square number is taken and eventually those results are added to each other.
* `this.radius / game.gridSize` gives you the equalent size related the coordinate system.

**e.g** `game.gridSize = 20px` \- thus one field in the coordinate system is equalent to 20x20px

I've used this formula with the example of (2/2) as destination and (4/4) as starting point. As result I end up at the line `if (distanceFromDestinationSquared < Math.pow(this.radius / game.gridSize, 2))` with `8 < (18 / 20)²` = `8 < 0.81`

What's the reason behind this apperently trivial formula of movement? Why is it important to take square number of the delta of x and y and add it together?

On one hand it avoides negative values but there would be other ways to deal more efficient with that issue.

Can someone point me to an explanation of this mathematical formula?

# Answer
This code snippet appears to simply compare two euclidean distances; the ordered distance and (what I'm assuming) is the maximum distance allowed (based on a movement radius?).

Euclidean distance is normally calculated as: `sqrt(dx^2 + dy^2) ;`(where `dx` is delta x and `dy` is delta y)

If you just want to compare two distances, to see which is greater, you would have this inequality:

`sqrt(dx1^2 + dy1^2) > sqrt(dx2^2 + dy2^2)`

Rather than performing the sqrt operation on both sides (which can be considered to be an expensive operation), you can skip it as `sqrt(a)` will always be greater than `sqrt(b)` if `a>b` `(a, b > 0)`. Which results in:

`dx1^2 + dy1^2 > dx2^2 + dy2^2`

For a fast euclidean distance comparison.
> -1 votes

---
Tags: movement, coordinates
---


title: CPU Usage and Available Ram in Unity 5

text:
# Question
Title: CPU Usage and Available Ram in Unity 5
In Unity 5 I would like to be able to print out the CPU Usage and Available Ram left in MB. I followed the code posted on http://zamov.online.fr/EXHTML/CSharp/CSharp\_927308.html and used it, however my CPU usage is always 100 and available ram is 0. According to the windows task manager CPU usage should be around 15-20% and available memory is around 4700MB. This is my first time using performance counters and further searching gives me the same code as below (from link):

```
public class ClientValues : MonoBehaviour {

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
public float myCPU;
public float myRAM;

// Use this for initialization
void Start () {

    cpuCounter = new PerformanceCounter();

    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";

    ramCounter = new PerformanceCounter("Memory", "Available MBytes");
}

// Update is called once per frame
void Update ()
{
    myCPU = getCurrentCpuUsage ();
    myRAM = getAvailableRAM ();
    //UnityEngine.Debug.Log (myCPU);
}

public float getCurrentCpuUsage(){
    return cpuCounter.NextValue();
}

public float getAvailableRAM(){
    return ramCounter.NextValue();
}
}

```

What needs to change for this to give me the correct values?

# Answer
On Unity 5, you may use Profiler window

http://docs.unity3d.com/Manual/ProfilerWindow.html
> -1 votes

---
Tags: c#, unity, performance, cpu
---


title: Map Generation Algorithm [BOMBERMAN]

text:
# Question
Title: Map Generation Algorithm [BOMBERMAN]
I'm looking for some wise tips concerning a specific game development : Bomberman-like.

I am currently implementing a "random map" generation for the game, but I feel like I'm not doing in the best way :

* I have a vector of Objects (fresh class having a type (like a Border, a Destructible Wall, a Bomb, a Player...) and two size\_t for (x, y) coords) that I initialize when I create a map.
* I generate Borders all around my Map that will define the game area.

This is the "I don't like that" part :

* I generate some Unbreakable/Breakable Walls using random coords : if at these coords there is nothing but an empty space, I put a Wall there. So that the map is filled with a certain percentage of walls.

Do you have any ideas of how to generate a Map with Walls properly, or using a certain algorithm ? I looked for a Maze Generation Algorithm but I don't have a very good feeling with this.

Thank you for your help and have a great day !

# Answer
> 1 votes
The question is, what pattern you want to achieve, and how to randomize the given pattern.

You could place fix walls in a grid shape, then fill the rest with walls, and when you place the players, clear enough space for them to start.

Then you could start randomizing things:

* Player starting position. Don't forget to check if the players aren't too close.
* Grid pattern: You could offset them by random values from a regular grid. You could generate them with blue noise.
* Walls: Perhaps use perlin noise to leave out some areas.
* Powerups: You could use blue noise again for a more fair distribution.
* Map shape: A big blob of Perlin/Bellow noise perhaps offset to produce some specific shape(multiply it by a blurred bitmaps values and you will get a "Squarish" or "Circleish" shape)

# Answer
> 0 votes
You could try doing things in reverse. Start with an empty grid and place the boundary walls on the play field. Then define a bunch of wall patterns that you can choose from. ... ie a straight section, an L shape, a C shape etc. Randomly place these on the map testing to make sure you still have a valid map. ie One that is not completely closed off by walls. Then place all the game elements on the map.

---
Tags: c++, algorithm, procedural-generation
---


title: Square Based or free movement

text:
# Question
Title: Square Based or free movement
What are the pros and cons of using a 'square' or 'space' based character movement mechanic vs using a free movement mechanic?

* Square/Space - Movement on a ridged grid using 'squares', 'hexagons' and 'triangles'
* Free - Character can move to any valid position on the game board

Some examples of 'Square'

* Final Fantasy Tactics
* Zoids Assault

Some examples of 'Free'

* Star Craft
* Age of Empires
* Baldur's Gate

I am designing a game that is a Tactical RPG my current idea is to use a square grid with a standard character size of 3x3 or 5x5 so that the maps tiles are more granular.

# Answer
> 3 votes
Both of these examples are commonly used because they both have their advantages and drawbacks, mainly on the programming side of things.

## Square/Restricted Maps

### Pros:

* Easy to program, positions can be stored in tile-coordinates as integers and/or in world coordinates.
* Easy for the player to understand
* Fast
* Fairly easy math

### Cons:

* Very restricted in movement positions
* Diagonal movement is a pain to implement and takes much more processing time, depending on implementation ofc.
* Low path quality

## Free-movement Maps

### Pros:

* Extremely intuitive (aka click here and the "character" moves exactly there)
* More natural looking

### Cons:

* Very computationally heavy
* Often requires a pre-generated map and a separate navigation map with valid positions.
* Hard to implement
* Takes a large amount of RAM
* Many duplicate edges

Note that you can get around some, but not all, of the limitations of both of these methods. You can reduce the amount of stored and loaded edges in the free-movement situation at the expense of the perfection of the paths, or can even create a navigation grid rather than a mesh, saving having to store all possible paths. You can also improve the tile-based maps by post-processing them, making them look a little more natural.

Amit Patel, one of the users here on StackExchange has a website where he has many of these additions and optimizations in a tutorial/blog kind of style. One of the best for the question that you are asking is here: http://theory.stanford.edu/~amitp/GameProgramming/MapRepresentations.html

---
Tags: game-design, movement
---


# Question
Title: PBR Metalness Implementation: specColor at Value 1?
I am doing a BRDF supporting the metalness/roughness workflow. I know that in cases of Metalness = 1.0 the reflectance value is taken from the albedo map - so is the specular color to tint the highlights.

My question is if the specular color is taken at the same value that it is in the albedo or is it set to 1.0 first and then used ?

**Example:**

A Pixel in my Albedo Map has a Hue/Sat/Value of 0.5/0.5/0.5

With metalness = 1 the reflectance is 0.5.

Is specColor

a) 0.5/0.5/0.5 b) 0.5/0.5/1.0 (to not dim the specular) ?

Thanks, Jens

# Answer
Short version: a) 0.5/0.5/0.5

In the metals workflow, the specular colour will be exactly as sampled in the Albedo map. It's possible with PBR to have some metals shinier than others (while of course still obeying conservation of energy), which can only be achieved by allowing dimmer colours in the Albedo Map to result in dimmer specular values.
> 1 votes

# Answer
It's not quite as simple as simply tinting the specular color with albedo for metals. For metals the albedo is used to define specular reflectance at normal incidence, but this color goes to white at grazing angles due to Fresnel effect. You can use Schlick's approximation for this computation.
> 1 votes

---
Tags: opengl, pbr, specular
---


# Question
Title: How long is SystemInfo.deviceUniqueIdentifier?
How long is `SystemInfo.deviceUniqueIdentifier`?

The official docs say nothing about it. Obviously I can do a few tries, but these will definitely not be conclusive: did someone either gather extensive data, or somehow analyzed the algorytm that creates it?

# Answer
The difficulty here is that `deviceUniqueIdentifier` is implemented in terms of different API calls depending on the underlying OS or hardware. On iOS platforms, it uses `identifierForVendor`. On Windows, it uses the `AdvertisingId`. In both cases there are fallbacks that might be used.

The fact that the API calls potentially vary even on the same platforms suggests that no guarantee *can* be provided about the length of the resulting identifier, only it's uniqueness properties; those are the only properties guaranteed by all of the underlying OS calls uses, so those are the only ones the Unity API can guarantee forward.

In practice the identifiers currently appear formatted as GUIDs. You could probably reasonably use that as an upper bound for the column size on your database; for maximal protection you could store then as `nvarchar(max)`, but that's seems *pointlessly wasteful*.

It's possible the output of the APIs involved may change in future revisions of the underlying APIs. You'll want to make sure to check for that somewhere, but you don't need to be overly aggressive about it.
> 3 votes

---
Tags: unity
---


# Question
Title: How to set borders in Rubik's cube using opengl GLSurfaceView
I'm developing a Rubik's cube game like seen in the picture. But I'm facing problems to set the cube face color with black border.

```
  public void setupSides() {
int i, j, k;
// Paint back blue
i = 0;
for(j = 0; j < dim; j += 1) {
    for(k = 0; k < dim; k += 1) {
    cubes[i][j][k].setFaceColor(Cube.kBack, colors[faceColors[Cube.kBack][j][k]]);
    }
}

// Paint front green
i = dim - 1;
for(j = 0; j < dim; j += 1) {
    for(k = 0; k < dim; k += 1) {
    cubes[i][j][k].setFaceColor(Cube.kFront, colors[faceColors[Cube.kFront][j][k]]);
    }
}

// Paint right white.
k = dim - 1;
for(i = 0; i < dim; i += 1) {
    for(j = 0; j < dim;j += 1) {
    cubes[i][j][k].setFaceColor(Cube.kRight, colors[faceColors[Cube.kRight][i][j]]);
    }
}

// Paint bottom orange
j = 0;
for(i = 0; i < dim; i += 1) {
    for(j = 0; j < dim;j += 1) {
    cubes[i][j][k].setFaceColor(Cube.kBottom, colors[faceColors[Cube.kBottom][i][k]]);
    }
}

// Paint top red
j = dim - 1;
for(i = 0; i < dim; i += 1) {
    for(j = 0; j < dim;j += 1) {
    cubes[i][j][k].setFaceColor(Cube.kTop, colors[faceColors[Cube.kTop][i][k]]);
    }
}
// Paint left yellow
k = 0;
for(i = 0; i < dim; i += 1) {
    for(j = 0; j < dim;j += 1) {
    cubes[i][j][k].setFaceColor(Cube.kLeft, colors[faceColors[Cube.kLeft][i][j]]);
    }
}
}

```

This method is used to set the colors in all sides.

My Rubik Cube image is shown which is given below

That image create through my code but i want my rubik cube color with black border like which is given below

# Answer
> 1 votes
If you want a rounded corner like the true cube I would use a texture map with a black border and transparent area which you wish your base colour to be visible through.

There is also newer methods of drawing shapes using paths but I haven't looked at these so I cannot advise how you could do those.

Hope it helps.

# Answer
> 0 votes
A good solution is rendering the face black, then render the face with your selected color with less height and width.

Also, render it a bit outwards, for eviting z-fighting.

---
Tags: android, opengl-es, view
---


title: How to check if a test ad is ready

text:
# Question
Title: How to check if a test ad is ready
I was going through UnityAds for Unity3D, and came across this setting:

> AD TEST MODE
>
> Force all

So as I understood it states that I will be able to see real ads, in test mode, without monetizations on my testing tool, which in my case is Unity3D IDE, but I am still getting that blue sample ad screen "Here would be your ad screen". Is there anything that I can do to check if any ad is placed for my app, and check this via code before `Advertisement.Show();` statement? Or am I missing something?

# Answer
> 2 votes
I am by no means an expert on this, but i played a little bit around with that. If you see the blue screen everything is fine in editor mode you will always see the blue screen stating that your advertisment would come here. If you build it then you will see the ad if you configured your app correctly.

I used it like this:

Advertisement.Initialize("YourAppIDGoesHere"); if (Advertisement.isReady() ) { Advertisement.Show(); }

For More Information check out the Unity documentation:

https://unityads.unity3d.com/help/Documentation%20for%20Publishers/Integration-Guide-for-Unity-Asset-Store

---
Tags: unity, advertisements
---


# Question
Title: How to set a struct as a Direct3D9 vertex shader constant?
I have a vs\_2\_0 shader like this:

```
struct ConstantBuffer
{
    float4 diffuse;
    float4 specular
};

shared uniform ConstantBuffer g_cb : app_constantBuffer;

void PS(out float4 Color: COLOR0)
{
    Color = g_cb.diffuse;
}

```

The above example is simple, the constant buffer only stores two 4 component colors. I want to set the constant buffer before binding the pixel shader. I do not want to use the ID3DXEffect interface.

The IDirect3D9Device interface only provides methods for setting primitive types...I want to set the entire struct at one time. Is this possible?

# Answer
> 1 votes
D3D9 doesn't support constant buffers but all uniforms are placed into one global "constant buffer". You can set multiple float4 constants at once with IDirect3DDevice9::SetPixelShaderConstantF() by passing the number of constants as the last argument.

---
Tags: c++, shaders, hlsl, directx9
---


# Question
Title: How to enter a level when touching an object
I am working on a project in Unity 4.6.1f1 and I was wondering how can I make a cube touch another cube to go to the next level (the image below)?

!

**EDIT:** I made a script and put it on the purple cube then enabled "is trigger" on the purple cube, but the blue cube goes right through it.

Inspector:

And the code:

**EDIT 5/15/15:** I edited my script and I was wondering if I'm doing something wrong.

# Answer
> 4 votes
Your LevelCollider is attached to a Collider that is a trigger. That means it will not call OnCollisionEnter. It will call OnTriggerEnter.

Try adding this to LevelCollider:

```
void OnTriggerEnter(Collider other) {
     Application.LoadLevel("Level1");
}

```

That should do ya!

# Answer
> 2 votes
Detect collisions with OnCollisionEnter then load your level there. I.e.:

```
void OnCollisionEnter (Collision col)
{
    Application.LoadLevel("Level1");
}

```

If your character's Collider is a trigger, then you need to use OnTriggerEnter. I.e.:

```
void OnTriggerEnter (Collider other)
{
    Application.LoadLevel("Level1");
}

```

If neither of these work, try checking these things:

* The character and object are set to collide in the layer collision matrix.
* The scene called "Level1" is added to the build. You can check if it is by pressing Ctrl-Shift-B under 'Scenes in build'.

# Answer
> 0 votes
The command to load a level is Application.LoadLevel(). Call that from an "On Collision" function on the cube.

# Answer
> 0 votes
You can add a box collider (`Add` -\> `Physics` -\> `Box Collider`) in the inspector.

Then, add a script with a function

```
 OnCollisionEnter(Collision other)

```

then add that script to the cube you want to collide with.

More info in here: https://unity3d.com/learn/tutorials/modules/beginner/physics/colliders-as-triggers

---
Tags: unity, 3d, javascript, gameobject
---


# Question
Title: Placing an AABB close to a point so that it doesn't intersect any other AABBs
Give a 2D space with a bunch of non-intersecting AABBs, and a point in this space (that may or may not be inside an AABB), how can I find the closest place where I can place a new AABB of a given size?

For example, given the space below and the point 'X', the correct position for a certain AABB is marked in green:

One solution I have considered is to iterate every edge, and find the closest point on that edge where the shape doesn't intersect (if such a point exists). This could be achieved by placing the AABB at the closest point on the given edge, and then if it's intersecting with another shape, move it to the outside edge of that shape, along the given edge, repeating until it's no longer intersecting. This seems relatively expensive (though could probably be optimized by using some kind of spatial hashing), but might be the way to go.

I'm wondering if there are any obvious or not so obvious solutions I'm missing here.

# Answer
> 2 votes
I recently encountered a related problem to do with packing a texture atlas. The main difference for yours is that you prefer "closest to a target point" result. But I think the approach will work about the same...

All of the candidate locations for the new rectangle have the following property:

* One of its corners will lie on one of the "implied grid points" of the existing collection of rectangles.

The implied grid points is the grid made from all present X-coordinates and all present Y-coordinates of existing rectangles, PLUS the size of the new rectangle centered on the target location.

So, you could test each of these implied grid points, starting with the ones closest to the x-mark, and each of the four positions that the new one might touch a corner to it, til one fits.

To test legality of each candidate, you can intersect with *every* other rectangle, or prune that down with spatial binning or quad tree or such. (Look up algorithms for collision resolution, they will go into more detail on optimizing this aspect.)

---
Tags: algorithm, bounding-boxes, spaces
---


# Question
Title: RPC events with client side interpolation
I've implemented client side interpolation, where a specified delay is put on each client. This allows them to interpolate between positions and rotations. Unfortunately, this means every thing else must be delayed, otherwise events ( like a particle effect on a collision ) will happen ahead of time( according to the interpolated data. )

Should I delay everything along with the interpolated data, or do I have the wrong idea about client side interpolation? I haven't seen a single mention of this problem anywhere, which makes me think I'm missing something.

# Answer
> 1 votes
The easiest way to implement interpolation correctly is by using fixed time steps. Basically, if you know you're going to get a new position about 10 times a second, you can interpolate from the last position to the current one in the time it takes to get a new position (.1 seconds).

In reality, there are things like jitter that make your job harder so packets won't always arrive .1 seconds apart if they're sent .1 seconds apart. This problem can be solved with some buffering. Instead of immediately accepting a position as the current position when you receive it, wait until the next expected sync frame to recognize it.

I.e.

```
Vector2 LastPos;
Vector2 CurrentPos;
Vector2 BufferPos

//When data is received, store it in the buffer
void OnReceiveData (byte[] RawData)
{
    BufferPos = DeserializationMagic (RawData);
}

//Runs every .1 seconds or however frequent this character gets synced
void FixedUpdate ()
{
    LastPos = CurrentPos;
    CurrentPos = BufferPos;
    ElapsedTime = 0;
    //Send out your position to everyone (except yourself)
    Networking.RPC (transform.position);
}

//Used for smooth interpolation
float ElapsedTime;

//Interpolate position every frame based on time since last position was set
void Update ()
{
    ElapsedTime += Time.deltaTime;
    //Lerps by a factor of 10 since interpolation needs to happen within .1 seconds
    transform.position = Vector3.Lerp (LastPos, CurrentPos, ElapsedTime * 10);
}

```

There are a bunch of things you can do with time stamps and whatnot for staggered syncing, but at 10 syncs per second, any advantages you get without an expected sync frame probably won't get noticed. Plus, this is the most straightforward and simple way to get smooth interpolation in my opinion.

I don't recommend using RPCs to sync objects though, since the RPC most likely is reliable. Reliable protocols involve sending an ACK packet which means another 20-40 bytes for the packet header. The sender could also resend the original packet if an ACK was not received in time.

Syncing unreliably should be fine since if 1 or 2 packets go missing, the next received packet will fill in the gap.

---
Tags: unity, networking
---


title: How to read a custom map format

text:
# Question
Title: How to read a custom map format
I am trying to create a custom map format for my own little 2D RPG, so my question is rather how do I manage reading and creating a custom map format properly and flexible. First off, I am writing my code in Java. The idea was to have a class called 'TileMap'. This class defines a 2-dimensional integer - array where all my entities are stored ( I'm using an entity-system to realize my game ). I also want to save and parse some information about the size of the map before the actual reading process happens. The map file should look much like this:

```
#This is a test map
width=4
height=3
layercount=1
tilesize=32

[1;0;0;0]
[23;1;0;0]
[5;0;1;0]

```

where layercount is the number of layers the z-dimension offers. and tilesize is the size of every tile in pixels. Entities are defined in between the brackets. The pattern goes: \[*entity\_id*;*x\_pos*;*y\_pos*;*z\_pos*\]. I already wrote the code to parse a file like this but its not very flexible because you just have to put one tiny whitespace in front of the square brackets and the map can't load up. I just need some few helpful tips to do this in a flexible way. Can anybody help me out?

# Answer
You want to look into parsing, which is a very well documented field.

To start off simply though, you might parse the file line-by-line, stripping '#' to the end of the line, and stripping any padding whitespace. This solves the issue of "its not very flexible because you just have to put one tiny whitespace in front of the square brackets".

You can then recognize (either via a search or, better, via regular expressions) and parse each type of line (`key=value` lines, `[x;y;z]` data lines) as it comes.

Regular expressions will allow you to easily define a simple grammar for the lines and as a bonus, easily extract the data from it.
> 0 votes

---
Tags: java, 2d, maps, entity
---


# Question
Title: How to properly activate trigger objects?
I have made a flying cat that follows the player, but I want the cat to be a separate object. Cat is following the player and as soon as it sees a collectible it grabs it for the player and then returns following our player. I have it working, but I need the cat to be a different object, it only triggers properly when it's a child of the player object. I have made two scripts for the cat, one for detection, following, flying and the other for destruction of collectibles.

AI script

```
void OnTriggerStay2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        //Destroy(col.gameObject, 1F);
        if(positionList.Count <= 0){
        positionList.Add(col.transform.position);
        timerDelay = 1F;
        mustReturn = false;
        }
    }
}

void OnTriggerEnter2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        positionList.Add(col.transform.position);
        timerDelay = 1F;
        mustReturn = false;
    }

}
void Update () {

    if (mustReturn) {
    //  positionList.RemoveAt(0);
        transform.position = Vector3.MoveTowards (
            transform.position, player.transform.position, Time.deltaTime * speed);

    }

    if (timerDelay > 0) {
        timerDelay-= Time.deltaTime;
        idleDelay = 0;

        if(positionList.Count > 0) {
        foreach (Vector3 nextPos in positionList)
        {
            transform.position = Vector3.MoveTowards (
            transform.position, nextPos, Time.deltaTime * speed);

        }
    }

}

    if (timerDelay <= 0) {

        if(positionList.Count > 0) {
            positionList.Clear();
            timerDelay = 1F;
        }

        if(positionList.Count <= 0)
        mustReturn = true;
    }

    if (idleDelay >= 3F) {
        idleAnimation();
    }

    /*Debug.Log ("pos count is " + positionList.Count);

    if(timerDelay > 0)
        Debug.Log ("delay is " + timerDelay);*/

    idleDelay += Time.deltaTime;

}

void idleAnimation(){

}

void OnTriggerExit2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        mustReturn = true;
    }
}

```

Destruction class

```
void OnTriggerStay2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        Destroy (col.gameObject, 0.5F);
    }
}

void OnTriggerEnter2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {

    }

}
void OnTriggerExit2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {

    }
}

```

**Question: Why won't the cat function on it's own???**

Collectibles DO have that tag, and they DO have a Box Collider 2D along with a 'Trigger: true'

Cat:

# Answer
> 1 votes
When an object has a Collider set to Trigger, but no rigid body, it's called a "Static Trigger Collider". This is likely the scenario for both your collectables and your cat.

If you look at the "Trigger messages are sent upon collision" chart near the bottom of this page

You'll see that two Static Trigger Colliders will not interact with each other. If you want your collectibles to have their trigger methods called, your cat needs to be one of the following:

* Rigidbody Collider
* Kinematic Rigidbody Collider
* Rigidbody Trigger Collider
* Kinematic Rigidbody Trigger Collider

Notice anything about all those options? They're all rigidbody types! **You need to add a `RigidBody2D` component to your cat!**. It's up to you if you want the non-kinematic or kinematic.

* Non-kinematic: will collide with objects and should be controlled via the physics system (i.e. applying forces to it)
* Kinematic object isn't simulated in the physics and should be moved around by modifying its transform (position, rotation).

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


title: Android: Improving surfaceView?

text:
# Question
Title: Android: Improving surfaceView?
I'm using Surfaceview in my Android app. I have two threads, one for UI and another for rendering and updading the UI.

I am limiting my frames per second to 30 fps and have employed frame-skipping to a max of 3 frames.

I am using delta to update my sprite positions.

All works as it should apart from one thing - the sprites don't move entirely 'smoothly'

They seem to 'jerk' randomly. And I'm just wondering, is this just the way surfaceview is? I'm guessing it's when the device is doing something else? Can I give priority to my app somehow or does anyone have any tips (apart from switching to OpenGL !!) On optimising surfaceView and to get it to run a bit smoother?

Thanks

I've removed everything from my onDraw() and update() methods and just put 1 small sprite in onDraw() and added 1 to the sprites X position in my update() method. The sprite still 'jerks' along, hard to explain, but it moves smoothly for a little while then there's a slight stutter.

Edit: Some code as requested..... (I've given my onDraw, update and run methods here)

```
@Override
protected void onDraw(Canvas canvas) {
   canvas.drawBitmap(scaledBackground, 0, 0, null);
   canvas.drawBitmap(scaledSmallCloud, cloudX, cloudY, null};
}

public void update() {
   cloudX++;
}

protected class preThread extends Thread {

   private SurfaceHolder mySurfaceHolder;
   private Context myContext;
   // flag to hold game state
   private boolean running;

   public preThread(SurfaceHolder surfaceholder, Context context, Handler handler) {                          // Constructor
      mySurfaceHolder=surfaceholder;
      myContext=context;
      res = myContext.getResources();
   }

   public void setRunning(boolean running) {
      this.running = running;
   }

    @Override
    public void run() {
        Canvas c;
        while (running) {
            c=null;
            timestart = System.currentTimeMillis(); //Get time at start of loop for FPS calc
            try {
                c = mySurfaceHolder.lockCanvas(null);
                synchronized(mySurfaceHolder) {
                    onDraw(c);
                    update();
                }
            } finally {
                if (c != null) {
                    mySurfaceHolder.unlockCanvasAndPost(c);
                }
            }

            //Frame limiting and skipping calcs
            timeend = System.currentTimeMillis();                               //Get end time of current frame
            frametime = timeend-timestart;                                      //Time frame took to render and update
            sleepfor = (int) ((1000/fps)-frametime);                            // this is the time that the thread will sleep for if <target time

            if (sleepfor>0){                                                    // If the 'sleepfor' variable is >0 then set the thread to sleep for it's value (expressed in ms)
               try {
                   MainThread.sleep(sleepfor);                                  //send thread to sleep for value of sleepfor (determined above).
               } catch (InterruptedException e) {}                              //in case of exception
            }                                                                   //close if statement
            while (sleepfor<0 && framesskipped<maxframesskipped) {              //if sleepfor is < 0 (ie, frame took longer to render than target time and the maxframesskipped has not reached it's limit)
                update();                                                       //Update animation variables without rendering to the screen while these conditions are met
                sleepfor+=33.33333333333333;                                    //time to sleep plus the time frame took to render
                framesskipped++;                                                //add one to framesskipped variable so this only skips a certain number of frames
                //Log.v("Timer","frame skipped!");
                //frame=0;
            }
        }
    }

```

This is basically a really stripped down onDraw() which simply displays a static background and a single moving sprite.

I have removed my delta-sprite movement to rule that out and am simply incrementing the sprite's x position by an explicit value (1).

I've also tried the following:

* Removing the drawing of the background image
* Changing 'overridden' onDraw() to doDraw and moving it to the preThread class.
* Increasing upper frame rate limit to 60fps (as @Lumis suggested in comments)
* I've removed my frame limiting and skipping so the game just runs flat out at the max frame rate - this gives a slightly different effect, less of a 'quick skip' and more of an intermittent prolonged 'slow down', then 'speed up' of the sprites.

What actually happens - the sprite does move smoothly (even at 30 fps), but every now and then (more often than I would like) - it kind of 'lags' or 'jerks', it's a small effect but is extremely annoying.

Any more suggestions would be very much appreciated - thank you again!

# Answer
> 3 votes
System.currentTimeMillis() should be changed to System.nanoTime() / 1000000;

currentTimeMillis has an issue in it that sometimes comes back with a weird number and in games causes twitching in animations and graphics

# Answer
> 1 votes
This solved the problem for me:

```
Paint bitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);

canvas.drawBitmap(scaledBackground, 0, 0, bitmapPaint);

```

---
Tags: android, sprites, html-canvas, game-loop
---


# Question
Title: Moving a character depending on the direction he is facing (C#/Unity3D)
Right now I have a small soldier on the screen that moves with W, A, S, D and rotates / changes direction with the arrow keys. What I want to happen is when the player's direction changes (by using the arrow keys), pushing W will send him in that direction instead of up the screen.

Also (for example), if you are holding D and the right arrow key at the same time he should move in a circle about a point on the ground (instead of spinning in a circle while moving in a straight line to the right).

Here is my current code:

```
public class MovePlayer : MonoBehaviour {
  void Update() {
    // Rotate left
    if (Input.GetKey (KeyCode.LeftArrow)) {
      transform.Rotate(0, 0, 1.3f);
    }
    // Rotate right
    if (Input.GetKey(KeyCode.RightArrow)) {
      transform.Rotate(0, 0, -1.3f);
    }
    // Strafe left
    if (Input.GetKey (KeyCode.A)) {
  Vector3 position = this.transform.position;
      position.x -= 0.055f;
      this.transform.position = position;
    }
    // Move up
    if (Input.GetKey (KeyCode.W)) {
      Vector3 position = this.transform.position;
        position.y += 0.043f;
        this.transform.position = position;
    }
    // Move down
    if (Input.GetKey (KeyCode.S)) {
      Vector3 position = this.transform.position;
      position.y -= 0.043f;
      this.transform.position = position;
      isMoving = true;
    }
    // Strafe right
    if (Input.GetKey (KeyCode.D)) {
      Vector3 position = this.transform.position;
      position.x += 0.055f;
      this.transform.position = position;
    }
}

```

}

Any ideas? Wasn't sure what to search exactly.

# Answer
I don't fully understand your question.

But, if you want to move something forward, what I would do is something like:

```
this.transform.position += this.transform.forward * moveSpeed;

```

Whereas, moveSpeed is the speed at which you want your unit to go forward.

To go in the opposite direction that you are facing:

```
this.transform.position -= this.transform.forward * moveSpeed;

```

---

Try giving this a try and seeing it it helps:

```
private float moveSpeed = 1;

void Update() {
    // Rotate left
    if (Input.GetKey(KeyCode.LeftArrow)) {
        transform.Rotate(0, -1, 0);
    }
    // Rotate right
    if (Input.GetKey(KeyCode.RightArrow)) {
        transform.Rotate(0, 1, 0);
    }
    // Strafe left
    if (Input.GetKey (KeyCode.A)) {
        transform.position -= new Vector3(1,0,0);
    }
    // Move forward
    if (Input.GetKey (KeyCode.W)) {
        transform.position += transform.forward*moveSpeed;
    }
    // Move backward
    if (Input.GetKey (KeyCode.S)) {
        transform.position -= transform.forward*moveSpeed;
    }
    // Strafe right
    if (Input.GetKey (KeyCode.D)) {
        transform.position += new Vector3(1,0,0);
    }
}

```
> 1 votes

# Answer
Use transform.TransformDirection() along with Vector3D.forward (or .up or whatever). TransformDirection() will convert the 'forward' direction of the player to that direction in global space.

EDIT: oops you want to transform the direction the other way, from world space to local space, not local to world. Use InverseTransformDirection()

---

Another simple approach would be to separate the rotating visual from moving object, so that the object you moves never rotates. In that case, just parent the character to the moving object.
> 0 votes

---
Tags: c#, unity, 2d, game-mechanics
---


# Question
Title: Importing .anim files created using the Unity Animation controls
Our artist created some .anim files using the built-in Unity Mecanim system (where you use keyframes and drag various body parts to construct the animation).

However, now we're trying to export them from her Unity program into mine so that I can incorporate them into the scene. The problem is that they're simply appearing as blank files.

Here, the files are importing and everything looks fine aside from the controller:

However, once it's imported, it just shows up as a blank/unrecognized file:

She's exporting everything as a .unitypackage and I'm importing the .unitypackage, but it doesn't work for some reason.

In addition, she was able to create a new project on her computer and import the package fine. Any ideas why mine is funking up?

# Answer
> 0 votes
This was simply an error with her and my Unity versions being different. By updating my version of Unity, that solved the issue. Apparently files need to come from the same Unity version to be compatible!

---
Tags: unity, 2d, animation, importing, mecanim
---


# Question
Title: Create a continuous flight path on a Bezier Curve in Unity3d
I am working on a game in which a butterfly is flying along some path.

What I am trying to do currently is create a Bezier curve starting from the butterfly's position(previous curves end point) and the rest of the points random for it to fly on. Once it has finished on the curve it needs to continue its path along the next curve that is generated. The problem I have is that the next curve sometimes starts in a direction that makes the transition look rugged and unrealistic. This is the code I have so far.

```
void updateDirection()
{
    if (!LeanTween.isTweening(this.gameObject))
    {
        Vector3 curveA = { transform.position, new Vector3(Random.Range(-5f, 0), 0, Random.Range(-3f, 0)), new Vector3(Random.Range(-5f, 0), 0, Random.Range(-3f, 0)), new Vector3(Random.Range(-5f, 0), 0, Random.Range(-3f, 0)) };
        LeanTween.move(this.gameObject, curveA, 3f);
    }
}

```

I am using the LeanTween API to create the movement method easier.

So basically I need to find a way to make a continuous bezier I guess and I am no mathematician so if it could be explained in easy to understand terms that would be amazing!

# Answer
> 1 votes
You will probably have an easier time with a catmul rom spline. You give points for the path to pass through and it figures out the rest. A catmul rom spline is a type of Hermite spline, which is a different mathematical form of bezier splines. http://www.mvps.org/directx/articles/catmull/

# Answer
> 0 votes
I guess you could use a trail system much like the one provided for a similar problem:How to approach 360 degree snake without having it "slide"

if you can get the transform of every point of your splines (all of them) you can then add them to a List and use the trail system to traverse them.

---
Tags: c#, unity, 3d, game-mechanics
---


# Question
Title: Unity3D Tag as a public variable in editor
How do you incorporate Tag strings into a scripts editor found in the inspector?

What it is I'm babbling about: When you create a `public GameObject fooObject` in a script, it shows up as a box that can have Game Objects dragged onto in its editor. It also has a small clickable dot that shows every Game Object that could be selected.

Now, say I have a `public string fooString` that would specifically be used for referencing the Tag strings of Game Objects (such as `if (fooObject.tag == fooTag)` or another use). Is there a way to define that string so that in the script's editor it strictly allows tag names to be used with it? I'm assuming with a similar clickable dot or a drop down menu of every selectable tag.

Although I could just manually type my string, a solution like the one above would have big object-orientated advantages. For example, if I was to change the name of this tag, it would change the string variable accordingly, as if the variable was a reference to such tag.

*\[Note to the moderators: I looked for an answer to this question for nearly 2 hours now to no avail. I understand that I may be missing some specific wrong word choice, in which case this question easily could have already been answered here. If this is closed as a duplicate, then, a quick comment explaining my mistake would be greatly appreciated.\]*

# Answer
> 2 votes
I'm not really sure why you need this, or how exactly will it optimize your script, and I can think of several ways you can handle this in a much more efficient way without need of all these, but here goes :

EditorGui.TagField gives you a selector for choosing a tag.

UnityEditorInternal.InternalEditorUtility.tags gives you an array of all the Tags in your Build, which is probably what you need.

---
Tags: unity
---


# Question
Title: How to properly pass sprites to a std::vector without destroying the sprite's texture in SFML?
*From the official SFML tutorials, The **White Box Problem**:-*

"When you set the texture of a sprite, all it does internally is store a pointer to the texture instance. Therefore, if the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer." Thus you will see a sprite without a texture.

I have a class called **World**. In this class I made a 2d integer array called **level** and **a vector of type Block called blocks**. Now I wanted to store the 'Block' objects inside the vector whenever level\[ i \]\[ j \] = 1.

*header file of the 'World' class:-*

```
#ifndef WORLD_H
#define WORLD_H
#include <vector>
#include "Block.h"
#include "Grass.h"
#include <SFML/Graphics.hpp>

using namespace std;

class World
{
    public:
        World();
        void draw(sf::RenderWindow *window);
        vector<Block> blocks;

    private:
        int level[12][16];
        int wd;
        int hi;
};

#endif // WORLD_H

```

*cpp file of the 'World' class* :-

```
#include "World.h"
#include "Grass.h"
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

World::World() : level{
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
    }
{
    wd = 16;
    hi = 12;
    int count = 1;
    //make a 'Block' object and pass it in the vector when level[ i ][ j ] = 1.
    for(int i = 0; i<hi; i++)
    {
        for(int j = 0; j<wd; j++)
        {
            if(level[i][j] == 1)
            {
                Block block(j*50, i*50);
                blocks.push_back(block);
            }
        }
    }
}
void World::draw(sf::RenderWindow *window)
{
    for(unsigned int i = 0; i<blocks.size(); i++)
    {
        blocks[i].draw(window);
    }
}

```

The 'Block' class has two members - **sf::Texture blockT** and **sf::Sprite block**. It also has a draw(RenderWindow \*window) method. This is how the 'Block' class is made :-

*header file for block class*

```
#ifndef BLOCK_H
#define BLOCK_H
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

class Block
{
    public:
        Block(float x, float y);
        void draw(sf::RenderWindow *window);

    private:
        sf::Texture blockT;
        sf::Sprite block;
};

#endif // BLOCK_H

```

*cpp file for 'Block' class*

```
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

Block::Block(float px, float py)
{
    if(!(blockT.loadFromFile("textures/block.png")))
    {
        cout<<"Could not load block texture."<<endl;
    }
    block.setTexture(blockT);
    block.setPosition(sf::Vector2f(px, py));
    cout<<px<<endl;
    cout<<py<<endl;
}

void Block::draw(sf::RenderWindow *window)
{
    window->draw(block);
}

```

When I run the program, in place of blocks, only white box is shown. I don't understand how the texture is getting destroyed. This is what the output looks like :-

As you can see, the white places are sprites each of size 50\*50 without any texture.

*Edit: The Main Function :-*

```
int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Untitled game");
    window.setVerticalSyncEnabled(true);
    Player player;
    World world;

    //variables

    while(window.isOpen())
    {
        //event handling

        //updating

        //drawing
        window.clear(sf::Color::Black);
        world.draw(&window);
        window.display();
    }

    return 0;
}

```

# Answer
When I asked this question I didn't knew much about sprites and textures, but then I learned quite a lot from the internet and sfml tutorials. Actually what I was doing in the program was not correct. I was storing the texture in a local scope which was getting destroyed at the end of the scope. Textures should be stored at a global scope.

In fact, one should use vertex array and map texture coordinates to its vertices, instead of making thousands of sprites, as it is faster and more convenient for the graphics card. The lesser the number of calls to the 'draw' function, the better is the performance of the game. So a million sprite objects means a million calls to the 'draw()' function of your application which reduces performance.

Tutorials about the use of vertex arrays in sfml can be found in sfml's website, in the tutorials section. http://www.sfml-dev.org/
> 1 votes

# Answer
Your problem is most likely the fact that you create copies of your blocks when adding them to your vector.

That way once the original copy/block is destroyed, the texture won't be valid anymore (since there's a shallow copy happening, so even the new copies still point to the old texture, despite having their own copy).

As a potential fix, change your vector to `std::vector<Block*>` and only store pointers in there (don't forget to free the memory later on) or use smart pointers straight away.
> 2 votes

# Answer
You appear to be correctly storing a texture and then setting that texture to a sprite, so I don't think the White Square problem they're referring to in the documentation applies to you in this situation as you don't have the texture being created in a local function scope etc. `std::vector<T>::push_back()` creates a copy of the argument and stores it in the vector so that shouldn't be a problem here I believe.

You didn't post your main function so I'm unsure, but it would appear that you don't have a clear() or display() function wrapped around your primary SFML draw() function. http://www.sfml-dev.org/tutorials/2.2/graphics-draw.php

Assuming the texture is not actually white, in order to do some quick elimination testing you could pick a section of the loaded texture i.e. :

```
sprite.setTextureRect(sf::IntRect(10, 10, 32, 32));

```

or you could just test with a colour i.e. :

```
sprite.setColor(sf::Color(0, 255, 0)); // green

```

Additionally, I've noticed that you're loading a new texture for each block. This kind of defeats the object of using a texture. With a texture you want to load it once into video memory and then point all of your sprites to that once instance to reduce draw calls and memory requirements etc (aka batching your draws). In 2D games using the concept of one large texture atlas is very common because it's so efficient. You could have a variety of block textures all tightly packed into one 'blockTypes' texture and then just use 'sprite.setTextureRect' to refer to different sections of that texture as mentioned above.

I'd just throw a few texture atlases into a map so that you have a single texture dictionary to refer to in all of your block objects.
> 1 votes

# Answer
A quick test, just grab the logo image from the SFML site and paste it into the working directory of your project (or just somewhere simple and explicitly state that in code i.e. "C:\test\img.png")

```
#include <vector>
#include <iostream>

#include <SFML/Graphics.hpp>

int main()
{

    sf::Texture texture;
    if (!texture.loadFromFile("sfml-logo-big.png")) {
        // error out here
        std::cout << "Error loading texture!" << std::endl;
    }

    std::vector<sf::Sprite> sprites = std::vector < sf::Sprite > {
        sf::Sprite(texture,), sf::Sprite(texture), sf::Sprite(texture)
    };

    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML works!");

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

        window.clear();
        for (int x = 0; x < sprites.size(); x++) {
            window.draw(sprites[x]);
        }
        window.display();
    }

    return 0;
}

```
> 1 votes

# Answer
The simplest solution is to keep textures in `World` class, like this:

```
class World
{
    public:
        World();
        void draw(sf::RenderWindow *window);
        vector<Block> blocks;

    private:
        int level[12][16];
        int wd;
        int hi;
        sf::Texture Texture;
};

```

And definition:

```
World::World()
{
    if (!(Texture.loadFromFile("textures/block.png", sf::IntRect(0, 0, 50, 50))))
    {
        cout << "Could not load block texture." << endl;
    }

    wd = 16;
    hi = 12;
    int count = 1;
    //make a 'Block' object and pass it in the vector when level[ i ][ j ] = 1.
    for (int i = 0; i<hi; i++)
    {
        for (int j = 0; j<wd; j++)
        {
            if (level[i][j] == 1)
            {
                Block block(j * 50, i * 50, &Texture);
                blocks.push_back(block);
            }
        }
    }
}

```

You also need to change `Block` constructor in `Block.h`:

```
Block(float x, float y, sf::Texture* Tex);

```

In `Block.cpp`:

```
Block::Block(float px, float py, sf::Texture* Tex)
{
    block.setTexture(*Tex);
    block.setPosition(sf::Vector2f(px, py));
    cout << px << endl;
    cout << py << endl;
}

```

In professional games, resources like textures, audio, and so on, are kept in separate container (or class), to prevent resource being destroyed or moved elsewhere in memory and it saves memory. **Actually, the answer to problem ends here**, however you can also make you `Block` class inherit form `sf::Drawable`:

```
class Block : public sf::Drawable

```

You will have to change `void draw(sf::RenderWindow *window);` to `virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;`, so whole `Block` class will look like this:

```
class Block : public sf::Drawable
{
public:
    Block(float x, float y, sf::Texture* Tex);
    Block();

private:
    sf::Sprite block;
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
}

```

You also need to add default constructor.

In `Block.cpp`:

```
void Block::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
    states.texture = block.getTexture();
    target.draw(block, states);
}

```

It is much nicer way to draw an object by making it drawable from SFML's point of view.

You must also change implementation of `void draw(sf::RenderWindow *window);` in `World` class, because you don't know what are the `states`:

```
void World::draw(sf::RenderWindow *window)
{
    for (unsigned int i = 0; i<blocks.size(); i++)
    {
        window->draw(blocks[i]);
    }
}

```

It's possible because `Block` inherits from `sf::Drawable`, so `window` can call \`Block::draw(...) internally.

For future reading: http://www.sfml-dev.org/tutorials/2.3/graphics-vertex-array.php#creating-an-sfml-like-entity
> 0 votes

---
Tags: c++, textures, sprites, tilemap, sfml
---


# Question
Title: What is the best type of c# timer to use with a Unity game that uses many timers simultaneously?
I am developing a stand-alone 3d game in Unity that will have anywhere from 1 to 200 timers running simultaneously. There will be a GameObject containing 1 timer. For this game timer durations will range from 5 minutes to 4 days. There will not be any countdown displays or any UI for the timers.

Each object is a prefab, with all the necessary materials included. An attached script will handle the timer and all the necessary code to change the materials and make any sound effects. Once the timer is expired, the user will then click on the object again, and the object will be destroyed, and the user's inventory will be adjusted.

If the user wants to save or end the game before all the timers are done, the start value of the still running timers is to be saved to an XML file such that when the game is started again, any still running timers will be checked to see if they have expired, where the object's materials will be changed appropriately.

I am still trying to figure out what type of timer to use, and see also if there are any suggestions for saving and calculating times over several days.

What class(es) of timers should I use? Are there any special issues I should look out for in terms of performance?

# Answer
With so many timers, you are better off with setting ExpirationTime for each of your events.

When you need to start a "timer" set the events expiration time to "now" + "timer duration". Then add just one timer that will run e.g. each second and check all the "expiration times" and fire events when their time has come.
> 3 votes

# Answer
Recognizing time is pretty expensive but you can do it just once with a System.Timers.Timer and let that drive your timers. I.e.:

```
public class EfficientTimer ()
{
    //A static timer that drives all other timers; ticks every .1 seconds
    static System.Timers.Timer GlobalTimer = new System.Timers.Timer (100);

    //What the EfficientTimer keeps track of time with
    public uint MyTimerCount = 0;

    public EfficientTimer ()
    {
        GlobalTimer.Elapsed +=
            //Function that increases MyTimerCount every tick of GlobalTimer
            (object sender, System.Timers.ElapsedEventArgs e) => MyTimerCount++;
    }

    public float ToSeconds ()
    {
        //Returns the time in seconds
        return .1f * MyTimerCount;
    }
}

```

With the above class, you could have thousands of timers running simultaneously without breaking a sweat. When you're done with one, you can even recycle it by setting MyTimerCount to 0 instead of sending it to the garbage collector.
> 0 votes

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


# Question
Title: Basic C# Script in Unity3D for firing a bullet (not working)
I am working on a 2D top-down view game. I am trying to get my player to fire a bullet, when spacebar is pressed. I added a component to my player (a bullet sprite) and placed it under his gun (so you can't see it). I added a debug message "Shoot" to make sure that whenever I hit spacebar it gets registered - however, the bullet never shoots. I get the message

> *UnassignedReferenceException: The variable bulletPrefab of ShootBullet has not been assigned*

Here is my script:

```
public class ShootBullet : MonoBehaviour {
    public Rigidbody bulletPrefab;
    float attackSpeed = 2f;
    float cooldown;

    void Update () {
        if(Time.time >= cooldown) {
            if(Input.GetKeyDown (KeyCode.Space)) {
                Fire();
                Debug.Log ("Shoot");
            }
        }
    }

    // Fire a bullet
    void Fire() {
        Rigidbody bPrefab = Instantiate(bulletPrefab, transform.position, Quaternion.identity) as Rigidbody;
        bPrefab.AddForce (Vector3.up * 100f);
        cooldown = Time.time + attackSpeed;
    }
}

```

Any ideas?

# Answer
> 1 votes
Assuming you've correctly assigned a valid prefab GameObject to your 'bulletPrefab' variable, it looks like it should work.

You say the "bullet still doesn't fire". Have you ensured that the AddForce method is being called i.e. add some debugging to that Fire() method to ensure it's being hit.

The only other thing I can think of is that you need to be using and referencing a RigidBody2D component instead of RigidBody. It all depends on what target settings you chose for your project i.e. 2D or 3D.

# Answer
> -1 votes
```
public class ShootBullet : MonoBehaviour {
    public GameObject bulletPrefab;
    float attackSpeed = 2f;
    float cooldown;

    void Update () {
        if(Time.time >= cooldown) {
            if(Input.GetKeyDown (KeyCode.Space)) {
                Fire();
                Debug.Log ("Shoot");
            }
        }
    }

    // Fire a bullet
    void Fire() {
        GameObject bPrefab = Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject;
        bPrefab.AddForce (Vector3.up * 100f);
        cooldown = Time.time + attackSpeed;
    }
}

```

The problem you're having here is that you're declaring bulletPrefab as a Rigidbody, Rigidbody is a Component, not an object, you do not instantiate Rigidbodies alone. You instantiate a whole gameObject, with Components such as, transform, SpriteRenderers, Rigidbody, Collider, etc..

Go to your Assets, create a new Prefab. Now create a new gameObject in your scene, and modify the bullet you want to instantiate. After you're all set, drag the gameObject you just created onto the empty prefab, so it knows what it is. And afterwards, drag the Prefab you just created, onto the Public GameObject of your script, so the script will now instantiate a new bullet **Object** everytime you press space.

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