# Question
Title: Will an optional device type specific permission hide my game in the Play Store for those types of devices?
I have heard in many places that if my app uses a permission not applicable to a certain device, it will not show up in the play store for that device. Now, in my code, I am playing audio. I mute that audio whenever there is a phone call by doing this:

```
 private PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_RINGING) {
                    onPhoneCallInterrupt(); //Method I made that mutes audio for phone call
                } else if (state == TelephonyManager.CALL_STATE_IDLE) {
                } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                    onPhoneCallInterrupt(); //Method I made that mutes audio for phone call
                }
        }
    };

```

Now, this uses the following permission in the manifest:

```
<uses-feature android:name="android.permission.READ_PHONE_STATE"  android:required="false" />

```

Will I get any exceptions because I have made the permission optional by doing `android:required = "false"` on devices that don't have phone compatibility (tablets)?

The reason I am so confused on this, is because I am checking if the phone is being used, but I am not using it. So, will my app work on tablets, let alone show up in the play store for them?

Thanks for helping me clear up this confusion,

Ruchir

# Answer
> 6 votes
Yes, Google Play does filter out content that is not appropriate for the current device. If your device doesn't have a camera, no camera apps should be visible to you, however you may still see apps using the camera as a minor feature. The distinction is made by the use of `android:required` when declaring a used feature.

Note that permissions are different from features. Permissions are there for security and you declare the use of permissions by the `<uses-permission>` tag. Features on the other hand is there for compatibility and you declare the use of features by the `<uses-feature>` tag.

Google Play will filter your application based on what features it uses. However even if your never declare any `<uses-feature>` tags in your android-manifest file, you app may still be filtered. This is because Google also reads through all of your declared permissions and infers any feature requirements you haven't explicitly declared. So if you declare the `READ_SMS` permission then this implies the use of the `android.hardware.telephony` feature. So it won't show up on tablets or other devices without phone capability.

Quoting this section here:

> Note: Some system permissions implicitly require the availability of a device feature. For example, if your app requests permission to access to BLUETOOTH, this implicitly requires the FEATURE\_BLUETOOTH device feature. You can disable filtering based on this feature and make your app available to devices without Bluetooth by setting the required attribute to "false" in the tag. For more information about implicitly required device features, read Permissions that Imply Feature Requirements.

So to avoid having your app filtered on Google Play based on a certain feature your app is using you need to explicitly declare it with `android:required` set to false. Do note however that since the feature is no longer guaranteed to be present on the device your app is running on you need to check that the feature exists at run-time.

Example of what your AndroidManifest.xml should contain.

```
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-feature android:name="android.hardware.telephony" android:required="false" />

```

And a quote on how google filters apps based on explicitly declared features. Link

> An explicitly declared feature is one that your application declares in a element. The feature declaration can include an android:required=\["true" | "false"\] attribute (if you are compiling against API level 5 or higher), which lets you specify whether the application absolutely requires the feature and cannot function properly without it ("true"), or whether the application prefers to use the feature if available, but is designed to run without it ("false").
>
> Google Play handles explicitly declared features in this way:
>
> * If a feature is explicitly declared as being required, Google Play adds the feature to the list of required features for the application. It then filters the application from users on devices that do not provide that feature. For example:
>
> `<uses-feature android:name="android.hardware.camera" android:required="true" />`
>
> * If a feature is explicitly declared as not being required, Google Play does not add the feature to the list of required features. For that reason, an explicitly declared non-required feature is never considered when filtering the application. Even if the device does not provide the declared feature, Google Play will still consider the application compatible with the device and will show it to the user, unless other filtering rules apply. For example:
>
> `<uses-feature android:name="android.hardware.camera" android:required="false" />`
>
> * If a feature is explicitly declared, but without an android:required attribute, Google Play assumes that the feature is required and sets up filtering on it. In general, if your application is designed to run on Android 1.6 and earlier versions, the android:required attribute is not available in the API and Google Play assumes that any and all declarations are required.
>
> Note: By declaring a feature explicitly and including an android:required="false" attribute, you can effectively disable all filtering on Google Play for the specified feature.

Basically if you using permissions that require a feature, see this list, your should explicitly declare that feature with `android:required="false"` next to it and you are good to go. But also since this feature isn't guaranteed to be there you also need to check that the feature exists at run-time before using any methods requiring it. Otherwise a tablet will crash on `Phone.call(5551234)`, while with `android:required="true"` you won't be required to check that the phone is there as it must be since otherwise it your app should have been filtered out. Though you might want to check it anyway as people might install it from other sources, something to consider.

Example of checking for feature at run-time.

```
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
   // This device does have a phone.
   havePhone = true;
}

```

If you have more questions about this I really recommend reading through these:

---
Tags: android, marketing
---


# Question
Title: cannot implement GLSurfaceView.RENDERMODE_WHEN_DIRTY
I'm trying simply to display an openGL surface when I click the screen using GLSurfaceView.RENDERMODE\_WHEN\_DIRTY mode

but the surface does not display when I click it , why ?

my Activity :

```
public class ViewManager extends Activity {
    private GLSurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        surfaceView = new GLSurfaceView(this);
        surfaceView.setEGLContextClientVersion(2);
        surfaceView.setRenderer(new MyRenderer());
        surfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

        surfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event!=null){
                    if (event.getAction()==MotionEvent.ACTION_DOWN)
                        surfaceView.requestRender();
                    return true;
                }else{
                    return false;
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        surfaceView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        surfaceView.onPause();
    }
}

```

# Answer
You have never actually added the surfaceView to the activity. So add this at the end of your activity's onCreate method should fix that.

```
setContentView(surfaceView);

```
> 1 votes

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


title: Scene node system

text:
# Question
Title: Scene node system
I read Real-Time Rendering and the author explains that scene graphs can be used to propagate "materials" and light sources down the hierarchy, that's cool but it really ends right there. There's no explanation on methods and techniques of doing these stuff.

Right now I'm using scene nodes as containers for geometry objects and the farthest I've gone is doing skeletal animation with them.

My question is how such a system of using scene nodes as cameras, lights, shadows etc. can be be implemented. (A reading source will be gratefully accepted as well)

# Answer
> 1 votes
You should have a look at jmonkey engine that is an open source engine implementing a scene graph.

Jmonkey home

By the way, the general idea for material in this case is that each node of the scene has a material definition that, for each material parameter, specifies either inheritance from the previous node or a value

The inheritance is done when traversing the scene for collecting the leaves of the tree for rendering. Each leaf then have it's own material with some elements inherited from upper nodes.

Hope this helps!

---
Tags: scene-graph, scene
---


# Question
Title: Why do my Box2D bodies not fall, even though world.step is called?
I have SFML set up with a Box2D world that has gravity, but my bodies won't move. I `std::cout`'ed the position of the body in the game loop, but it's always at `(0, 14)`!

No errors or warnings, just no movement when there's supposed to be.

I'm quite new to Box2D, so I'm unsure if I'm doing this correctly. What mistake am I making?

**main.cpp**:

```
#include <SFML\Graphics.hpp>
#include <Box2D\Box2D.h>
#include <iostream>
#include <vector>

#include "Box.h"

sf::RenderWindow window;

int main(int argc, char* argv[])
{
    // Initialize stuff here since the things here will only run on startup
    b2Vec2 gravity(0, 9.8f);
    b2World world = b2World(gravity, true);

    // Initialize entities
    b2BodyDef groundBodyDef;
    groundBodyDef.position.Set(0.0f, -10.0f);
    b2Body* groundBody = world.CreateBody(&groundBodyDef);

    b2PolygonShape groundBox;
    groundBox.SetAsBox(50.0f, 10.0f);
    groundBody->CreateFixture(&groundBox, 0.0f);

    Box box;
    box.init(&world, sf::Vector2f(0.0f, 14.0f), sf::Vector2f(15.0f, 15.0f), sf::Color::White);

    sf::RenderWindow window(sf::VideoMode(1200, 840), "Title");

    while (window.isOpen())
    {

        sf::Event e;
        while (window.pollEvent(e))
        {

            if (e.type == sf::Event::Closed)
                window.close();

        }

        // Drawing

        world.Step(1 / 60, 8, 3);

        window.clear();

        box.getSfShape().setPosition(sf::Vector2f(box.getBody()->GetPosition().x / 30.0f, box.getBody()->GetPosition().y / 30.0f));
        box.getSfShape().setRotation(box.getBody()->GetAngle());

        window.draw(box.getSfShape());

        //std::cout << "X : " << box.getSfShape().getPosition().x << " Y : " << box.getSfShape().getPosition().y << std::endl;
        std::cout << "X : " << box.getBody()->GetPosition().x << " Y : " << box.getBody()->GetPosition().y << std::endl;

        window.display();

    }

}

```

**Box.h**:

```
#pragma once

#include <Box2D\Box2D.h>
#include <SFML\Graphics.hpp>

class Box
{

public:
    Box();
    ~Box();

    void init(b2World* world, sf::Vector2f position, sf::Vector2f dimensions, sf::Color color);

    b2Body* getBody() { return body; }
    b2Fixture* getFixture() { return fixture; }

    sf::RectangleShape getSfShape() { return sfmlShape; }

private:
    b2Body* body = nullptr;
    b2Fixture* fixture = nullptr;

    sf::RectangleShape sfmlShape;

};

```

**Box.cpp**:

```
#include "Box.h"

Box::Box()
{

}

Box::~Box()
{

}

void Box::init(b2World * world, sf::Vector2f position, sf::Vector2f dimensions, sf::Color color)
{
    // Creates a body definition
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(position.x, position.y);

    // Create the body into the world
    body = world->CreateBody(&bodyDef);

    // Create the box for the body
    b2PolygonShape boxShape;
    boxShape.SetAsBox(dimensions.x / 2.0f, dimensions.y / 2.0f);

    // Create a fixture for the body
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &boxShape;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.3f;
    fixture = body->CreateFixture(&fixtureDef);

    sfmlShape.setFillColor(color);
    sfmlShape.setPosition(body->GetPosition().x / 30.0f, body->GetPosition().y / 30.0f);
    sfmlShape.setRotation(body->GetAngle());
}

```

# Answer
`1/60` in your `world.Step` call is an **integer division**, which truncates toward zero. The world is being told to step by 0 seconds every iteration of the loop, hence nothing moves.

Write `1.0f / 60.0f` instead.
> 4 votes

---
Tags: c++, physics, box2d, sfml
---


# Question
Title: 2D Physics: storing previous position vs storing velocity
I saw a number of 2d game tutorials and books where previous position of an object was stored in state instead of velocity vector. Velocity is then calculated each frame as a difference between positions.

What are the advantages of that method?

# Answer
> 1 votes
Without knowing exactly the tutorials or books you have read, here is what I can tell you.

To be more precise in terms of physics definition: the vector direction is calculated as the difference between current position and last position. The vector velocity is equal that divided by the time elapsed when going from one position to the other. See: http://www.physicsclassroom.com/class/1DKin/Lesson-1/Speed-and-Velocity

However, when the elapsed time is considered to be the generic "1 frame", i.e. from the last frame to the current, then the vector velocity and the vector direction become the same. In pseudo-code:

```
direction = current_position - past_position
elapsed_time = 1 frame
velocity = direction / elapsed_time

```

So, in general, the main reason for storing the position in the last frame and getting the position in the current frame is that it can be either the only way or the cheapest way of knowing the updated direction (and therefore the updated velocity), i.e. the movement direction in the current frame.

Suppose that you store the direction (or even the velocity) in a given frame. In the next frame, the only way of knowing if the direction (or even the velocity) had changed is if you calculated it again. The reason being that previous direction or previous velocity do not let you know the current direction or current velocity in case movement changed from one frame to the next.

Now, taking into account the tutorials you have mentioned in the comment to your own question, it becomes even clearer. In one of the tutorials the authors says that:

> Now, let's teach our particle how to move with Verlet integration. That's just a fancy way to say that we're going to find out how fast our particle is moving by comparing its position this frame to its position last frame. Why? Because that gives us implicit velocity - any change to the particle's current position will automatically update its velocity

So, as you can see, storing position last frame allows, as I said above, the updated calculation of velocity in the current frame when the object (in the tutorial it's a particle) changes position. If you saved **only** the direction or velocity in the last frame, you wouldn't be able to update it as easily in case the position changed from past to current frame. Therefore, as also pointed in the other tutorial you linked to, saving previous position allows automatic updating of velocity when positions change.

---
Tags: 2d, physics, movement, direction
---


title: Lidgren not starting server properly

text:
# Question
Title: Lidgren not starting server properly
I have a server set up for my game with Lidgren, and it works well when I have it set up on one machine, but if I try to run the server on another machine, I am unable to connect from other machines. I checked my port when running the server, and it says it's closed, despite the lidgren server running. I set the NetPeerConfiguration localaddress to be my ipv4 address and made sure my router was forwarded at this ipv4 address at the port I was running the server on, but still no luck. Here is the relevant server code-

```
NetPeerConfiguration config = new NetPeerConfiguration("Platformer");
IPAddress[] ipv4Addresses = Array.FindAll(Dns.GetHostEntry(string.Empty).AddressList, a => a.AddressFamily == AddressFamily.InterNetwork);
config.LocalAddress = ipv4Addresses[0];
config.Port = 8888;
config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
NetServer server = new NetServer(config);
server.Start();

```

The server says it's being started at the local ip with the right port, and everything *is* forwarded correctly on the router. What is going wrong here?

# Answer
> 1 votes
You say you have checked your ports, but have you opened them first?

Find your Router portforward.com and add a rule for port 8888 (The port the server is listening on) if there is an option for TCP / UDP, choose UDP.

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


# Question
Title: Why there are no 3D games which allow you to move?
I've tried many 3D augmented reality games animations vs. all of them were based on this concept: your head is on one reference point, standing still, they only allow you to turn your head and look around, maybe arms and legs are included but you are not allowed to walk around or change your position. Right?

Is this because of the graphic processor has enough competing power to look around but not enough power to calculate depth perception when you also move? Because when you calculated, at least 120hz\*1080\*1080px\*3(RGB)\*8bits =3359232000 bits data transfer per second is required for monitoring in 1080p resolution with 120 Hz. When you are standing still, 3+ Giga ram may be enough to store calculated datas of other direction of views to cache but when you are moving it may not be enough right? Because your processor will has more like 3 Ghz clk speed and even in most RISC processors calculating new depth perception will require minimum 2-3 assembly instruction step so the processor chip would not be able to support such calculation because even if it achieves to calculate new perception per pixel in 2 steps it will decrease the speed of construction for whole pix lower to 1.5 GHz and the monitor will require minimum 3.3 GHz(I am not counting the dimming information of BLU or RGBs). So, is this the main issue for this or am I wrong and other concerns are included? If so, what are those?

Thanks.

# Answer
As others have already explained, your question is based on a false premise: that most 3D games don't allow you to move. I think what you actually meant is "Why do you control movement in most VR-first games with a controller, rather than with your body?".

The answer is not to do with technical limitations, but human factors. For most games, it's completely unnecessary - and indeed makes for frustrating gameplay - to control your character with your body rather than a controller. Nobody wants to clear out their room to play a VR FPS only to get annoyed with wires and obstacles. There would be too many compromises needed (unless you literally had a huge hall to play in) to make it so that the controls don't interfere with the game.

That doesn't mean that there aren't games where you can at least move a bit by actually moving your body. The controller is your primary mode of ambulation, but you can still look around corners by moving your head etc. On that front, the commenters on your question are right; most games actually *do* let you do that.

Regardless, your reasoning is still wrong. Think of a VR headset as just a set of double monitors; anything that can be done on your actual screen can be done here too. IMU input from a headset is equivalent to WASD + mouse or a controller. It has nothing to do with caching a scene in VRAM or limitations of your graphics card or anything of the sort.

The actual UX pitfalls with VR headsets are resolution, FOV, and latency. People might decide to limit how you control your player based on those for example, to prevent motion sickness among other things.
> 2 votes

---
Tags: 3d, augmented-reality
---


# Question
Title: In Monogame, why does Rectangle.Offset not work?
I have the following code in a default Monogame Game project:

```
protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.Left))
    {
        paddle.Box.Offset(-10, 0);
        Debug.WriteLine(paddle.Box);
    }
    if (Keyboard.GetState().IsKeyDown(Keys.Right))
    {
        paddle.Box.Offset(10, 0);
        Debug.WriteLine(paddle.Box);
    }
    base.Update(gameTime);
}

```

`paddle.Box` is a normal XNA Rectangle.

The problem is that the location of `paddle.Box` does not change after calling any of the `Offset()` overloads, as debugging confirms. If I just assign a new Rectangle, it works, but `Offset` (and `Inflate()`, FWIW) seems to be broken.

What am I doing wrong?

# Answer
This is because Rectangle is a struct, which causes this to be a bit of tricky case. Since structs are passed and returned by value in C#, calling Paddle.Box will return a **copy** of Paddle.Box. After that, you call Offset on this fresh copy of Paddle.Box, but it's the copy, not the rectangle you were trying to change! The copy did change however, but it is discarded straight after that line. This is why calling '= new Rectangle...' does work.

You will encounter similar things with built-in Vector*n* types.Assigning a new object ('... = new ...') is generally what you should do in these scenarios. (On a side-note, I believe that C# even prevents you from doing this on properties and member variables).

Edit: A more of an actual answer: if you want to use offset, you can do something like this instead:

```
protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.Left))
    {
        Rectangle box = paddle.Box;
        box.Offset(-10, 0);
        paddle.Box = box;
        Debug.WriteLine(paddle.Box);
    }
    if (Keyboard.GetState().IsKeyDown(Keys.Right))
    {
        Rectangle box = paddle.Box;
        box.Offset(10, 0);
        paddle.Box = box;
        Debug.WriteLine(paddle.Box);
    }
    base.Update(gameTime);
}

```
> 4 votes

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


title: VBO rendering crashed with glDrawArrays

text:
# Question
Title: VBO rendering crashed with glDrawArrays
I'm playing around in LWJGL3 and I'm experiencing an issue regarding glDrawArrays.

At glDrawArrays the JVM crashes.

I'm using modern OpenGL and therefore I have my own shaders and matrix calculations. The pipeline I've programmed is quite complex so pasting all the code here isn't of any use.

Vertex shader:

```
#version 330 core

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

layout (location = 0) in vec3 in_position;

void main() {
    gl_Position = (projectionMatrix * viewMatrix * modelMatrix) * vec4(in_position, 1.0f);
}

```

Fragment shader:

```
#version 330 core

void main() {
    gl_FragColor = vec4(1.0f, 0.0, 1.0f, 1.0f);
}

```

I'm trying to draw 1 point to the screen using a VBO. Creation of the VBO:

```
float[] vboData = new float[]{0.0f, 0.0f, 0.0f};
FloatBuffer buffer = BufferUtils.createFloatBuffer(vboData);

vbo_id = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

```

And the rendering of the point using glDrawArrays:

```
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    testShader.bind();
        pipeline.applyMatrices(testShader);

        glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
            glVertexAttribPointer(0, 3, GL_FLOAT, false, 12, 0);
            glDrawArrays(GL_POINTS, 0, 1);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        pipeline.setCameraPosition(new Vector3f(0.0f, 0.0f, 0.0f), new Vector3f(0.0f, 0.0f, 0.0f));
    testShader.unbind();

    GLFWUtils.swapBuffers();

```

Using GLIntercept I managed to get a log of every OpenGL call made:

```
glClearColor(1.000000,0.000000,1.000000,1.000000)
glPointSize(10.000000)
glGenBuffers(1,000000001E0F6FC0)
glBindBuffer(GL_ARRAY_BUFFER,1)
glBufferData(GL_ARRAY_BUFFER,12,0000000025EB8D90,GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER,0)
glCreateProgram()=1
glCreateShader(GL_VERTEX_SHADER)=2
glCreateShader(GL_FRAGMENT_SHADER)=3
glShaderSource(2,1,000000001E0F6FC0,000000001E0F6FC8)
glShaderSource(3,1,000000001E0F6FC0,000000001E0F6FC8)
glCompileShader(2)
glCompileShader(3)
glGetShaderiv(2,GL_COMPILE_STATUS,000000001E0F6FC0)
glGetShaderiv(3,GL_COMPILE_STATUS,000000001E0F6FC0)
glAttachShader(1,2)
glAttachShader(1,3)
glLinkProgram(1)
glEnableVertexAttribArray(0)
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)
glUseProgram(1)
glGetUniformLocation(1,"projectionMatrix")=1
glUniformMatrix4fv(1,1,false,[-0.671312,-0.000000,-0.000000,-0.000000,-0.000000,-0.895083,-0.000000,-0.000000,-0.000000,-0.000000,-1.000020,-1.000000,-0.000000,-0.000000,-0.020000,-0.000000])
glGetUniformLocation(1,"viewMatrix")=2
glUniformMatrix4fv(2,1,false,[1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000])
glGetUniformLocation(1,"modelMatrix")=0
glUniformMatrix4fv(0,1,false,[1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000])
glBindBuffer(GL_ARRAY_BUFFER,0)
glVertexAttribPointer(0,3,GL_FLOAT,false,12,0000000000000000)
glDrawArrays(GL_POINTS,0,1)

```

I've carefully tested a few things:

* The shaders compile and link fine
* The matrices calculated look correct (you can double check inside the GLIntercept log)
* The VBO is correctly created and filled with the correct data
* The attribute pointer ( = layout 1) is enabled
* The matrices are correctly sent to the shader (this happens at pipeline.applyMatrices)

What am I missing?

Interesting debug finding: I'm running this on nVidia. On a Intel graphics CPU it runs, but nothing shows on the screen!

# Answer
Your GLIntercept says `glBindBuffer(GL_ARRAY_BUFFER,0)` right before the call to `glVertexAttribPointer`. So you have no buffer bound to attirbute 0 which will cause a memory violation error causing JVM to crash. You should look into why vbo\_id is 0.
> 3 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: Should I be returning weak/shared_ptrs or unique_ptr's to my resources?
A friend of mine told me instead of normal pointers, I should use unique\_ptr, i asked him why unique\_ptr's if some resources are going to be shares, like multiple grass tiles, or enemies. I currently use this:

```
    std::map<ResourceTextures /* this is just a int */,
    std::unique_ptr<sf::Texture>> _textures;

```

Shouldn't I be using shared\_ptr instead? That way I can keep the reference count, and unload resources as they have 0 references?

Also one more question, currently, I am passing my resource manager in every file, is there a way to make it so that all my functions dont require this:

```
Level(ResourceManager& resMan);
Tiles(ResourceManager& resMan);

```

A level is an array or tiles, should i just make it inherit tiles, so that i don't have to pass around my resourceManager everywhere?

Thanks for the help guys, after 2 years of doing nothing programming, I'm trying to make a simple game!

# Answer
Shared pointers/reference-counted pointers are the correct way of handling data who's lifetime needs to be, well, shared `:)`.

`unique_ptr` means "this object will have only one owner at any given time, when the owner goes away, that object is destroyed with it", while `shared_ptr` means "this object can have many simultaneous owners, the last owner holding a pointer to it that goes away cleans up the object with it".

Now a word of caution: go easy on the shared resources. A shared pointer is in many ways a glorified global variable, and excessive use global data makes for spaghetti and meatballs kind of code.

---

> Also one more question, currently, I am passing my resource manager in every file, is there a way to make it so that all my functions don't require this...

**Don't change that!**

You're doing the right thing by making dependencies explicit. Always prefer passing dependencies via function parameters, it will make your code easier to reason about and easier to test!
> 2 votes

# Answer
Going with a pure standard library approach, `shared_ptr` is the best tool you have for resources. Yes, you want to share resources between all the objects that use them.

I personally dislike `shared_ptr` and generally use a custom ref-counted handle for cases where I really need them, such as with resource handles. There's various features that are *really* handy that `shared_ptr` lacks such as the ability to track who is holding onto all those references (so you can track down reference "leaks" and the like).

Some engines also prefer to merge a few different bits of information into their resource handles, at least in some cases. An engine may want to have streaming load operations so their `Load` functions can't actually return a `shared_ptr` directly and need an extra `future` or some other mechanism tied into their resource handles. Other engines prefer tying the resource name into the handle. None of these are necessary, though.

You shouldn't need to pass your resource manager to a lot of places. For instance, I can't think of many reasons that a `Tiles` class would need one. Likewise, a `LeveL` class only needs the resource manager when you're loading the level and not again. Since there are very specific call chains that need the resource manager you can try moving the parameter to just those functions, which can simplify your code and unbloat your structures quite a bit.
> 3 votes

---
Tags: game-mechanics, sfml, c++
---


# Question
Title: How/where can i learn everything unity2d
I just learnt unity basics and would like to learn everything else related to 2d development beginner to advanced in less time.

Because i dont want to stick to game business/development for a long time.

Any websites if you know that has everything thats mentioned above?

# Answer
Here is a good start http://unity3d.com/learn http://forum.unity3d.com

Virtual Game Lab also have an updated list of resources and tutorials for learning Unity. http://www.virtualgamelab.com/unity-resources.html

My recommendation for you is to pick a couple of old school 2d games and try to remake them. This will make you face real game development problems.

Good luck
> 1 votes

---
Tags: unity, 2d, reinforcement-learning
---


# Question
Title: Adding terrain features to a perlin noise heightmap
I'm currently using Perlin Noise to generate heightmaps and model moisture levels as well as tree density to create terrain (in the form of 2D tilemaps - think dwarf fortress).

How can I generate things like caves, or other landmarks like massive boulders or buildings?

I don't want to model these features (i.e. I don't care about the inside of the cave), I just want the game to be able to say 'there is a cave here' when you're at the x,y position of the cave, and importantly, follow rules about where caves might be (e.g. side of a mountain / rocky areas).

I also want to be able to generate this in a procedural way, similar to perlin noise, so that with any 'seed', the same landmarks will always appear.

I'm struggling to think of a way to create these features, and have them always reappear with the same seed. Does anyone have any ideas? :)

# Answer
Depending on your perlin noise implementation you may have some kind of pseudo random 0..1 float generation . In my implementation I use a gradient array and a permutation table and given two int coords i get a value :

```
private float pseudoRandomFromPerm(int x, int y)
{
    return grad[(x + p[y & 255]+Seed) % grad.GetLength(0)];
}

```

I also have a 3d version of that and it looks like this:

```
private float pseudoRandomFromPerm(int x, int y, int z)
{
    return grad[(x + p[y + p[z & 255] & 255]+Seed) % grad.GetLength(0)];
}

```

So assuming that in your perlin algorithm you call a 2d generator at x,y , try using a 3d generator at x,y ; call it with z=0 in terrain generation call it with z=1000 (take some distance from zero) to 'decide' if in x,y there's a cave or a building or anything else. When you get the value for `v=pseudorandom3d(x,y,1000)` manage the results (assuming it is in 0..1 range)

```
if v<=0.05 and (current terrain conditions) then
 cave entrance
else if v>0.05 and v<=0.07 and (current terrain conditions) then
 building
...

```
> 2 votes

---
Tags: tiles, tilemap, procedural-generation, terrain, perlin-noise
---


title: LibGDX : Textfield input type

text:
# Question
Title: LibGDX : Textfield input type
I want to change TextField input type . When I click on the textfield the android keyboard appears with all the symbols , but I want only numbers and dot (**.**) .

```
TextFieldStyle textFieldStyle = new TextFieldStyle(font_38, Color.valueOf("646b6c"), getDrawable(atlas.findRegion("textField_cursor")), getDrawable(atlas.findRegion("textField_selection")), getDrawable(atlas.findRegion("textField_bg")));
TextField textField = new TextField("", textFieldStyle);
textField .setTextFieldFilter(new TextFieldFilter.DigitsOnlyFilter());

```

I have done in this way but here the only inputs are numbers and there is no dot . And when I click on the textfield again android keyboard appears with all the symbols , but I can type only numbers . There is a keyboard in android only with numbers , how to open it instead of all the symbols keyboard and type numbers and dot?

# Answer
> 7 votes
I found out a solution to your other problem. To allow the typing of a dot you should create your own implementation of `TextFieldFilter` like this.

```
public class DigitFilter implements TextFieldFilter {

private char[] accepted;

public DigitFilter() {
    accepted = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'};
}

@Override
public boolean acceptChar(TextField textField, char c) {
    for (char a : accepted)
        if (a == c) return true;
    return false;
}}

```

This simple solution should work with any kind of input you may want to allow.

---
Tags: libgdx, input, scene2d
---


# Question
Title: XNA Advanced font rendering (outline, shadows, etc)
I am looking for a tool that will output spritefonts for XNA consumption that have an outline effect. I know that this can be done by rendering the text multiple times, but I'd like to take care of it in the content pipeline.

The options that I was able to find reference to were hosted at sites that are now offline. I know Nuclex has a vector font option, but again, I'd like to stick with sprite fonts and handle the rendering at compile time.

If anyone can link to an archived copy of those free tools, it would be appreciated.

# Answer
> 0 votes
Not shure about tool but I think you can do it using custom shader. For example, draw text to render target, then draw it again, but set outline color for pixels it is near letter pixel. Also you can use bitmap fonts and stylize it as you wish.

---
Tags: xna, outline
---


# Question
Title: Creating a seamless open world 2d game map
I'm creating an open world game similar to Pokemon. Should I load the full map, or divide it into chunks and load only the the nearby area? I don't want my user to get to a point where it will transition between maps, like Pokemon.

If I were to split it into chunks, how could I load them seamlessly?

# Answer
Short answer: Depends on size and type of world/map, but when in doubt use an tile based solution using an array.

---

You might benefit from creating your map as 2D jigzaw, where you load only the relevant pieces you actually need to show on screen. The simplest way to do this is to treat your map as made up of tiles, as is done in any kind of old scool tile-based game, from Mario to Civilization 1.

Tile-based games usually store the poisition of objects in an array, from which the rows and colums of tiles which need to be visible are extracted and drawn/positioned on screen. This is done based on the player's x/y coordinates in relation to the world coords.

To load new "rows" or "columns" of the map you might simply check if the player is getting close to the edge of the screen and then start to scroll the map and load/draw new rows or columns from the array as needed.

For some examples see this tutorial:

http://gamedevelopment.tutsplus.com/tutorials/an-introduction-to-creating-a-tile-map-engine--gamedev-10900

I picked up the techniques myself over 10 years ago when doing Flash games via these excellent (but outdated code-wise) tutorials. The code and examples still make sense, but will likely not work in newer versions of Flash):

http://oos.moxiecode.com/blog/index.php/tutorials/

Also check out this related question:

Whole map design vs. tiles array design
> 2 votes

# Answer
If not sure how to proceed ,You have 3 methods to do so:

* Keep map-sizes fixed and create same size maps, just manipulate navigation
* Use tiles, and create maps loading scenery each time,(use templates for faster access)
* GET one full big map

Now i have not implemented method 3, but it seems the obvious first attempt to do that, and it may end if you finally decide to limit your big world to array and int size =32;

**FOR METHOD II** you have to implement simple 2d array code, design some tiles (like your example from pokemon, containing desert,water,grass, and city style surroundings) and load it from your stored pointer referrence

```
function starter(args:Event)
{
        thumb.startDrag(false, new Tile(track.x, thumb.y, track.width, 0));
}
function stopper(args:Event)
{
        thumb.stopDrag();
}
function mover(args:Event)
{this.Tile={Tile.water[0],Tile.water[1],Tile.grass[3]};}//each as in constructor
void(int * point){//img here}

```

**For method I** You will need a bit work here ,and create templates to each design of tiles and fix them ...like saying array is fixed for 100 tiles \[10X10\] or as per your game window size And as per your question you want them to be seamless so load arrays

a\[10\]\[10\] and a\[10-20\]\[10-20\], alongwith add temporary array store for half list that is

b\[10-15\]\[10-15\]=a\[10-20\]\[10-20\]:

And implement a Camera type function that focuses your character, so map moves along with character and you move around seamlessly

*Hope this answers your question...*

referrence http://pygame.org/project-pyMap+-+2D+Tile+Mapping-2769-.html

http://students.4j.lane.edu/~bortega23/ArcuzGuide.html map section in game arcuz, you may alos implement minimap, and create further zoom on same data as in this game

unity 3d tutorials for game point lightsource & camera view
> 1 votes

# Answer
When developing open sandbox games you always have to deal with this problem, sometimes the map is splited in grid(DayZ Standalone), sectors(Battlestar galactica), voxels(EVE) or zones (like pokemon) and sometimes it's stored in RAM, it only depends on the mapsize.

If you have a 255x255 map that stores just integers (0: water, 1: grass, etc) it'd be (255x255x4) 260100 bytes (254 kB), so you can store the entire map in an array on ram, else, if you have a more complex datastructure for each tile or you have more tiles you gonna have tu chunk the data.

In 2D games I like chunk it in tiles, and load the current cell and adjacents that i need every time "currentcell" changes, remember that this is just a "logic" division.

You can store the entire map in different ways, form DDBB to .dat files or .JSON, it doesn't matter just load the new cells from storing before your char goes in and you will have an enviable performance.
> 1 votes

---
Tags: game-design, maps, open-world
---


# Question
Title: How can I make a progress bar for EXP in JavaScript?
So I am making an incremental game with JavaScript, HTML5, and CSS, I need to have this bar that is essentially a `div` with a `p` element in it "fill up" as the player earns more points through sacrifice. All the ways I saw to do this on Google required other CSS code that messed up the spacing and such of my whole page.

Here is a non-functioning idea of how it should look. I basically need the `Div` to fill with any color behind the `p` element:

```
function expCalc(){
 var expC = exp;
 var expN = expC + clickCount + modif;
  exp = exp + expN;
 getElementById("exp").innerHTML = exp;
}
```

```
div#ovvw-c{
float: center;
border: 3px solid green;
width: 3.3%;
height: 50%;
text-align: center;
margin-top:1%;
margin-left:49.25%;
margin-bottom: 1%;
background-color: rgba(255, 255, 255, .5);
}
.pbar{
 transform: rotate(270deg);
 margin-right:4px;
 margin-top:250px;
 text-align:center;
 font-size:20px;
 font-weight:900;
}
```

```
<div id="ovvw-c">
<p class="pbar">Hatchling:<span id="exp">0</span>/<span id="expMax">100</span></p>
</div>
```

I understand that my coding is probably sub-par so any constructive criticisms would be appreciated but my main question is how to turn the `div` into a progress bar with minimal changes to size/spacing/CSS in general. Thanks!

# Answer
This is a bit of a hackjob. I'm no CSS/HTML pro, and I'm hoping someone else will chime in with a better solution for you. That said, one option would be something like this:

```
<div id="ovvw-c">
  <div class="pbar">
    <div id="fillbar" style="width: 270px"></div>
    <div id="pbartext">
      Hatchling:
      <span id="exp">0</span>
      /
      <span id="expMax">100</span>
    </div>
  </div>
</div>

```

With some slight changes/additions to the CSS:

```
div#ovvw-c{
  ... (same as before)
}
div#fillbar{
  background-color: green;
  height: 50px;
  margin: 0px 0px -35px 30px;
}
div#pbartext{
  float: left;
  margin-left: 48px;
}
.pbar{
  transform: rotate(270deg);
  margin-right:2px;
  margin-top:250px;
  text-align:center;
  font-size:20px;
  font-weight:900;
}

```

Then you just change the width style of the fillbar to match whatever percent you want at run-time.

(Since this is hacked together, it looks like width=0 to width=2 are effectively 0%, and width=268 to width=270 is effectively 100%. So, percentage * 2.7 gets a pretty good scaling.)

Some easier-to-miss changes:

* pbar's margin-right is 2px instead of 4px.
* Changed pbar from a paragraph tag to a div.
> 1 votes

# Answer
Since this is an html5 game then I guess you are already using canvas or at least you know about it. I think this might help.

There are 2 ways I see this could be done: (i) Using a progress tag. (ii)Or you could do this using the canvas tag.

I don't know how to use the former, but I do know how to use the latter.

```
/* Get the canvas element */
 var c = document.getElementById('canvas');

/* Get the canvas' context */
 var ctx = c.getContext('2d');

/* Variables used for bar fill */
 var total = 100,
  hatched = 0;

window.onload = function() {
 /* Fill Rectangle*/
 ctx.fillStyle = "#FF0000";
 ctx.fillRect(0,0,0,c.height);

 /* Fill text */
 ctx.fillStyle = '#000000';
 ctx.font = "30px Arial";
 var text = 'Hatchling: ' + hatched + '/' + total;
 ctx.fillText(text,225,35);
}

function inc () {
 hatched += 10;
 /* Perc (or percentage) takes the answer from hatched/total... */
 var perc = hatched / total;
 /* ... and filled takes perc and multiplies it by canvas.width (700px in this case) */
 var filled;
 filled = perc * c.width;

 ctx.clearRect(0,0,c.width,c.height);

 /* Fill Rectangle*/
 ctx.fillStyle = "#FF0000";
 ctx.fillRect(0,0,filled,c.height);

 if (hatched >= total) {
  hatched = total;
 }

 /* Fill text */
 ctx.fillStyle = '#000000';
 ctx.font = "30px Arial";
 var text = 'Hatchling: ' + hatched + '/' + total;
 ctx.fillText(text,225,35);

}

function dec () {
 hatched -= 10;
 /* Perc (or percentage) takes the answer from hatched/total... */
 var perc = hatched / total;
 /* ... and filled takes perc and multiplies it by canvas.width (700px in this case) */
 var filled;
 filled = perc * c.width;

 ctx.clearRect(0,0,c.width,c.height);

 /* Fill Rectangle*/
 ctx.fillStyle = "#FF0000";
 ctx.fillRect(0,0,filled,c.height);

 if (hatched <= 0) {
  hatched = 0;
 }

 /* Fill text */
 ctx.fillStyle = '#000000';
 ctx.font = "30px Arial";
 var text = 'Hatchling: ' + hatched + '/' + total;
 ctx.fillText(text,225,35);
}
```

```
<!DOCTYPE html>
<html>
<head>
 <title>Progress bar example</title>
</head>
<body>
<!-- Use Canvas to draw bar. -->
<canvas id="canvas" width='700px' height='50px' style="border: 2px solid black">
 <p>Your computer doesn't support the canvas tag</p>
</canvas><br>
<br>

<!-- Buttons to increase and decrease values -->
<button type="button" onclick="inc();">Increase!</button>
<button type="button" onclick="dec();">Decrease!</button>

<script type="text/javascript" src="test.js"></script>
</body>
</html>
```

This will be easy to implement into a canvas game and if you are using the DOM then my guess is the progress tag will be much more better.
> 1 votes

---
Tags: javascript, html5, css
---


title: Camera horizontal shift

text:
# Question
Title: Camera horizontal shift
I want stretch my game on two monitors. I use Unity 5.3. This version support the multi-display. But, one camera = one monitor. So, have two perspective cameras (at the same position). I search a "camera horizontal shift" option for create stretch effect. I don't find this option. Is-there a trick ? A solution ?

# Answer
> 1 votes
Yea, once I did this adventure. I can tell you what ever I can recall. Place 2 cameras with different `Viewport Rect` settings. On first camera, set `X` to `0` and `W` to `0.5` and on second one set `X` to `0.5` and `W` to `0.5`. Just like pictures given below. And attach some script to resize camera to full screen(You can try it later. First give a try without it). This could be your starting point. You can play further. :)

---
Tags: camera, perspective
---


title: Keeping camera at player's back

text:
# Question
Title: Keeping camera at player's back
I'm developing a 3D game similar to the Roller Ball game from Unity's tutorials mixed with a runner type game like Subway Surfers. The game uses the arrow keys for control. When the player hits the left or right arrow key, I want the player to do a 90 degree turn and have the camera stay behind the player. My questions are, how would I do this? Would I need to do this in my player controller script and just change the rotation? Or would I need to add some controls to the camera and change the rotation of the camera every time the player hits the right or left key?

# Answer
> 2 votes
This link has solution for your problem. Make a Camera Follow script, attach it to camera and assign `Transform` of player to it. You can further customize it according to your needs

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


# Question
Title: Issues with depth calculation in HLSL shader
I'm currently trying to implement shadow maps in my graphics framework.
I ran into an issue with depth calculations I wasn't able to solve myself (yet). I did a lot of testing and debugging and think I finally localized the problem.

To get the position in light-projection space I do this in the vertex shader:

```
float4 worldPosition = mul(input.position, worldMatrix)
output.lightPosition = mul(worldPosition, lightViewProjectionMatrix);

```

Note that I premultiplied the view and projection matrix on CPU.

To calculate the corresponding uv coordinates I'm doing the following in the pixel shader:

```
float2 shadowCoords;
shadowCoords.x =  input.lightPosition.x / input.lightPosition.w / 2.0f + 0.5f;
shadowCoords.y = -input.lightPosition.y / input.lightPosition.w / 2.0f + 0.5f;

```

This appears correct too, as I used the sampled value as surface colors and it went exactly as expected.

Now I want to calculate the depth (in relation to the light of course) of the current pixel. The corresponding code:

```
float depth = input.lightPosition.z / input.lightPosition.w;

```

(input.lightPosition is the float4 I output in the vertex shader as shown above)
However, this apparently gives wrong results. If I use this depth as surface color (disabling any lighting) I get
, which is obviously wrong. Note that the point light is right above the black line.

Now, if I use `input.position` (which is calculated by multiplying the camera viewprojection-matrix with the world position) to calculate the depth, I get correct results.

I figured this has to be caused by semantics. `input.position` is using SV\_POSITION, while `input.lightPosition` used POSITION0 (I also tried TEXCOORD0 without success). I verified this by modifying the DepthmapShader and got different results when using SV\_POSITION instead of POSITION0. If you need more information I'll happily post them.

---

**Now for the final question**: What semantic do I have to use to properly calculate the depth? As SV\_POSITION is already in use for the actual screen position I can't use that. Or do I have some general missconception? I just can't wrap my head around what's happening and would be glad if someone could help me out.

---

For the sake of completeness, here's my Depthmap-Shader:

```
struct VertexInputType {
    float4 position : POSITION;
};

struct PixelInputType {
    float4 position : SV_POSITION;
    float4 depthPosition : POSITION0;
};

PixelInputType DepthmapVertexShader(VertexInputType input)
{
    PixelInputType output;

    input.position.w = 1.0f;

    float4 worldPosition = mul(input.position, worldMatrix);
    output.position = mul(worldPosition, viewProjectionMatrix);
    output.depthPosition = output.position;

    return output;
}

float4 DepthmapPixelShader(PixelInputType input) : SV_TARGET
{
    float depth = input.depthPosition.z / input.depthPosition.w;
    float4 color = {depth, depth, depth, depth };
    return color;
}

```

**Edit:** I'm constructing the view-projection matrix like that (in response to Tim's answer) (Snippet is located inside of the PointLight class):

```
XMVECTOR dir = XMLoadFloat3(&XMFLOAT3(0, 0, 1));
XMVECTOR up = XMLoadFloat3(&XMFLOAT3(0, 1, 0));
XMVECTOR pos = XMLoadFloat3(&Location);

XMMATRIX proj = XMMatrixPerspectiveFovLH(XM_PIDIV2, 1.f, 0.1f, 1000.f);
XMMATRIX view = XMMatrixLookToLH(pos, dir, up);

return view*proj;

```

Is this valid? Or do I have to do something else? As Tim mentioned it projects on a plane. **How should I setup the matrix** (and how would I write the depth information to texture for the case that this procedure changes?)? (Bonus question: Is there a way to do a 360° shadow map with a single matrix?)

# Answer
> 2 votes
I think the problem lies with lightViewProjectionMatrix, by the looks of things it calculates depth from a plane containing the point light, double check your projection matrix if it actually projects to a point.

Otherwise the depth seems to be calculated correctly, it's not supposed to be linear gradient as you'd might expect because you typically want more accuracy closer to you. And seeing as you export the depth as an rgba-value means you're limited to 8 bits and only 255 different depths, you should return it as an r-value, that way you have 32 bits with 2^32 different depths and much, **MUCH** higher accuracy.

Important to note though:

With modern Direct3D(10+) when creating shadowmaps you don't manually calculate depth, instead you set a new z-buffer, render the scene from the perspective of the light as normal but skip the pixel shader and later you read from that z-buffer. This lets the GPU optimize in ways you can't.

---
Tags: directx, hlsl, shadows, shadow-mapping
---


# Question
Title: Should I use a database for storing game content?
I have a 2D Game written in C++ using SFML. I want to make the game expandable in such a way that content like items or entities could easily be added by adding a line/entry/row to a file or database.

I am looking for something that does not need to be compiled into the program, but instead can be read from and written to at runtime. When would it be appropriate to use a database?

# Answer
> 27 votes
Only use a database if you need a database. That is:

* If you need to perform complex queries often.
* If you have complex data relationships.
* If your data is *huge* and is not likely to fit in memory.

If your game's data satisfies any of these conditions, you might benefit from using a database. Note that these are not very common, and you probably *don't* satisfy any of them. If you do, I would go with SQLite or something with a similar idea of not requiring a running server and being just a library.

Otherwise, use files and load data in memory on startup. If you want the game to be moddable, load this data from both your game's directory and from mods' directories and define how conflicting information might be merged.

Also note that, if you *do* use a database, it might benefit both you and mods' developers to still use files to read initial data and construct the database only when the game loads. Unless the potential size of this database is huge (i.e., more than a few dozen MiB), you might want to use an in-memory database, which is possible in SQLite by specifying `:memory:` as the database path.

# Answer
> 6 votes
I really like MongoDB for game develpoment, it has a really good performance and it's really flexible, easy to use and json-based.

You can just add any field you need in any collection due it's NoSQL Arch, so it fits really well in any "dynamic" enviroment like games.

Give it a peek.

If you are developing some kind of MMO Turn based strategy game, probably you should read about CouchDB, it's an NoSQL Database that has a really good versioning system.

# Answer
> 1 votes
CastleDB is a good option because it is simply an editor that converts a database to a JSON file afterwards. I have seen lots of answers saying a plaintext file is best, so CastleDB is probably the best of both worlds.

---
Tags: c++, sfml, databases
---


title: Implementing grid based selection box

text:
# Question
Title: Implementing grid based selection box
What is a *good* way of implementing a RTS selection box for tiles on a grid? I'm making a game with some similarities to Evil Genius, the building in particular. In that game you click one place, drag the cursor somewhere else and something similar to the GIF below shows.

To do so a grid and a way of translating `mousePosition` to the correct cell is needed. Then a set of `for loops` (one for x and one for y) for executing the necessary action on each cell. My main problem is accounting for the direction of dragging, and in particular when shrinking. My current solution (hastebin here) is rather crude, and I would like a more elegant solution for a more civilized age. Hopefully someone else can think of a easier way of accounting for drag direction, I surely can't.

Any help appreciated.

# Answer
> -1 votes
For anyone interested, here is the solution I (with great help from Draco18s) came up with:

```
void SelectionBox() {

    //Get end position
    Vector3 endCoordinate = FindCoordinate(FindHitPoint(), CellSize());
    int xEnd = (int)endCoordinate.x;
    int zEnd = (int)endCoordinate.z;

    //Return if no change in mouse position
    if (previousX == xEnd && previousZ == zEnd) return;

    temporarySelectedCells.Clear();

    //Get corners of selection rectangle
    int left, right, bottom, top;

    if (xStart > xEnd) {
        left = xEnd;
        right = xStart;
    } else if (xStart < xEnd) {
        left = xStart;
        right = xEnd;
    } else {
        left = xEnd;
        right = left;
    }

    if(zStart > zEnd) {
        bottom = zEnd;
        top = zStart;
    } else if(zStart < zEnd) {
        bottom = zStart;
        top = zEnd;
    } else {
        bottom = zEnd;
        top = bottom;
    }

    // Loop through selected cells and mark as selected
    for(int x = left; x <= right; x++) {
        for (int z = bottom; z <= top; z++) {
            Cell cell = FindCell(x, z);
            AddToSelection(cell);

        }
    }

    // Check if selected cells are still needed (inside selection rectangle)
    for (int i = currentCells.Count - 1; i >= 0; i--) {
        Cell cell = currentCells.ElementAt(i);
        if (!temporarySelectedCells.Contains(cell)  && !selectedCells.Contains(cell)) {
            RemoveFromSelection(cell);
        }
    }

    //Set current position as previous for next frame
    previousX = xEnd;
    previousZ = zEnd;

}

```

# Answer
> 0 votes
The approach I would take is to track the selected squares and only add/remove squares as necessary when the drag-to location changes.

On option to making that efficient is a data structure which has good insertion and deletion times such as a R-B tree.

Another option is to maintain the selection in duplicate storage, one in row vector form and one in column vector form. This might be better because as you move you will always be losing or adding a row or column segment, assuming you can transform one to the other efficiently.

Another option is to use an interval tree to track the selected zones.

---
Tags: selection
---


# Question
Title: Swipe and hold character movement not working
Heres my PlayerControl script

```
void Update () {

    foreach (Touch FingerTouch in Input.touches)
    {
        if(FingerTouch.phase == TouchPhase.Began)
        {
            FingerInitialPosition=FingerTouch.position.x;
       }
        if(FingerTouch.phase == TouchPhase.Moved)
        {
            FingerMovedPosition=FingerTouch.position.x;
            if(FingerMovedPosition>FingerInitialPosition)
            {
                charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
           }
            if(FingerMovedPosition<FingerInitialPosition)
            {
                charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);
            }
            }
        if(FingerTouch.phase == TouchPhase.Ended)
        {
            FingerInitialPosition=0f;
            FingerMovedPosition=0f;

        }

    }

}

```

}

The problem here is the player doesn't move when you swipe and hold on the touch screen but only moves when you keep swiping.

Can you please help whats wrong or missing in the code so that the player moves when swiped and held?

# Answer
It only works when you keep swiping because you only update the player's position during the `TouchPhase.Moved` event. If you want to update the player's position even when the user's finger hasn't been moving, you need a default case:

```
void Update () {

    foreach (Touch FingerTouch in Input.touches)
    {
        if(FingerTouch.phase == TouchPhase.Began)
        {
            FingerInitialPosition=FingerTouch.position.x;
        }
        else if(FingerTouch.phase == TouchPhase.Moved)
        {
            FingerMovedPosition=FingerTouch.position.x;
            if(FingerMovedPosition>FingerInitialPosition)
            {
                charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
            }
            else if(FingerMovedPosition<FingerInitialPosition)
            {
                charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);
            }
        }
        else if(FingerTouch.phase == TouchPhase.Ended)
        {
            FingerInitialPosition=0f;
            FingerMovedPosition=0f;

        }
        else //NEW PART!//
        {
            FingerMovedPosition=FingerTouch.position.x;
            if(FingerMovedPosition>FingerInitialPosition)
            {
                charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
            }
            else if(FingerMovedPosition<FingerInitialPosition)
            {
                charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);

            }
        }
    }
}

```

In addition to the new statement, the others are all `else if` as well.
> 1 votes

---
Tags: unity, unityscript, touch, control
---


title: Basic Moving/Anim Script [Unity CSharp]

text:
# Question
Title: Basic Moving/Anim Script [Unity CSharp]
So, I got this to do the anims for my sprite in Unity 2d...

```
using UnityEngine;
using System.Collections;

public class Move : MonoBehaviour {
public float Speed = 2;
Animator anim;
// Use this for initialization
void Start () {
    anim = GetComponent<Animator>();
}

void FixedUpdate () {
    rigidbody2D.velocity = new Vector2(Input.GetAxis("Horizontal") * Speed, 0);
    anim.SetFloat("HorizontalSpeed", Mathf.Abs(rigidbody2D.velocity.x));

if(transform.localScale.x > 0 && rigidbody2D.velocity.x  < 0)
    transform.localScale = new Vector3(-1, 1, 1);

if(transform.localScale.x < 0 && rigidbody2D.velocity.x > 0)
    transform.localScale = new Vector3(1, 1, 1);

}
}

```

That works fine... then I add the script so he can move up and down. (the previous was moving left+right)

```
using UnityEngine;
using System.Collections;

public class UpMove : MonoBehaviour {
public float VerticalSpeed = 2;
Animator anim;
// Use this for initialization
void Start () {
    anim = GetComponent<Animator>();
}

void FixedUpdate () {
    rigidbody2D.velocity = new Vector2(Input.GetAxis("Vertical") * VerticalSpeed, 0);
    anim.SetFloat("VerticalSpeed", Mathf.Abs(rigidbody2D.velocity.y));
}
}

```

Welll.. The second script doesn't do anything. I've been working at this (rookie noobness) for around an hour now.. so pls pls pls.

# Answer
> 0 votes
You're asking for the `y` property of the Vector2 you created, which is 0. You set the input to `vec2.x`

Try:

```
void FixedUpdate () {
    rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, Input.GetAxis("Vertical") * VerticalSpeed);
    anim.SetFloat("VerticalSpeed", Mathf.Abs(rigidbody2D.velocity.y));
}

```

Do same change for the `Horizontal` code too. Change `new Vector2(...,0)` to `new Vector2(...,rigidbody2D.velocity.y);`

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


# Question
Title: How to set indent spacing of a tree in libGDX scene2d?
I've been trying to create a customized UI using scene2d library in libGDX. However I am having troubles as I'm trying to set a custom indent spacing on my Tree object.

I have tried to search for the answer but haven't actually found any discussions about this on the internet.

This is the current situation which I am having.

This is how I would prefer it to look like.

All I want is that I could be able to change the size of the margin which is caused by nodes being on different levels. How can I achieve this?

# Answer
As the nodes are just `Actor`s, you could place you node content (the labels and sliders) first in some container like `Table` or `Container` and give the actual content a bit of margin in that wrapper container.

After you explanation about what you want to achieve the above won't work as you want to move the *plus* and *minus* buttons that are used to expand and collapse the `Tree`'s `Tree.Node`s.

I don't think the **Scene2D** `Tree` implementation will allow you to set the indentation level to be anything other than the max of the width of the *plus* and the *minus* `Drawable`s. But there are always ways around that. The bad news is that the field you need to alter is a private field so simply inheriting `Tree` won't allow you to fix it, but if you're willing to get a bit dirty you can achieve what you're looking for using some reflection.

Instead of doing something like this

```
Tree tree = new Tree(skin);

// Add nodes to tree here

```

You could do this;

```
// First create an instance of Tree where the setStyle method is overridden
tree = new Tree(skin) {
    @Override
    public void setStyle(TreeStyle style) {
        super.setStyle(style);

        // After having called the base class's setStyle,
        // use horrible reflection to find and alter the indentSpacing field.
        try {
            Field field = Tree.class.getDeclaredField("indentSpacing");
            field.setAccessible(true);
            field.set(this, 8); // This is how much you want each plus and minus indented.
                                // Normally this is set to something like
                                //     Math.max(style.plus.getMinWidth(), style.minus.getMinWidth())
            System.out.println(field);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
};

// You will likely want to play around with this to make sure the node
// content is not rendered too close to the plus/minus
tree.setIconSpacing(4, 4);

// Add tree nodes here!

```

This is obviously not ideal, but will likely be easier than creating a new version of `Tree` and get the pull request accepted. Only good thing about this approach is that it involves almost no typing for you.

Alternatively you can just copy the `Tree` code and change it accordingly.
> 1 votes

---
Tags: libgdx, tree, scene2d
---


# Question
Title: How do I expose a field with a generic class to the Inspector?
I have some utilities implemented as generic classes.

I would like to have fields of these types exposed to the inspector but they appear to not display.

This test code:

```
[Serializable]
public class TestGenericClass<T>
{
    public string testField;

    public TestGenericClass(T testValue)
    {
        testField = testValue.ToString();
    }
}

[Serializable]
public class TestNormalClass
{
    public string testField;

    public TestNormalClass(string testValue)
    {
        testField = testValue;
    }
}

public class MonoBehaviourClass : MonoBehaviour
{
    public TestGenericClass<string> testGenericClass = new TestGenericClass<string>("generic");
    public TestNormalClass testNormalClass = new TestNormalClass("normal");
}

```

Produces this result:

As you can see the field for the generic class is missing.

How can I expose a field with a generic class to the inspector?

# Answer
I think there are several people who have come across this problem before. The short of it is that there isn't a way to directly serialise the class. However, there are a few workarounds posted in solutions in the unity answers:

here using subclasses:

```
 [Serializable]
 public class GenericClassOfString : GenericClass<String>
 {
 }

 [Serializable]
 public class SomeClass
 {
    public GenericClassOfString stringClassField; //serializes
 }

```

and here using inheritance/interfaces:

```
using UnityEngine;
using System;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using UnityObject = UnityEngine.Object;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;

namespace Assets.Vexe.ShowEmAll
{
    public abstract class SerializedBehaviour : MonoBehaviour, ISerializationCallbackReceiver
    {
        [SerializeField]
        private StrObjDict serializedObjects = new StrObjDict(); // a serializable Dictionary<string, UnityObject>
        [SerializeField]
        private StrStrDict serializedStrings = new StrStrDict(); // a serializable Dictionary<string, string>

        private BinaryFormatter mSerializer;

        private BinaryFormatter serializer
        {
            get
            {
                if (mSerializer == null)
                {
                    mSerializer = new BinaryFormatter();
                    var selector = new SurrogateSelector();

                    Action<Type, ISerializationSurrogate> addSurrogate = (type, surrogate) =>
                        selector.AddSurrogate(type, new StreamingContext(), surrogate);

                    addSurrogate(typeof(Vector3), new Vector3Surrogate());
                    // add more custom surrogates here

                    // create our unity surrogate
                    var unitySurrogate = new AnotherUnityObjectSurrogate(serializedObjects);

                    // get all unity object types
                    var unityTypes = typeof(UnityObject).Assembly.GetTypes()
                                                        .Where(t => typeof(UnityObject).IsAssignableFrom(t))
                                                        .ToArray();

                    // add our surrogate to let the serializer use it to handle unity objects serialization
                    foreach (var t in unityTypes)
                        addSurrogate(t, unitySurrogate);

                    serializer.SurrogateSelector = selector;
                }
                return mSerializer;
            }
        }

        public void OnAfterDeserialize()
        {
            Deserialize();
        }

        public void OnBeforeSerialize()
        {
            Serialize();
        }

        private void Serialize()
        {
            foreach (var field in GetInterfaces())
            {
                var value = field.GetValue(this);
                if (value == null)
                    continue;

                string name = field.Name;
                var obj = value as UnityObject;
                if (obj != null) // the implementor is a UnityEngine.Object
                {
                    serializedObjects[name] = obj; // using the field's name as a key because you can't have two fields with the same name
                }
                else
                {
                    // try to serialize the interface and store the result in our other dictionary
                    using (var stream = new MemoryStream())
                    {
                        serializer.Serialize(stream, value);
                        stream.Flush();
                        serializedObjects.Remove(name); // it could happen that the field might end up in both the dictionaries, ex when you change the implementation of the interface to use a System.Object instead of a UnityObject
                        serializedStrings[name] = Convert.ToBase64String(stream.ToArray());
                    }
                }
            }
        }

        private void Deserialize()
        {
            foreach (var field in GetInterfaces())
            {
                object result = null;
                string name = field.Name;

                // Try fetch member serialized value
                UnityObject obj;
                if (serializedObjects.TryGetValue(name, out obj)) // if the implementor is a UnityObject, then we just fetch the value from our dictionary as the result
                {
                    result = obj;
                }
                else // otherwise, get it from our other dictionary
                {
                    string serializedString;
                    if (serializedStrings.TryGetValue(name, out serializedString))
                    {
                        // deserialize the string back to the original object
                        byte[] bytes = Convert.FromBase64String(serializedString);
                        using (var stream = new MemoryStream(bytes))
                            result = serializer.Deserialize(stream);
                    }
                }

                field.SetValue(this, result);
            }
        }

        private IEnumerable<FieldInfo> GetInterfaces()
        {
            return GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                            .Where(f => !f.IsDefined(typeof(HideInInspector)) && (f.IsPublic || f.IsDefined(typeof(SerializeField))))
                            .Where(f => f.FieldType.IsInterface);
        }
    }

    public interface ITestInterface
    {
        string StringValue { get; set; }
        float FloatValue { get; set; }
        Vector3 Vector3Value { get; set; }
        Transform Target { get; set; }
    }

    [Serializable]
    public class SystemImplementer : ITestInterface
    {
        public string StringValue { get; set; }
        public float FloatValue { get; set; }
        public Vector3 Vector3Value { get; set; }
        public Transform Target { get; set; }
    }

    // This should have its own file
    public class UnityImplementer : MonoBehaviour, ITestInterface
    {
        public string StringValue { get; set; }
        public float FloatValue { get; set; }
        public Vector3 Vector3Value { get; set; }
        public Transform Target { get; set; }
    }

    // Put this in a file on its own inside an "Editor" folder
    [CustomEditor(typeof(SerializationTest))]
    public class SerializationTestEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            var typedTarget = target as SerializationTest;
            if (GUILayout.Button("Set to system implementor"))
                typedTarget.test = new SystemImplementer();
            if (GUILayout.Button("Set to unity implementor"))
                typedTarget.test = UnityEngine.Object.FindObjectOfType<UnityImplementer>() ?? new GameObject().AddComponent<UnityImplementer>();
            if (GUILayout.Button("Print value"))
                Debug.Log(typedTarget.test);
        }
    }
}

```
> 3 votes

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


# Question
Title: Why does writing to a D3DFMT_R32F render target clamp to 1?
I'm currently implementing a picking system. I render some objects in a frame buffer, which has a render target, which has the `D3DFMT_R32F` format.

For each mesh, I set an integer constant evaluator, which is its material index.

My shader is simple: I output the position of each vertex, and for each pixel, I cast the material index in float, and assign this value to the Red channel:

```
int
    ObjectIndex;
float4x4
    WvpXf : WorldViewProjection< string UIWidget = "None"; >;

struct VS_INPUT
{
    float3 Position : POSITION;
};

struct VS_OUTPUT
{
    float4 Position : POSITION;
};

struct PS_OUTPUT
{
    float4 Color : COLOR0;
};

VS_OUTPUT VSMain( const VS_INPUT input )
{
    VS_OUTPUT
        output = (VS_OUTPUT)0;

    output.Position = mul( float4(input.Position, 1), WvpXf );

    return output;
}

PS_OUTPUT PSMain( const VS_OUTPUT input, in  float2 vpos : VPOS )
{
    PS_OUTPUT
        output = (PS_OUTPUT)0;

    output.Color.r = float( ObjectIndex );
    output.Color.gba = 0.0f;

    return output;
}

technique Default
{
    pass P0
    {
        VertexShader = compile vs_3_0 VSMain();
        PixelShader = compile ps_3_0 PSMain();
    }
}

```

The problem I have, is that somehow, the values written in the render target are clamped between `0.0f` and `1.0f`. I've tried to change the rendertarget format, but I always get clamped values...

I don't know what the root of the problem is.

* For information, I have a depth render target attached to the frame buffer.
* I disabled the blend in the render state
* the stencil is disabled

Any ideas?

# Answer
Why are the values clamped to 0-1? Because in non HDR rendering all pixel values are 0-1. If you want values outside that range, you need HDR rendering. That will, of course, *scale* the values across the whole render to fit 0-1 using fancy math, which lets the brightest brights be brighter than their surroundings without being clipped (e.g. an area being solid white or black with no definition).

In the end though, pixel values *must* be between 0 and 1 (inclusive) because *that's the maximum displayable value.*
> -1 votes

---
Tags: directx, fragment-shader, rendertargets, frame-buffer
---


# Question
Title: In Unity, how do I set the window's size?
Say I want a "world map" (maybe think the overworld in ff games) with dimensions 800px by 600px. How would I do that? Is this tied in with the resolution? Because I know you can set the game aspect.

Tutorials don't seem to cover this. For example, in this video, he just sort of drops the sky into the scene. You can see that some parts of the sky is cut off. He fixes this later by setting the pixels to units to 200 instead of 100. However, this all seems arbitrary to me. We don't know how large the sky is now, ie we don't know the dimensions of the sky. How do people fix this problem? Do you just look at the original image and do math to figure out how "large" it is in unity? What happens if you do something like this video where no size is defined?

# Answer
> 1 votes
It depends on your image.

If you have a background image that is say 1920 * 1080px in size, you just have to divide it by the "Pixels to Units" ratio to find out how big in units will the sprite be. So in this case, it'll be 19.2 * 10.8 units for the default 100 Pixels to Units ratio.

If I want the background's width in Unity to be 10 units, then I just need to divide my background's width by the required width. In this case it'll be 1920/10=192 which is the required Pixels to Units ratio for the background. Or if I want a height of 10 units then the ratio will be 1080/10=108.

Now if I know that my players will be playing in a 16:9 aspect ratio and I want my orthographic camera's viewport to have a width of 10 units, then the size of the camera (at least for me in Unity 5.0.1) has to be kept as 2.792129. That way you can modify the pixels to units ratio according to the image's height/width in pixels and the wanted height/width in Unity units respectively.

# Answer
> 0 votes
There are two easy ways to do this :

1. Set the size of your image in `Start()` according to the screen size, by adding a simple

```
    this.transform.localScale.X = Screen.Width * pixelsToUnits;
    this.transform.localScale.Y = Screen.Height * pixelsToUnits;

```
2. Use the image as a UI Image, instead of a gameObject, and make it Scale to fill the whole Canvas in the editor using its Rect Transform, which itself scales to the Screen Size.

# Answer
> 0 votes
Simplest way to do this,

* Create a Quad. Make sure it has position (0,0,0) and scale (1,1,1)
* Keep selecting Quad, drop your Texture in inspector, that will create a new material.
* Set material's shader to Unlit/Texture or Unlit/Transparent (if your image has transparency)
* Create a small script named "ScaleToFit" or any other name you like,

```
using UnityEngine;
using System.Collections;

public class ScaleToFit: MonoBehaviour
{

    float _screenWidth;
    float _screenHeight;

void Start ()
{
    _screenWidth = (Camera.main.orthographicSize * 2) / Screen.height * Screen.width;
    _screenHeight = Camera.main.orthographicSize * 2;
    transform.localScale = new Vector3(_screenWidth,_screenHeight);
}

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

}
}

```

Drop this script to the Quad. That's it. :)

---
Tags: unity, window-management
---


# Question
Title: How can I remove unnecessary nodes from my path?
How do I remove the unnecessary nodes from the path to make it as short as possible? Idealy I'd like the result path to look like the green line. The red thingy is not walkable.

```
        var newPath = new List<Vector3>();
        var nodes = p.vectorPath;
        int lastCp = 0;

        List<int> toRemove = new List<int>();

        for (int i = 2; i < nodes.Count; i++)
        {
            if (IsPassable(nodes[lastCp], nodes[i]))
            {
                toRemove.Add(i - 1);
            }
            else
            {
                lastCp = i - 1;
            }
        }

        for (int i = 0; i < nodes.Count; i++)
        {
            if (!toRemove.Contains(i))
            {
                newPath.Add(nodes[i]);
            }
        }

```

Here's my attempt to solve the problem and it usualy works well but sometimes if I stand next to obstacle I get the orange line in the picture above.

I'm assuming the path has at least 3 nodes.

`nodes` is a list of `Vector3` (the positions of grey dots on picture), `IsPassable` returns true if the path between two given `Vector3` is passable.

`newPath` idealy should contain two points in the case of example path above.

**EDIT**:

I know why the algorithm doesn't work in this case (look at @Draco18s answer below). What I don't know is how to fix it so it always returns the shortest path regardless of start and target location.

# Answer
> 1 votes
Your method works just as you've programmed it: that is, nodes *are* being removed. The problem with getting the orange path instead of the yellow sometimes has to do with the fact that you trimmed Node3 (Node0 being the first, where the character is) and so the first non-trimmed node is *Node10* at the corner with the orange line. Node11 isn't reachable from Node0 because of the obstacle, so your final path is 0 --\> 10 --\> 19 whereas the yellow line is 0 --\> 3 --\> 19.

It is because 0 --\> 4 is uninterrupted (`IsPassable(0,4)` returns true), which causes the removal of Node3.

If you were to trim in reverse you would have similar problems with a destination very close to an obstacle, while the example case here would work beautifully.

---
Tags: algorithm, path-finding
---


title: Combining Pause and Start Menu

text:
# Question
Title: Combining Pause and Start Menu
I got my pause menu working by using this code:

```
using UnityEngine;
using System.Collections;

public class PauseMenu : MonoBehaviour {

public GameObject pauseUI;

private bool paused = false;

void Start()
{
    pauseUI.SetActive(false);
}

void Update()
{
    if(Input.GetButtonDown("Pause"))
    {
        paused = !paused;
    }

    if(paused)
    {
        pauseUI.SetActive(true);
        Time.timeScale = 0;
    }

    if(!paused)
    {
        pauseUI.SetActive(false);
        Time.timeScale = 1;

    }
}

public void Resume()
    {
    paused = false;
    }

public void Restart()
{
    Application.LoadLevel(Application.loadedLevel);
}

public void MainMenu()
{
    // please write a main menu Luke! (using Loadlevel) Then the Main Menu button will work
    Application.LoadLevel(0);
}

public void Quit()
{
    Application.Quit();
}
}

```

sorry for the appearance of the code.

And I wrote a start Menu using this, which includes a background image and 2 buttons.

```
    using UnityEngine;
using System.Collections;

```

public class StartMenu : MonoBehaviour {

```
public GameObject StartUI;
public GameObject startScreenUI;

private bool startit = true;
private bool background = true;

private void Start()
{
    StartUI.SetActive(true);
    startScreenUI.SetActive(true);
    Time.timeScale = 0;

}
void Update()
{

    if (startit)
    {
        Time.timeScale = 0;
    }

    if (!startit)
    {
        Time.timeScale = 1;
        StartUI.SetActive(false);
        startScreenUI.SetActive(false);
    }

}

public void Play()
{
    startit = false;
    background = false;
}

public void Quit()
{
    Application.Quit();
}

}

```

The problem is, once I have included the Start screen and the Pause screen together, the pause screen, although showing up and the buttons working correctly does not pause the game.

I am thinking perhaps a public function, that would be shared between the PauseMenu and the StartMenu script should do the trick?

or should I combine the two scripts into one and manage them together?

I think the problem is related to the StartMenu script automatically updating and setting the Time.timescale to 1 when the start screen is not activated when Update() is called.

I am not quite sure how to go about solving this issue. It already was a real pain to get the start screen image to disappear when the "play" button was pressed and the Play() function called because of the way the UI system works. If there is a work-around that would not involve me having to move the UI around again that would be great!

# Answer
> 0 votes
The startmenu seems to be the source of this bug indeed. Apparently, update on it is called after the update on the pausemenu. The pausemenu will set the timescale to 0 because paused is true, but then the startmenu is changing this back to 1 because startit is false.

I don't see a need for updating the timescale every update. If you were to change it at the moment the start-or pausescreen (dis)appears instead, it should solve your issue. E.g.:

```
public void Play()
{
    startit = false;
    background = false;
    Time.timeScale = 1;
}

```

The same goes for any related actions you are performing in the update calls.

---
Tags: c#, unity, ui-design
---


# Question
Title: Why am I getting this "tag not defined" error?
In the log, it says

```
UnityException: Tag: car is not defined.
  at PlayerController.OnTriggerEnter (UnityEngine.Collider other) [0x00000] in <filename unknown>:0

```

I'm checking against the tag car when colliding, why does this happen? I have tagged the object, see picture below

heres some code

```
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("car"))//error here
    {
        //more code
    }
}

```

# Answer
> 3 votes
The problem was that there weren't actually any tags in Edit \> Project Settings \> Tags and Layers, even though there were in the inspector

---
Tags: unity
---


# Question
Title: How expensive is Wwise's SetRTPCValue method?
In an ideal world I would have an RTPC value that I could set every frame (as it is time-based and needs to count milliseconds). Is this an expensive call or should I not sweat it?

```
AKRESULT AK::SoundEngine::SetRTPCValue(
    const char *    in_pszRtpcName,                                 // Name of the RTPC
    AkRtpcValue     in_value,                                       // Value to set.
    AkGameObjectID  in_gameObjectID = AK_INVALID_GAME_OBJECT        // Associated game object ID

```

);

https://www.audiokinetic.com/library/2015.1.4\_5497/?source=SDK&id=soundengine\__rtpc.html

Since it may make a difference, I'm using this via a plugin for Unity3D.

# Answer
> 3 votes
I don't know concretely "how expensive it is" but I do know that you don't need to sweat it. We're calling `SetRTPCValue` more than a few times per frame without trouble; can't even see it on a profile.

You may or may not run into trouble calling it hundreds of times per frame (I don't know), but a handful of times is just fine.

That said, I can't speak authoritatively on the Unity integration, but I'd imagine it's comparable.

---
Tags: audio, wwise
---


# Question
Title: Is this a correct backward Euler implementation?
I want to simulate a mechanic object like this:

```
init acceleration a;
init velocity v;
init position x;
loop {
  get delta time dt;
  v = v + a*dt;
  x = x + v*dt;
}

```

I use the velocity (which is the derivative of position) at the end of each time step to approximate the new position. So this should be exactly what the backward euler method does.

Do I have an error in reasoning?

# Answer
> 2 votes
Assuming your acceleration is constant, you should be taking the change in velocity into account when calculating your position and therefore you should also update your position first.

Update the position using the current position (xo), the current velocity(vo), **and** the change in velocity due to acceleration (0.5 * a * t^2):

`x = xo + vo * t + 0.5 * a * t^2` (that's delta-time squared)

Then update your velocity (which you're already doing correctly).

`v = vo + a * t`

# Answer
> 1 votes
This is correct mathematics, though a few things I want to point out.

A) your first position value and first velocity value from loop will always be off.

B)if the dt is near zero, or gets rounded to zero, you'll not get any correct vales.

C)you need a reimann sum, not an Euler. :-).

D) you need the program to use average velocity (dv/2) and average acceleration for correct calculations.

Try something like this:

\`

```
Float accel, vel, pos;
Float da,dv,dx;
Loop {
Get(dT)
Get(newAccel);
da = (accel-newAccel)/dT; //FINDS da in m/s2
accel = newAccel;
dv = (da*dT)/2; //uses the average acceleration (IVT) to find dv
dx = (dv*dT)/2; //uses average change in vel (ivt) to find dx
Vel += dv;  //add change in vel
Pos += dx; //add change in pos

}

```

---
Tags: physics, euler-method
---


title: Create.js CPU High load

text:
# Question
Title: Create.js CPU High load
I'm new in Create.js and I'm trying to make countdown progress bar.

I have this simple code:

```
var stage = new createjs.Stage("timerCanvas");

stage.canvas.width = document.getElementById('timerProgress').offsetWidth;
stage.canvas.height = document.getElementById('timerProgress').offsetHeight;

var square = new createjs.Shape();
square.graphics.beginFill('red').drawRect(0, 0, stage.canvas.width, stage.canvas.height);

stage.addChild(square);

createjs.Tween.get(square, { loop: false }).to({ scaleX: 0 }, 90000);

createjs.Ticker.timingMode = createjs.Ticker.RAF;
createjs.Ticker.addEventListener("tick", stage);

```

My canvas width is 1920px and height 5px. My CPU average load is 20%, when this script runs...

I think it is high load, for such simple script. Am I right? If I am, What I'm doing wrong?

# Answer
I am not familiar with create.js, if I wanted to create a loading bar I would use regular JS, with a canvas or CSS and html. You may want to use:

```
lC=document.getElementById("load");
lCC=lC.getContext("2d");
lCBackground="rgba(0,0,0,0)";
lCForeground="red";
function load(a){
    lCC.fillStyle=lCForeground;
    lCC.fillRect(0,0,lC.width*a,lC.height);
    lCC.fillStyle=lCBackground;
    lCC.fillRect(lC.width*a,0,lC.width-lC.width*a,lC.height);
}

```

With

```
<canvas id="load" width="1920" height="5"></canvas>

```

Just call load with the percentage as a decimal (.50=50%)

You can use any CSS Color

To un-render the loading bar use:

```
lCC.clearRect(0,0,lC.width,lC.height);

```

And will rerender when you call load again.

*Note: you can change the color of the loading bar at anytime during the program, and this supports stuff like gradients and images*
> 1 votes

# Answer
Try using this. It draw a bar, fill it up, and then drain it. (You will probably have to change some things so that it works with easeljs):

```
/* Get the canvas element */
 var c = document.getElementById('canvas');

/* Get the canvas' context */
 var ctx = c.getContext('2d');

/* Variables used for bar fill */
 var total = 100,
  hatched = 100;

window.onload = function() {
 /* Fill Rectangle*/
 ctx.fillStyle = "#FF0000";
 ctx.fillRect(0,0,c.width,c.height);
  var id = setInterval(dec,700);
}

function inc () {
 hatched = 100;
}

function dec () {
 hatched -= 4;
 /* Perc (or percentage) takes the answer from hatched/total... */
 var perc = hatched / total;
 /* ... and filled takes perc and multiplies it by canvas.width (700px in this case) */
 var filled = perc * c.width;

 ctx.clearRect(0,0,c.width,c.height);

 /* Fill Rectangle*/
 ctx.fillStyle = "#FF0000";
 ctx.fillRect(0,0,filled,c.height);

 if (hatched <= 0) {
  hatched = 0;
 }
}
```

```
<!DOCTYPE html>
<html>
<head>
 <title>Progress bar example</title>
</head>
<body>
<!-- Use Canvas to draw bar. -->
<canvas id="canvas" width="1920px" height="5px" style="border: 2px solid black">
 <p>Your computer doesn't support the canvas tag</p>
</canvas><br>
<br>

<!-- Buttons to increase and decrease values -->
<button type="button" onclick="inc();">Fill Up</button>

<script type="text/javascript" src="test.js"></script>
</body>
</html>
```

Hopefully this helps. I think using requestAnimationFrame would actually be much more useful.
> 0 votes

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


# Question
Title: Legal restrictions if using Google Analytics on PC game?
I'm thinking of using Google Analytics to collect various user information (including hardware information) in my PC desktop game I'm making with Unity.I figured I can do this by setting up a new tracking property and using Measurement Protocol to send hits to Google Analytics using HTTP.

Are there any legal restrictions on this? After all, I will be collecting hardware information along with gamer behavior. Do I need to inform the user and / or ask for their allowance for this?

# Answer
> 1 votes
I dont think, that you are allowed to collect userdata, without the allowance of the player. But you should have a look at http://www.google.com/analytics/terms/gb.html or http://www.google.com/analytics/terms (for more languages).

# Answer
> 1 votes
Yo have to notify the user and he has to accept, if the user don't want his data collected and you do it anyways you could be in troubles.

Analytics is not the problem, the problem is collecting data without explicit permission.

---
Tags: legal, pc, analytics
---


# Question
Title: Efficient vertex buffer memory management?
I am building a voxel engine with a similar mechanism to minecraft(yes, I know...). It works by loading and unloading individual chunks of 16\*64\*16 cubes each in a square grid around the player. This works fine for small render distances - like a 9x9 square grid of chunks. However, since updating a single vertex buffer entirely with a new mesh of millions of blocks each time a chunk is loaded/unloaded is inefficient, I have designed it so that each chunk has its own VB of fixed size, and rendering the entire world is basically looping through all the buffers, using `d3dDeviceContext->IASetVertexBuffers(...)`.

When I increase the render distance, say to a square grid of 11x11 (around minecraft's large render distance), creating the vertex buffers simply cannot proceed beyond a certain point, and `d3dDevice->CreateBuffer()` returns E\_OUTOFMEMORY.

So my question is: How do i manage the memory usage of the vertices, to both maintain good FPS (not using a single buffer for the entire terrain) and to have decent memory usage?

Additional Details: My vertex datatype is a struct composed of x,y,z coords, u,v texture coords and 3 normal coords. I know it can be improved in ways like a single byte for normals, since in voxels there are only 6 possible directions, however this will come later.

The fixed size of each chunk's vertex buffer is 16\*16\*64\*18 vertices (16\*16\*64 blocks with a maximum of half of the sides showing, or 36/2 vertices max per block). This could also use some work, as each of these buffers is around 10MB.

How do games like minecraft handle this amount of data at once? (not to say i am using 64 blocks high chunks, where minecraft has 256) I have briefly considered using points as vertex shader inputs and expanding them to cubes in the geometry shader, to save 87.5% of the space, but this seems rather intense on the GPU.

# Answer
> 2 votes
i have implemented a minecraft renderer on myself 2 years ago.

You have a vertexbuffer for every chunks. Thats right, so you only need to update that chunk if Anything changes.

Due to the fact you only handle voxels, and voxels have a fixed orientation you dont need any normals in buffer.

You Need to write a complex geometry shader. You dont even need any positions.

The pos of every voxel can be computed from the sv-vertexId. Then You only need a global offset to draw the chunk to the correct Position.

So all in all The only thing you Need for your voxels is a textype (8bit) to access one of the 255 textures in your array.

This will save lot of memory.

The next thing you need is frustum culling, so that the graphics device only renders what your camera really sees.

I think your underating the possibilities of a graphics card... If you have memory problems, compute as much as you can on your video card.

GOOD LUCK

---
Tags: c++, directx11, voxels, memory-efficiency, vertex-buffer
---


title: making an object follow a path libgdx

text:
# Question
Title: making an object follow a path libgdx
I am making a game that has objects that shoot other objects. I need the enemies to follow a path. The easiest way I can think of doing this is by having an array of coordinates and they move between them. But when I make a curve in the path, I don't want to have to put in 100 coordinates. There must be a better way.

# Answer
You can use the Gdx AI that provides you with an API for that :

Also check the wiki :
> 1 votes

# Answer
I don't know Java very well and never touched libgdx but IMHO i think you should use a pathfinder, in a quick google search i found that libgdx has a pathfinder "Method".

If you set a "hardcoded" path for your npc they wont be able to move around obstacles or other npc but if you set a walkable kind of tiles like "path" or "grass" or whatever and implements a pathfinder algorithm your npc gonna walk by themselves.

Depending on your needs you can use the prebuilt libgdx pathfinder algorithm or build your own from scratch.

Good luck mate ;)
> 0 votes

# Answer
It sounds like you need use a spline. A cubic spline is good for this. You can use it to take a group of waypoints in space and create a curved path between all of the points.

The maths can look a bit heavy. I managed to find this site with java examples ( which is easier for me to understand than the actual maths :) ) http://www.paulinternet.nl/?page=bicubic

You can also investigate hermite curves.
> 0 votes

---
Tags: libgdx
---