# Question
Title: How can I load textures in Unity and keep them between scenes?
I have some textures that are used in multiple scenes and I want to keep them in memory to speed up load times between scenes. I know about Resources.Load, but does that always keep it loaded? If a texture is loaded with Resources.Load, will instantiating a prefab with that texture recognize that it's already loaded or will it load its own instance of the texture?

It would be better if it's a method that I can use in code so that I can make a loading screen and not freeze everyhing up. I'm limited to an earlier version of Unity so I don't have access to LoadLevelAsyc.

# Answer
Unity is pretty smart about keeping stuff around that you need in the future. What's more difficult is telling it when to get rid of stuff you don't need anymore.

So yes, once this texture is loaded, it will recognize that and not load it again provided something hasn't removed it from memory in the meantime.
> 2 votes

# Answer
If you are sure you want to keep it around, you can call DontDestroyOnLoad. See http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

If you set that, it will not be destroyed when the scene loads. Keep in mind that you are now explicitly in charge of destroying that object, as it won't otherwise go away. I would therefore make sure to track any object you mark as DontDestroyOnLoad, or you're likely to end up with memory leaks.
> 0 votes

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


title: Where to create scenes?

text:
# Question
Title: Where to create scenes?
I'm starting to develop a 3D game with Unity and 3ds Max. Where do I create levels for my game? Do I create individual objects in 3ds Max and transfer them to Unity, or do I create the whole level in 3ds Max and transfer everything at once to Unity?

How about lightning? Animations? I would like to do these all in 3ds Max and use Unity to create the game mechanics.

# Answer
**Where do I create levels for my game?**

* File -\> New Scene

**Do I create individual objects in 3ds Max and transfer them to Unity, or do I create the whole level in 3ds Max and transfer everything at once to Unity?**

**How about lightning? Animations? I would like to do these all in 3ds Max and use Unity to create the game mechanics.**

* Go ahead, do it! Unity is a great tool to join many different assets (animations, particles, models, etc..) into a single object by attaching them as components, the combination of all these things is called **GameObject**.
> 1 votes

# Answer
Create individual models with modeling software (3ds Max), and import them as game objects in a Unity scene. That way you have more control over individual objects. Lightning also create in Unity.

You can make the level in 3ds Max, then import it as a whole in Unity, but it's (resource) expensive and your game mechanics don't have control over specific level objects (if you want them to be interactive)
> 0 votes

---
Tags: unity, animation, models, level-design, 3dsmax
---


# Question
Title: Bad performance using VBO with OpenGL ES in Android
I'm making an **Android** app and I need to draw some polygons using **OpenGL ES**. I'm able to render them but I'm disappointed with performance. I updated the code to use **VBO** but I didn't notice any improvement. I want to render at **60 frames** per second (**16 ms** per frame).

I have a test project where I render several triangles on the screen. When I render **1000** triangles it takes about **20 ms** per frame (depending on the device).

I want to keep the rendering under **10 ms** because I need the rest (**6 ms**) to perform other calculations (e.g. update positions, detect collisions, etc.).

Here is the code where I render a triangle:

```
public void render(int positionLocation, int colorLocation)
{
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.bufferIndex);
    GLES20.glVertexAttribPointer(positionLocation, Polygon.POSITION_COMPONENT_COUNT, GLES20.GL_FLOAT, false, Polygon.STRIDE, 0);
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);

    GLES20.glUniform4f(colorLocation, this.red, this.green, this.blue, this.alpha);
    GLES20.glDrawArrays(this.mode, 0, this.length);
}

```

https://github.com/mauriciotogneri/test/blob/master/src/com/testopengl/Polygon.java#L51-66

Here is the code where iterate over the triangles:

```
private void renderTriangles()
{
    long start = System.nanoTime();

    for (int i = 0; i < COLUMNS; i++)
    {
        for (int j = 0; j < ROWS; j++)
        {
            float x = (i * TRIANGLE_SIZE) + (TRIANGLE_SIZE / 2);
            float y = (j * TRIANGLE_SIZE) + (TRIANGLE_SIZE / 2);

            moveTo(x, y);

            this.triangles[i][j].render(this.positionLocation, this.colorLocation);
        }
    }

    long stop = System.nanoTime();

    this.totalTime += stop - start;
    this.totalFrames++;

    Log.d("TEST", (this.totalTime / this.totalFrames) / 1000000 + " ms");
}

```

https://github.com/mauriciotogneri/test/blob/master/src/com/testopengl/MapRenderer.java#L117-139

(Change the value of **NUMBER\_OF\_TRIANGLES** to display more triangles)

For what I understand, the method **GLES20.glDrawArrays(...)** takes too much time if I need to call it **1000** times per frame (one per triangle).

Is there another way to render several polygons that doesn't take too much time?

Notes:

* In the example all the triangles have a fixed position on the screen but in the real scenario they will move around
* In the example I assign a random color to each triangle but in the real scenario each of them will have a fixed color

# Answer
> 2 votes
It's slow because you're sending a drawcall for every polygon. And each drawcall means communication with the drivers and the GPU, which is slow (I don't know exactly how it is the OpenGL ES. But on Desktops your target is to minimize the amount of drawcalls).

And that is, where vbo's come in. A Vbo stores all the vertices of an object in a buffer. If you do so, you can render this object with only one drawcall. This means your target should be to pack as many polygons as possible into one vbo.

You are passing a vertex array to the vbo by calling glBufferData. Here is some more detailed explanation: https://stackoverflow.com/questions/5091570/most-basic-working-vbo-example

If you need to render each polygon seperate, you can search for instanced rendering. By using this technique you can render alot of objects (which have the same geometry) and still use just one drawcall.

---
Tags: android, opengl-es, performance, vbo
---


title: Space game: inheritance for spaceships?

text:
# Question
Title: Space game: inheritance for spaceships?
In a space game I'm writing in C++11, I have a class Spaceship. Now I want to create 3 more spaceship types, how should I do?

* `Attack` type: have a weapon
* `Research` type: have a sensor
* `Religious` type: have both a weapon and a sensor.

I think I'll write three classes AttackSpaceship, ResearchSpaceship, ReligiousSpaceship, which all inherits from Spaceship, but I think there is another, better solution for this case.

# Answer
*Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach.*

```
class Weapon {
    public:
        virtual ~Weapon() = default;

        virtual void action() = 0;
};

class AttackWeapon : public Weapon {
    public:
        void action() override {
            // ...
        }
};

class ReligiousWeapon : public Weapon {
    public:
        void action() override {
            // ...
        }
};

class Sensor {
    public:
        virtual ~Sensor() = default;

        virtual void check() = 0;
};

class ResearchSensor : public Sensor {
    public:
        void check() override {
            // ....
        }
};

class ReligiousSensor : public Sensor {
    public:
        void check() override {
            // ...
        }
};

class Spaceship {
    public:
        enum class Type {
            Research,
            Attack,
            Religious
        };

        Spaceship(Type type) {
            switch(type) {
                case Type::Research:
                    m_sensor.reset(new ResearchSensor());
                    break;
                case Type::Attack:
                    m_weapon.reset(new AttackWeapon());
                    break;
                case Type::Religious:
                    m_sensor.reset(new ReligiousSensor());
                    m_weapon.reset(new ReligiousWeapon());
                    break;
            }
        }

        void update() {
            if(m_weapon/* && Keyboard::isKeyPressed(Keyboard::Key::A)*/) {
                m_weapon->action();
            }

            if(m_sensor) {
                m_sensor->check();
            }
        }

    private:
        std::unique_ptr<Weapon> m_weapon;
        std::unique_ptr<Sensor> m_sensor;
};

```
> 5 votes

# Answer
I think it is perfectly fine use inheritance *if* your only plan on having 3 or so subclasses. `AttackSpaceship`, `ResearchSpaceship`, `ReligiousSpaceship` would be fine, but what if six months from now you decide to add 3 more types of ships? What a hassle it would be having to create another class for each new type of ship. Other worse extensibility problems might also come up if you need to extend the hierarchy. For instance, suppose a new type of ship (say a `CivilianFreighterShip`) could use some of the functionality of `AttackSpaceship` and some functionality of `ResearchSpaceship`, but most of the functionality provided by those classes would be misplaces in it (i.e. it shouldn't have attack capabilities but it has a few sensors and shields). Then your options would be to either duplicating code and functionality or sprinkling a bunch of `if` tests on the parent classes to enable/disable features so that your `CivilianFreighterShip` can inherit from them.

So if you aim on making your code more flexible and extensible, which other approaches to take? You could make your space ships configurable. If you think about it, a space ship that can attack doesn't have to be an `AttackSpaceship` class, it just has to have weapons attached to its hull, right? So why not have a single `SpaceShip` class having an array of `Weapons`? The *is a* relationship so common in OOP languages is very overused in places a simple component would be a much simpler an flexible solution.

I should reiterate that if you have a static hierarchy that is not meant to grow, then plain inheritance is fine and might even be simpler and cleaner that components and configuration parameters, however, if the goal if flexibility and extensibility, then a component-based approach will produce much better and saner code.

References you should read before making your decision:

Do a search for "components based architecture" and you should find a lot more.
> 1 votes

---
Tags: c++, inheritance
---


# Question
Title: What's the size of library in unity for android?
In unity3d what is the size of library compiled into apk. Is that affect when i make game without any physics(2d or 3d) or when making 2d or 3d game.

# Answer
> 2 votes
You can see what's in an apk file by renaming it with a .zip extension and using the usual tools to look inside it.

That way, you can see the size of everything included in your build.

---
Tags: unity, android
---


title: Downscaling an asset, still pixellated?

text:
# Question
Title: Downscaling an asset, still pixellated?
I created a rounded rectangle in photoshop, and I rasterized the rectangle before I saved it. Yet, when I try to use the rectangle in libGDX, it looks pixelated. How can I make it so that it's smooth?

Here is how my rectangle looks now:

My original image is 2048x2048, and I'm using batch to rescale it depending on the screen size. For example, this is how I draw the rectangle:

```
    batch.draw(img, Gdx.graphics.getWidth()/2-fitW/2, Gdx.graphics.getHeight()/2-fitH/2, fitW, fitH);

```

Where `fitW` and `fitH` depend on the current screen width and height (arbitrarily set to 300 now). So I'm essentially downscaling the original 2048x2048 rectangle to one that's 300x300. Can this be why the image is not rasterized?

# Answer
This is simply the result of nearest pixel centre scaling, the simplest, fastest, and most horrible form of image scaling.

For this image to be scaled in an acceptable fashion you need two features enabled. You need the texture to have a mipmap, otherwise it is impossible to get good results from heavy downscaling, to get a mipmap all you need to do is tell LibGDX to create one when you load the texture. And you need a reasonable method of filtering enabled for the texture. Depending on use case you may get away with something simpler, but `TextureFilter.MipMapLinearLinear` works for everything, and I don't think there is many devices left where it makes much of a performance difference.

Relevant documentation:
Texture class
setFilter method
> 1 votes

# Answer
Looks to me like any anti-aliasing you see in photoshop after (supposedly) rasterising, is not being applied to the final image , either in general or more specifically when rendered in your program. You may want to check the resultant image in your operating system's image viewer to be very certain that you are not in fact getting the expected result. If this does look correct, it may be due to how `batch.draw()` is rendering your alpha channel, e.g. alpha cutoff values.

Otherwise (and this doesn't look like what's happening in your image, but just in case), jaggies can occur due to the rescaling algorithm used by LibGDX's `batch.draw()` (which may result in unwanted jaggies when downscaling).
> 0 votes

# Answer
You can use an anti aliasing algorithm to fix it. One simple way to do AA is to take multiple samples per destination pixel when you down sample. Here's a link to one such method, called 4-rook ssaa! http://blog.demofox.org/2015/04/23/4-rook-antialiasing-rgss/
> 0 votes

---
Tags: libgdx, graphics
---


# Question
Title: Would flipping a sprite depending on direction be too inhibitive for modders?
For a game I'm making (similar to games like Terraria, Starbound etc.) I want to ensure that the framework is as modder friendly as possible. This leads me to wonder if it would be too inhibitive to modders if I only allowed them to create one sprite, then the game flips the sprite depending on what direction you're walking/facing. The only reason I want to make the game flip sprites is because my file structure is already horrible, and I feel like creating another right/left folder would make the whole think even worse.

# Answer
**Using an atlas:**
You can pack the left and right versions into a single texture for each sprite, and only swap UV's based on the player's direction.

Although **you** may put only left/right images into the textures, will your modders?
A few descriptors to think about:

```
bool AutoFlip;        //Swap UV's based on L/R?
bool ReverseTextures; //Reverse standard "autoflip" direction - who know's why...
bool MirrorUVx;       //Backwards? - who know's why...
bool MirrorUVy;       //Upside-down? - who know's why...

```
> 1 votes

---
Tags: 2d, sprites, modding
---


# Question
Title: How can I use a lookup table for brightness and contrast?
Currently, I implemented a rudimentary brightness and contrast algorithm that changes brightness and contrast pixel by pixel. This was super inefficient performance wise and the algorithm looked a bit strange.

I heard that I can use a lookup table to get values brightness and contrast for a texture 2D image. How can I do something like this in Unity?

Currently in Unity, I have a prefab in which I load a texture 2D image on top of it. That's the image i want to apply brightness and contrast changes to.

# Answer
> 1 votes
Something like the following:

```
public void addContrast(float Contrast)
{
    byte[] contrast_lookup = new byte[256];
    double newValue = 0;
    double c = (100.0 + Contrast) / 100.0;

    c *= c;

    for (int i = 0; i < 256; i++)
    {
        newValue = (double)i;
        newValue /= 255.0;
        newValue -= 0.5;
        newValue *= c;
        newValue += 0.5;
        newValue *= 255;

        if (newValue < 0)
            newValue = 0;
        if (newValue > 255)
            newValue = 255;
        contrast_lookup[i] = (byte)newValue;
    }
}

```

At this point , for each pixel yuo replace G B R with contrast\_lookup(G) contrast\_lookup(B) contrast\_lookup(R)

---
Tags: c#, unity, color, image-processing
---


title: Calculating density of an object

text:
# Question
Title: Calculating density of an object
I'm using Box2D for physics in my game, and one of the things it needs to know when creating a shape for a physics body is the shape's density. I had no idea what value I should specify, so I went to the header file where it's defined, and it says:

> The density, usually in kg/m^2.

I took that to mean that you could find the density for an object by dividing its weight by its size in metres squared. If I do that for a square crate, which I want to weigh 20 kilograms and have a width of 0.72 metres:

```
float32 weightInKg = 20;
float32 metresSquared = 0.72 * 0.72;
float32 density = weightInKg / metresSquared;

```

The density is 38.5802. Is this correct? It also results in a computed mass of 20, which is correct, as the Box2D documentation says the mass is in kg. I've got gravity set to zero if that matters, as the game is top-down.

If I do a similar calculation for the character, a human whose shape is a circle with a radius of 0.5 metres:

```
float32 weightInKg = 80;
float32 metresSquared = pi * (0.5 * 0.5);
float32 density = weightInKg / metresSquared;

```

The density is 101.859. Again, this doesn't seem correct. I've read that a density of 1.0 makes sense for a human in the context of Box2D, so if that were true, I'm just *slightly* over. I've also read that the average density of the human body is 985 kg/m3, but I'm not even sure if my density calculation is correct, so I'm not sure how that figure translates to kg/m2.

# Answer
> 1 votes
Your density calculation is correct. Either the weight of the human is too much, or you have got to make the human bigger. In real life your human would have more volume or less mass. Which one to select is entirely up to you. And since this is top-down, you can expect to get the wrong density of the human with that formula. If it was a side view game, it would still be alright.

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


# Question
Title: How do I calculate rotational impulses in rigid body collisions?
I'm writing a simple 2D physics engine to help me understand the inner workings of physics engines. I'm following Randy Gaul's tutorial which can be found here and It's been extremely useful and interesting. I'm now on the fourth and final article in the series which covers rotation, but I've spent weeks trying to figure it out and I've hit a brick wall. I've looked all over for other tutorials or explanations, but I have yet to find any that help. No matter how I impliment it, to the point of translating the source code of the tutorial to C# I seem to get completely counter intuative behavour.

The first cause of confusion is that the tutorial states that the collision resolution impulse for two bodies according to the tutorial is the first of the equations below, but the source code accompanying the tutorials appears to be using the second. These two don't appear to be equivalent to me, but I may be wrong.

I'm using the second equation in my code, as implemented in the example source code. I alter the angular velocity as follows:

```
angularVelocity += ColumnVector2.crossProduct(contactVector, impulse);

```

Assuming neither of these are the problem, then I must be doing something fundamentally wrong. Can anyone explain, or point me to a good explanation of how to calculate the angular components of my physics engine because I am completely stuck!

Thanks in advance (and sorry for the lengthy question), Adam

# Answer
You're in luck. I did a full translation of Randy Gaul's 2D physics engine into C# and XNA. He hasn't really explained things well for beginners like me.

For your answer, you should just multiply the cross product with the inverse of the inertia of the body. This is from my translation:

```
angularVelocity += inverseInertia * Vector2D.Cross(contactVector, impulse);

```

It works fine for me (just as Fahim Ali Zain said in his answer). I am anyway going to release a series of tutorials properly explaining the code underlying physics engines and introduce extra features like Raycasting, a few weeks in the future maybe.
> 3 votes

# Answer
Whatever collision be, angular momentum is conserved. ie Iw = constant with the coefficient of restitution (in translation, i dont know if its said the same in rotation) u define, and with the moment of inertia, you should be able to figure it out.

And i think this would similar to collisions in 1D, since only one axis is used :)

Goodluck :)
> 3 votes

---
Tags: c#, rotation, physics, collision-resolution, physics-engine
---


# Question
Title: Legal issues around forming an international game dev team
A friend and I have been wanting to collaborate on a mobile app game. It's a 'start small but dream big' kind of venture, where neither of us has much experience, but we're hoping that if we succeed, we could build on it and become a proper full-time game dev studio in the future.

The main issue here is that we're both from different countries, and neither of us wants to risk personal liability in releasing a game without having first formed a LLC. I know the odds of ACTUALLY being personally sued for damages are very low, but it's just not a risk that we want to take.

There seem to be a lot of problems with forming a LLC when both people are in different countries, though. There are multiple laws against having a co-founder, director, or even an employee being someone from a different country.

How do game dev teams or studios consisting of people all around the world get around this problem?

# Answer
In the long term you will not get around taking some financial risks. When your project becomes a failure, separating your personal financial future from that of your company will allow you to sleep much better at night.

The exact laws which govern limited companies differ drastically between different countries. That means a definite answer is not possible when you don't tell us where you and your co-founder are from, and even then the answer should rather come from a lawyer than a game developer. However, there are some options you might want to check with a lawyer:

* Register your company in a 3rd country with a more liberal stance. Yes, there are countries which allow to register a limited company even when nobody resides there. But keep in mind that this might look a bit suspicious.
* Instead of forming one company and hiring a foreign employee, both of you form companies, and then have one contract the other.
> 1 votes

---
Tags: legal, teamwork
---


title: Inspector stuck on Editor Settings

text:
# Question
Title: Inspector stuck on Editor Settings
Probably a silly question, but I'm having an issue where I can't view the properties of an object in the inspector window. It seems to be stuck on "Editor Settings". If I click an object I can't view its properties.

Any idea what's going on it's confused me for the past 20 minutes.

# Answer
The padlock in the top right corner of the image indicates that this inspector panel is in "locked" mode.

Clicking on this icon will toggle the lock on and off.

Further information on this feature is available on the manual page Inspector Options.
> 1 votes

---
Tags: unity
---


# Question
Title: How to calculate collision detection from big rectangle to small rectangle?
I have big rectangle that can move from side to side, its boundaries can't enter the small rectangle inside it, the anchor point is in the middle of both of them.

Let's say the big rect is 1000 * 1000, and the small one is 200 * 200
in the game the small rect is the "camera" and the big rect is the ground, only the ground moves.

The solution can be in any programming language.

Here is some drawing to show what I mean :

# Answer
> 1 votes
It's just some basic maths. There are a lot of sides and tutorials about collision detection. For example this could help: What is the fastest way to work out 2D bounding box intersection? It is really easy, as long as no box rotates. Then it is called AABB (Axis Aligned Bounding Box). It gets a little bit more complicated, if they rotate, but it's still not taht difficult. Just ask Google for "Box Collision Detection"

---
Tags: collision-detection
---


# Question
Title: Unity 5 - Texture/Material rendering issue
I am working on a Minesweeper clone that started as a Unity 4.6 project and ended up as a Unity 5 project. I have cube objects that use Legacy Shaders/Diffuse. I am new to Unity 5, so I am not fully aware of the changes to the shaders.

The following texture on cube objects does not render as it is (I think it used to).

I want the flag appear on the cube as it is. What causes this output and how do I fix it?

# Answer
Turns out, the png file doesn't have any background (I expected there to be a white background behind the flag image). This is how Unity handles textures when the texture file (PNG) doesn't have a background. Get a white background in the texture file and you're good to go.
> 0 votes

---
Tags: unity, textures, shaders, materials
---


title: Making an organized rendering class

text:
# Question
Title: Making an organized rendering class
I'm using LWJGL (opeengl wrapper for Java) and Don't know how to make a renderer class for OpenGL. So In Immediate mode rendering I'd do a method like this to draw quadralaterals.

```
public static void drawQuad(int x, int y, int width, int height) {
    glBegin(GL_QUADS);
    glVertex2f(x, y);
    glVertex2f(x + width, y);
    glVertex2f(x + width, y + height);
    glVertex2f(x, y + height);
    glEnd();
}

```

Now that I want to use OpenGL 3+ , how can I organize code like this into a static rendering class I can call methods like `Renderer.drawRect(x,y, width, height);`? Or if I can make something like a spriteBatch class.

# Answer
> 0 votes
there are plenty of opengl 3+ tutorials out there. Since LWGJL is a thin wrapper, it doesn't matter what language they are in you should be able to adapt them easily. check those out:

http://www.opengl-tutorial.org/

http://www.mbsoftworks.sk/index.php?page=tutorials&series=1

https://www.opengl.org/wiki/Main\_Page

# Answer
> 0 votes
It is quite simple, actually. All you need is to replace the immediate mode draw calls with a Vertex Buffer Object - VBO.

However, updating the VBO at every `drawQuad()` would be very inefficient. The optimal approach would be to batch the vertexes in a system-side vertex array and then update the VBO once per-frame before rendering. I'm not very familiar with Java, but in a Java-like pseudocode, this could look something like this:

```
class Renderer {

    // The OpenGL VBO handle. Initialize it somewhere, like
    // in a class constructor or application startup method.
    GLuint quadVBO;

    // A growable array of 2D points, for the vertexes of quadrilaterals.
    Array<Point2> quadVerts;

    // "Drawing" doesn't really draw anything, it just adds one more quad to the batch.
    void drawQuad(int x, int y, int width, int height) {
        quadVerts.push(Point2D(x, y));
        quadVerts.push(Point2D(x + width, y));
        quadVerts.push(Point2D(x + width, y + height));
        quadVerts.push(Point2D(x, y + height));
    }

    // This will actually perform the OpenGL draw calls.
    void flushBatch() {
        if (quadVerts.isEmpty()) {
            return;
        }

        // Bind the buffer:
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO);

        // Then update the VBO data (use GL_DYNAMIC_DRAW since data is transient):
        glBufferData(GL_ARRAY_BUFFER, quadVerts.size() * sizeof(Point2D), quadVerts.data(), GL_DYNAMIC_DRAW);

        // TODO: Perform a draw call, look into `glDrawArrays` or `glDrawElements`
        // if you plan on using an Index Buffer.

        // Clear the batch after it was drawn, for the next frame:
        quadVerts.clear();
    }
}

```

To learn more about OpenGL Vertex Buffer Objects, check these two tutorials:

---
Tags: java, lwjgl, architecture
---


# Question
Title: How would I create classes for each map tile instead of using a tmx? LibGdx
I am making a top down style game using LibGdx that I want to be randomly generated each new game load.

I already have the algorithm to generate the array for what tile should be what.

But i'm stuck on how I should handle the tile classes.

I have this class called Tile

```
import com.badlogic.gdx.graphics.g2d.Sprite;

public class Tile extends Sprite{ // Should I use sprite??? Seems wrong..

public byte id;

public static Tile[] tiles = new Tile[256];

public static Tile grass = new GrassTile(0);

public Tile(int id) {
    this.id = (byte) id;
    if (tiles[id] != null)
        throw new RuntimeException("Tile Already Exists....");
    tiles[id] = this;
}

}

```

And I want to have multiple classes that exened this class for each tile. For example this is grass.

```
import com.badlogic.gdx.graphics.g2d.Sprite;

public class Tile extends Sprite{

public byte id;

public static Tile[] tiles = new Tile[256];

public static Tile grass = new GrassTile(0);

public Tile(int id) {
    this.id = (byte) id;
    if (tiles[id] != null)
        throw new RuntimeException("Tile Already Exists....");
    tiles[id] = this;
}

}

```

Should these classes be extended off of a sprite? Or some other class from libgdx?

Also These tiles are going to be 16 x 16 that are made up of 4 smaller 8x8 sprites.

# Answer
Think about having only one final Tile class and it defines only the data needed to render and update like the id of the Sprite or TextureRegion

```
public class Tile {

    private int type;
    private int spriteId;

    some other data that you need and that belongs to a Tile
    ...

    public int getType() {
        return type;
    }

    public int getSpriteId() {
        return spriteId;
    }

    public void setSpriteId() {
        this.spriteId = spriteId
    }

}

```

Then you can have a TileMap class with a array of tiles like this:

```
public class TileMap implements Iterable<Tile> {

    private int width;
    private int height;
    private Tile[][] tiles;

    public void setTile( Tile tile, int xpos, int ypos ) {
        tiles[ ypos ][ xpos ] = tile;
    }

    public Tile getTile( int xpos, int ypos ) {
        return tiles[ ypos ][ ypos ];
    }

    ...

    public Iterator<Tile> iterator() {
        ... create your iterator for the array
    }

    ....

}

```

And a TileMapRenderer that has access to a SpriteProvider that contains the sprites in a map within its ids;

```
public class TileMapRenderer() {

    private SpriteProvider spriteProvider;
    private SpriteBatch spriteBatch;

    public TileMapRenderer( SpriteProvider spriteProvider, SpriteBatch spriteBatch ) {
        this.spriteProvider = spriteProvider;
        this.spriteBatch = spriteBatch;
    }

    public void render( TileMap tileMap ) {
        for ( Tile tile : timeMap ) {
            spriteBatch.draw( spriteProvider.getSprite( tile.getSpriteId() ) );
        }
    }

}

```

It is always good to avoid static classes or fields! always try to inject things you need in objects within the constructor or setters. This is just a short sketch and the code is not compiling but should give an basic idea.
> 1 votes

# Answer
Having all Tiles be Actors that draw their sprite in the Actor's `draw()` call is an option. Of course there are many ways to draw a map, but this definitely is one of them. However I would warn against using Sprites.

Since you said all tiles are 16x16px you will likely have very many of them in each level of your game. This would mean that you would have very, very many Sprites.

What I would advise is for you to use Textures because these are very basic objects that do not hold any data besides their image, which means you can easily recycle them. What I do for my games is have one local class that handles all of my textures, because I do not want to be creating a new Texture for every Tile, if they are using the same image.

I have a class that looks exactly like this:

```
class TexturePool implements Disposable {
    private ObjectMap<String, Texture> textures;

    public TexturePool() {
        textures = new ObjectMap<String, Texture>();
    }

    public Texture getTexture(String path) {
        Texture t = textures.get(path);
        if(t == null) {
            t = new Texture(Gdx.files.internal(path));
            textures.put(path, t);
        }

        return t;
    }

    public void clearAll() {
        Entries<String, Texture> e = new Entries<String, Texture>(textures);

        while(e.hasNext()) {
            e.next().value.dispose();
        }
        textures.clear();
    }

    @Override
    public void dispose() {
        clearAll();
    }
}

```

With this class I can very easily ask it for a Texture, and if the Texture has already been loaded it will give it to me, if it has not yet been loaded, then it will be, and it will also be added to the ObjectMap for later use. This ensures you only load each texture exactly once and can re-use them for every Tile (just store a reference to the Texture in each Tile and draw it at the Tile's position in its draw call).
> 1 votes

---
Tags: java, libgdx, textures, sprites
---


title: Where the physics should be put

text:
# Question
Title: Where the physics should be put
I'm studying a book of artificial intelligence applied to games. It shows several algorithms for each argument (movements, path finding.. ecc). Unfortunately (but obviously) it does not explains how to design the code (no book do that i think). I'm using Java (swing + awt + a game loop) to try these algorithms. My question is, where should i put the physics?

In other words, how the relations between my Player class (the object to move in the window) and the Physics class (algorithms of the book) must be implemented?

My Player implements update(float delta) and draw(Graphics g) methods, but i think that within update method i don't have to make calculations, but they should be delegated to another class.

I could know the algorithm that makes the player jump, but i'm very confused about where to place it!

# Answer
> 1 votes
That's how I do it in my 2D fighting game:

The characters object holds only their physics values (position, velocity, acceleration and friction).

Each character contains a set of states (standing, jumping foward, jumping back, weak punch etc.)

When a character change its state, the 'Initialize' method of that state is executed. Inside it I can set the velocity.Y of my character to give it a vertical impulse to jump, so as set the acceleration.Y to give it a gravity to pull it down continuously on each game frame.

The 'Update' method of the current State of the chracter is called once per frame. Inside it is when I execute the code to calculate the physics of the character and consequently update their position.

This design allows the independency of the physics for each state. Because in certain states I would like the character to standing in the middle of the air, in another I would like it to fall slowly and so on.

Excuse my english, I'm just learning.

-- UPDATE --

Here's my physics code:

```
    public void InitializePhysics(float horizontalVelocity, float verticalVelocity,
                                  float horizontalFriction, float verticalFriction,
                                  float horizontalAcceleration, float verticalAcceleration, Entity entity)
    {
        entity.Friction = new Vector2(Math.Abs(horizontalFriction), Math.Abs(verticalFriction));

        var initialImpulse = new Vector2(horizontalVelocity, verticalVelocity);

        var directionFactor = entity.FacingRight ? 1 : -1;

        entity.Acceleration = new Vector2(horizontalAcceleration * directionFactor, verticalAcceleration);

        // This division by 2 is a correction of the Euler Integration. See this article for reference: http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html
        entity.Velocity = new Vector2((initialImpulse.X + (Acceleration.X / 2)) * directionFactor,
                                       initialImpulse.Y + (Acceleration.Y / 2));
    }

    public void UpdatePhysics(Entity entity) {
        entity.Position = new Vector2(entity.Position.X + entity.Velocity.X, entity.Position.Y + entity.Velocity.Y);

        var horizontalVelocity = entity.Velocity.X;

        if (entity.Velocity.X != 0) {
            if (entity.Velocity.X > 0) {
                horizontalVelocity -= entity.Friction.X;

                if (horizontalVelocity < 0) {
                    horizontalVelocity = 0;
                }
            } else if (entity.Velocity.X < 0) {
                horizontalVelocity += entity.Friction.X;

                if (horizontalVelocity > 0) {
                    horizontalVelocity = 0;
                }
            }
        }

        var verticalVelocity = entity.Velocity.Y;

        if (entity.Velocity.Y != 0) {
            if (entity.Velocity.Y > 0) {
                verticalVelocity -= entity.Friction.Y;

                if (verticalVelocity < 0) {
                    verticalVelocity = 0;
                }
            } else if (entity.Velocity.Y < 0) {
                verticalVelocity += entity.Friction.Y;

                if (verticalVelocity > 0) {
                    verticalVelocity = 0;
                }
            }
        }

        entity.Velocity = new Vector2(horizontalVelocity + entity.Acceleration.X, verticalVelocity + entity.Acceleration.Y);
    }

```

# Answer
> 1 votes
your calculations should go into the update method. it's fine to have an AIManager class, that has an update() method itself which gets called in the main update loop.

this AIManager could hold a list of all the Objects that need to be updated. Since you're using java, you could use an interface to declare something to have an AI, and use this interface to iterate over your objects (which could then be completely different Classes) and have interactions managed by this AI manager.

You would do the same for the physics. have something manage the Physics, that iterates over all the objects that implement a physics interface.

# Answer
> 1 votes
You're using Java so I'm going to assume off the bat that you're playing to Java's strong points and writing your game as Object Oriented as you possibly can. When you say you have a game loop I imagine you have a top level class with a main method that loops over your update and draw functions, something like the following (but yours will be far more detailed):

```
class Game {
    Player player;
    void main(){
        while(true){
            update();
            render();
        }
    }
    void update(){
        player.update();
        //etc
    }
    void render(){
        //draw everything to screen
    }
}

```

You're going to have a class for the player and what you want to do is have that class inherit from a base class for objects in your game that need physics applied to them.

```
class PhysicalObject {
    float x_position;
    float y_position;
    float x_velocity;
    float y_velocity;

    void update(){ ... }
    //Add some functions for algorithms:
    void applyGravity(){ ... }
}

```

In all likeliness you're going to want to override the update function of the base class to take things like user input and player states into consideration. Add your algorithms as functions to that base class so you can easily call them from any derived classes in whatever order makes sense for that class.

---
Tags: java, game-design
---


# Question
Title: Rigidbody physics concept: Why translate collision shape on-the-fly instead of mutating it?
Crossposting at https://stackoverflow.com/questions/29993547/rigidbody-physics-concept-why-translate-collision-shape-on-the-fly-instead-of-m

I've spent some time going through physics engine's sourcecode in Java like JBox2D, Phys2D (both 2D) and JBullet (3D).

I observed that, while the rigid bodies move and are mutated in each step, the collision shapes that are attached to them, are not. Instead, they always stay located around the coordinate origin. When checking two rigidbodies for collisions, a "translation" object is fetched from each and is used to translate the two checked shape's vertices (or other defining properties, depending on the shape type) to their attachment's world position on-the-fly. These information are then used to detect collisions and react to them.

I've concluded the main purpose is, that you can reuse the same shape instance for multiple bodies, as they are stateless in the described scenario and save some memory as the needed information are calculated on-the-fly in each step.

However, I currently see more advantage in mutating the shape's positional properties as in their member values. Each shape's aabb and vertices would change ONE TIME in each step, so you don't need to calculate the same vertices multiple times when intersecting one shape to multiple other ones. Plus, you could also change areal properties (damage deformation) of the shape, because it is only used by one body.

So the questions is:

Why is it common to use positionally immutable collision shapes instead of mutable ones?

Edit: Found quite the same question, but without much of an answer at Storing rigid body collision shapes in local or world coordinates

# Answer
One major advantage is that many collision detection operations are more efficient when performed at the origin. A classic example is box vs sphere. When done in a box's local space the tests are very simple axis aligned distance point-plane tests instead of the more costly non-axis aligned planes.

Furthermore objects moving through space may not actually hit anything for a frame so there is no value performing the costly operation of moving the shape and all of its vertices each frame. Instead the transform of the rigid body is updated every frame - it has to be to integrate linear and angular velocities, anyways - and then the axis aligned bounding box of the shape(s) is updated. Only when potential intersection exist do the costly tests get performed. If we had to move the vertices every frame it would be far too expensive. Good collision detection libraries are a series of steps that start from simple (AABB overlap) and move towards more complex (specific pair-wise collision agents) in the hopes that the higher level tests will prune out the costlier ones.
> 4 votes

---
Tags: collision-detection, collision-resolution, physics-engine, rigid-body-dynamics, intersection
---


title: Questions About Game Loops

text:
# Question
Title: Questions About Game Loops
I've been reading up how to lay out a game loop that'll work optimally in both great and not so great conditions but I think I've confused a few techniques together... so I have some questions...

1. Fixed Physics Step: If I fix my physics step because determinism is important in my game, and at some point the game falls behind and needs to catch up, would I need to update multiple times or is there a safe method of updating physics by double or triple steps? If I'm rolling my own physics should I write them in a particular way to facilitate this?
2. Input: If I need to update multiple times before the next frame should I check the input before updating each time or check once and leave the input for the next tick after that to handle?
3. Updating: How often do I really need to update a game so no lag is felt by the player? It seems like you can get away with well under 60tps but at what point do players feel the delay? Are there any drawbacks to updating less frequently than rendering?
4. Networked: If the game is networked through an authoritative server, would all machines have to update their client side predictive movement code at the same rate as the server to avoid constant visible repositioning or would the difference be minimal and virtually undetectable if I resolve potential jittering with smooth position correction?
5. Interpolation: Would interpolating the position of drawn objects between updates be something I'd only need to do if my game updated at a much slower rate than my fps or is it good to interpolate anyway? What would interpolating involve? Running another partial position update just before the draw or updating the next position in advance and using the partial step percentage (time passed sine last update) to advance positions that percentage between the current and next steps?
6. Render Timing: Is there a way (or a need) to draw a frame at the last moment before the screen refreshes?
7. Sleeping: After a draw when I don't yet need to update I should hand the thread back over to the OS, yeah? If I'm making a cross-platform game and some operating systems might wake my thread up a little earlier or later than I've specified is there a chance that might affect the game at all if my physics is fixed?

# Answer
> 2 votes
I'll answer multiple related questions at once, because it's easier to understand when everything related is at one place.

---

The best way your game loop can be implemented is to have **constant game speed** and **variable FPS**. Note that this does not mean it's the easiest way. Why is it so and how it can be implemented is nicely described in deWitters article, I'll just post a quick overview.

*Note: 'Update FPS' is basically 'Game speed' from deWitters article*

## Updating (1., 2., 3.)

In short, your game loop should call `update_game()` at constant manageable rate, say 25FPS (as in deWitters article). The reasons why your game speed should be rather lower than higher are, that it:

1. Assures game runs smoothly on slower hardware
2. Prevents big floating-point-number-calculation-inaccuracy by simply lowering the frequency of calculations.

Note that handling user input is one of those things, which should be handled in `update_game()` as well, (among the aforementioned physics handling). 25FPS for input is pretty good.

As it was mentioned before, in this case, your physics computations will always "catch up", there will be no need for doing multiple calculations. Simultaneously, your independent rendering part `render_game()` can run at 60FPS with some drops, while having no negative effect on handling physics.

As to the question of special care for your physics handling - in this case, you're using **constant** update FPS =\> NO.

## Interpolation (3., 4., 5.,)

If you only read the updating part of this answer and went for the implementation right away, you'd notice that you would be getting nice rendering FPS and always constant update FPS, but the movement would be jerky. That's because the data is still updated only 25FPS! This is when the interpolation comes in.

In render loop, you can **predict** where, let's say a ball, should be in this particular moment based on the current (means calculated the last update frame) position, velocity, orientation and delta time from the last updated frame. This is what we would be doing in the `update_game()` (however, we would add here some other things as well, for example collision detection) if we had unlimited or very high update FPS. Sure, the drawback of inaccuracy is still there even in `render_game()`, but it's not that big, because:

* We are calculating the data at the moment from last 1/25th of second, which is pretty accurate.
* All the heavy-stuff like collision detection is gone. Player won't notice that your ball went a bit behind the wall for *less than 1/25th of second*

### Implementation

I'll just use the ball example and I'll use the example implementation from deWitters article. You have to check it out, it's all there.

Something like this would be in your `update_loop()` (ignoring collision detection and stuff like that)

```
position = position + speed;

```

And something like this in your `render_loop()`

```
view_position = position + (speed * interpolation)

```

where interpolation is a value between `0.0` and `1.0` and represents the progress between two `update_game()` calls.

## Rendering (6.)

Using the constant game speed and variable FPS strategy, you are rendering frequently enough not to have to worry about this. Anyway, games often use so-called double-buffering, which basically means that one frame is being drawn to the screen and the other is being written to the buffer, based on the current data. After that is completed, they swap (= change their roles). This means that you always see things **one frame late**, but that is no big deal.

As for the question itself, we are interpolating and we have separate update and render loops, remember? It's the most accurate method I know of.

## Networking (4.)

Here, you always **have to** interpolate, even in the `update_loop()`. You won't be probably getting data every 1/25th of second, not to mention lags. Which means, that if you don't now the things at the moment, **predict them**. You have no better shot.

## Sleeping (7.)

You have 2-priority game loop:

1. `update_game()`, gets called at least 25 times per second
2. `render_game()`, gets called either as frequently as it can, or it has some upper limit, let's say 60 FPS

If we have the latter case, we can take the rest of time and let the computer "sleep". Chances are that this won't be *exact*, but based on what you used, it may be *exact enough*. In most cases, however, this **will not affect** your update loop.

# Answer
> 1 votes
to 1, 3, 7: I assume by "the game falls behind and needs to catch up" you mean, your update-rendering cicles are taking more time than they should, depending on the desired UPS and FPS length. In that case: In the methods for updating physics I know, the physical behavior changes when you change the deltaT time step. This would mean, if you simply take the passed time since the last update call for deltaT, falling and bouncing objects would behave different all the time, and the physics in your world would constantly change.

So the deltaT taking into calculation should always be the same. You could devide the passed time into segments of the size of your desired deltaT and the call the physical update multiple times "to catch up", as you said. In my cases rather always used the same deltaT and wrote my game loop in a way, that preferred updating over rendering, because there was never any reason to render, if I didn't update the physics. I would have drawn the exact same image like before. Furthermore, each game loop round (update+rendering) was desired to have a consant time to avoid further complication.

my gameloop basically is:

* get the time span, the previous loop round took till now, consider the previous round might have taken too long or was too short. Use this span and the desired round length, depending on the set fps to determine, when the current round should end. The ending time would be the time it would have taken for the previous round and the current round to end regularly, taking the exact desired time. Therefore, current round might be desired to be a little longer or shorter than the previous one to meet this case.

cycleEndTime = TimeNow() + cycleLength + getLeftTime(cycleEndTime);
* then, update physics (no matter what)
* check, if this cycle still got time. If not, skip drawing and continue with next loop round. I can skip for at least 6 times, before I can notice a skip in drawing with my eyes in 60 fps.
* after drawing, if still got time, Thread.sleep till cycle end. If, like you wrote in 7., the sleep is woken up too soon, I will detect this this in the described manner for calculating cycleEndTime and the upcoming loop round would be taking up the time by being longer.

So when changing the FPS and thereby the desired length of a loop round, the game would be updated more frequently in the same "viewer's time". The physics would be updated more often in the same time, objects would move faster, but the physical behaviour ittself would not change due to constant deltaT.

---
Tags: game-loop
---


title: How can I customize button graphics?

text:
# Question
Title: How can I customize button graphics?
Inside my buttons I added some variables (as you can see in the code below).

```
public UnityEngine.UI.Text itemInfo;
void Update () {
    itemInfo.text = itemName + "\nCost: " + (costo_stringa = ConvertiroreProiettili.Instance.GetCurrencyInString(costo, false, false))
    + "\nBullets: " + tickValue + "/s" + "\nLiv: " + count;

```

but in this way are one below the other as a list, how do I order them as I will, and also add a picture like this:

# Answer
A UI button by default contains one image and one label inside it, but you can change that. You can remove the label from within the button, and instead add several items, making the button a container of several other elements, hence creating whatever layout you want.

It might be easier if you created a panel, put in it all the info you wanted, and then just add the button script to handle clicks.

For more information on how to create a panel, or other complex gui elements, I recommend the UI tutorials:

https://unity3d.com/learn/tutorials/modules/beginner/ui

And there are a few live training sessions that show good exmplaes of stuff you can do with the GUI such as this, this, this and this
> 0 votes

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


# Question
Title: finding a path from one point to another with obstacles help
Im building a tile based game and im implementing my path finding algorithm. Currently, it can find a path from point A to point B with no problems. However, if there are obstacles between point A and B, the algorithm will often select the wrong tiles.

When computing a tile's F score, I calculate the cost by adding the number of squares weve moved away from the starting point + the manhattan distance to the destination square. This seems to work fine, but if I encounter a square later on that weve already added to the open list, it will often choose that one as the closest even though the number of squares weve moved away from that the starting point has changed since I originally computed that value.

```
For example:

S = Starting at 0,0
F = Finish at 3,3
X = Obstacle
E = Empty

S E E E E E
E E E E E E
E E E X X E
E E X F E E
E E E E E E

```

My algorithm will compute this path: (0,0), (1,0),(2,0),(3,0),(3,1),(2,1),(2,2),(1,1)

I think when we get to (2,1), my algorithm should be noticing that (1,1) has already been added to the open list. We then re evaluate (1,1)'s total cost to 10 (6 moves away from start, \+ 4 away from Finish (3,3).

Logically, the next step should be ...(2,2),(1,2),(1,3),(1,4)...

I feel like there is something fundamentally wrong with my algorithm. I just cant seem to figure out what it is. Ive been looking at this code for quite some time now. Any help would be appreciated.

Sorry for the absolute wall of code.

```
 private List<Vector2> FindPath_(Node start, Vector2 end)
    {
        if (start.X == end.X && start.Y == end.Y)
        {
            List<Vector2> final = mClosed.Select(node => node.Position).ToList();
            return final;
        }

        int xLeft = start.X - 1;
        int xRight = start.X + 1;
        int yUp = start.Y - 1;
        int yDown = start.Y + 1;

        TileNode left = GetNearestTile_( xLeft, start.Y);
        TileNode right = GetNearestTile_( xRight, start.Y);
        TileNode up = GetNearestTile_(start.X, yUp);
        TileNode down = GetNearestTile_(start.X, yDown);

        List<Node> adjacentNodes = new List<Node>();

        Node lNode = null;
        Node rNode = null;
        Node uNode = null;
        Node dNode = null;

        if (up != null)
        {
            uNode = new Node(new Vector2(start.X, yUp), start.CostFromA + 1, Math.Abs((int)end.X - start.X) + Math.Abs((int)end.Y - (start.Y - 1)), start);
            adjacentNodes.Add(uNode);
        }
        if (left != null)
        {
            lNode = new Node(new Vector2(xLeft, start.Y), start.CostFromA + 1, Math.Abs((int)end.X - (start.X - 1)) + Math.Abs((int)end.Y - start.Y), start);
            adjacentNodes.Add(lNode);
        }
        if (down != null)
        {
            dNode = new Node(new Vector2(start.X, yDown), start.CostFromA + 1, Math.Abs((int)end.X - start.X) + Math.Abs((int)end.Y - (start.Y + 1)), start);
            adjacentNodes.Add(dNode);
        }
        if (right != null)
        {
            rNode = new Node(new Vector2(xRight, start.Y), start.CostFromA + 1, Math.Abs((int)end.X - (start.X + 1)) + Math.Abs((int)end.Y - start.Y), start);
            adjacentNodes.Add(rNode);
        }

        foreach (Node node in adjacentNodes)
        {
            if (ClosedListContainsTile_(node))
            {
                continue;
            }
            else if (!OpenListContainsTile_(node))
            {
                InsertNode(node);
            }
            else if (OpenListContainsTile_(node))
            {
                if (node.Parent != null && node.CostFromA + 1 < node.Parent.CostFromA)
                {
                    node.Parent.CostFromA = node.CostFromA + 1;
                    Node parentNode = mOpen.FirstOrDefault(n => n.X == node.Parent.X && n.Y == node.Parent.Y);
                    int index = mOpen.IndexOf(parentNode);
                    mOpen.RemoveAt(index);
                    InsertNode(parentNode);
                }
            }
        }

        if (mOpen.Count == 0)
            return new List<Vector2>();

        int cost = int.MaxValue;

        Node closest = mOpen[0];

        mOpen.Remove(closest);
        mClosed.Add(closest);

        return FindPath_(closest, end);

    }

    private TileNode GetNearestTile_(int x, int y)
    {
        TileNode tile = null;
        try
        {
            tile = TileMap.GetTileNode(x, y);
            if (tile.Type != TileType.Empty)
                return null;
        }
        catch
        {
            return null;
        }
        return tile;
    }

    private bool OpenListContainsTile_(Node node)
    {
        return mOpen.FirstOrDefault(t => t.X == node.X && t.Y == node.Y) != null;
    }

    private bool ClosedListContainsTile_(Node node)
    {
        return mClosed.FirstOrDefault(t => t.X == node.X && t.Y == node.Y) != null;
    }

    private void InsertNode(Node node)
    {
        int i = 0;
        for (; i < mOpen.Count; i++)
        {
            Node n = mOpen.ElementAt(i);
            if (node.Total <= n.Total)
            {

                break;
            }
        }
        if (i < mOpen.Count)
        {
            mOpen.Insert(i, node);
        }
        else
        {
            mOpen.Add(node);
        }
    }

public class Node
{
    private Vector2 mPosition;
    private Node mParent;

    public Node(Vector2 position, int cost, int estimated, Node parent)
    {
        mPosition = position;
        CostFromA = cost;
        EstimatedCostToB = estimated;
        Total = CostFromA + EstimatedCostToB;
        mParent = parent;
    }

    /// F Score
    public int Total { get; set; }
    /// G Score
    public int CostFromA { get; set; }
    /// H Score
    public int EstimatedCostToB { get; set; }

    public int X { get { return (int) mPosition.X; } }
    public int Y { get { return (int) mPosition.Y; } }

    public Vector2 Position
    {
        get { return mPosition; }
    }

    public Node Parent
    {
        get { return mParent; }
    }
}

```

# Answer
Here is my working AStar implementation built in Java on the LibGdx framework (it should not be too difficult to adapt to C#):

```
public class AStar {
    /**
     * Makes the end passable, if it wasn't already, and then finds the shortest path towards it, using the AStar algorithm.
     * @param start The node to start the search from.
     * @param end The node the search will end at.
     * @param map The map of nodes.
     * @return The path from the start node to the final node (not including the start node).
     */
    public static Path findShortestPath (Node start, Node end, Array<Node> map) {
        Path path = new Path();

        Array<Node> open, closed;
        open = new Array<Node>();
        closed = new Array<Node>();

        // initialize heuristics
        for (Node n : map)
            n.setHeuristic((int)(Math.abs(n.position.x - end.position.x) + Math.abs(n.position.y - end.position.y)));

        open.add(start);
        end.setImpassable(false);

        while (open.size > 0) {
            Node current = getNextNode(open);
            open.removeValue(current, true);
            closed.add(current);

            for (Node neighbor : current.getNeighbors()) {
                if (neighbor.isImpassable() || closed.contains(neighbor, true)) continue;
                if (!open.contains(neighbor, true)) {
                    neighbor.setG(neighbor.getMoveCost() + current.g());
                    neighbor.setParent(current);
                    open.add(neighbor);
                } else {
                    if (neighbor.g() > current.g() + neighbor.getMoveCost()) {
                        neighbor.setG(current.g() + neighbor.getMoveCost());
                        neighbor.setParent(current);
                    }
                }
            }

            if(open.contains(end, true)) {
                path.add(end.addParents(path));
                path.getPath().removeIndex(0);
                return path;
            }
        }

        return null;
    }

    private static Node getNextNode (Array<Node> open) {
        Node n = open.first();
        for (Node n2 : open)
            n = n.f() < n2.f() ? n : n2;
        return n;
    }
}

```

`Path` is just a container for an `Array` of type `Node`.
This is the `Node` class:

```
public class Node {
    private Array<Node> neighbors;
    public Vector2 position;
    private int heuristic, moveCost, G;
    private Node parent;
    private boolean impassable;

    public Node(int x, int y, int moveCost) {
        neighbors = new Array<Node>();
        position = new Vector2(x, y);
        this.moveCost = moveCost;
        G = moveCost;
        impassable = false;
    }

    public void addNeighbor(Node n) {
        neighbors.add(n);
    }

    public Array<Node> getNeighbors () {
        return neighbors;
    }

    public int f() {
        return heuristic + moveCost;
    }

    public int g() {
        return G;
    }

    public void setG(int newG) {
        G = newG;
    }

    /**
     * Also resets the node for the next path search.
     * @param newHeuristic the new heuristic value. To be set by {@link AStar}.
     */
    public void setHeuristic(int newHeuristic) {
        heuristic = newHeuristic;
        G = moveCost;
        parent = null;
    }

    public void setParent(Node n) {
        parent = n;
    }

    public Node getParent() {
        return parent;
    }

    public int getMoveCost () {
        return moveCost;
    }

    public Node addParents(Path path) {
        if(parent != null)
            path.add(parent.addParents(path));
        return this;
    }

    public boolean isImpassable () {
        return moveCost <= 0 || impassable;
    }

    public void setImpassable (boolean b) {
        impassable = b;
    }
}

```

My game has different movement costs depending the tile, but if yours doesn't just make `moveCost` a constant (and alter it for diagonals, if you're using those).
> 1 votes

---
Tags: c#, algorithm, tiles, path-finding, tilemap
---


# Question
Title: How to change trail renderer start width dynamically by script in Unity?
I created a prefab that contains a trail renderer to draw a sprite in the GUI which I in a GameObject in a script.

I want to change the start width or end width of the trail renderer dynamically during run time. Could anyone help me how write code to access to the trail renderer prefab to change that property?

# Answer
I have no experience with Unity, so I will make a few assumptions:

1. You tried to make a TrailRenderer, but don't know "how to change trail renderer start width dynamically by script in unity?".
2. So far, you have a TrailRenderer, but don't know "how to change trail renderer start width dynamically by script in unity?".
3. The TrailRenderer that you have so far is working, but you don't know "how to change trail renderer start width dynamically by script in unity?".

I had to Google "Trail Renderer Unity" to see if that was a Unity thing or a class you'd created. Here are the first two links that Google returns:

Link to the manual page: manual reference
Link to the scripting page: script reference

`endWidth` and `startWidth` are listed right after the first entry on the script reference page and should allow you to achieve what you want.
> 0 votes

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


# Question
Title: 6DOF camera: inverted yaw and roll when orientation changes
Whenever I change the orientation of the camera, yaw and roll become inverted (or correct); the strafing, movement and pitch do remain correct however.

Can you tell what is causing this and how to fix it ?

```
private Vector3 _cameraOrientation;
private Vector3 _cameraPosition;
private Matrix _matrixProjection;
private Matrix _matrixView;

protected override void Update(GameTime gameTime)
{
    var state = GamePad.GetState(PlayerIndex.One);
    if (state.Buttons.Back == ButtonState.Pressed ||
        Keyboard.GetState().IsKeyDown(Keys.Escape))
        Exit();
    if (state.Buttons.Start == ButtonState.Pressed) _cameraPosition = _cameraOrientation = Vector3.Zero;

    var right = state.ThumbSticks.Right;
    var left = state.ThumbSticks.Left;

    // get position/orientation deltas from gamepad
    var position = new Vector3
    {
        X = left.X,
        Y = state.Buttons.A == ButtonState.Pressed ? -1 : state.Buttons.Y == ButtonState.Pressed ? 1 : 0,
        Z = -left.Y,
    };
    var orientation = new Vector3
    {
        X = -right.Y,
        Y = -right.X,
        Z = state.Buttons.X == ButtonState.Pressed ? -1 : state.Buttons.B == ButtonState.Pressed ? 1 : 0
    };

    // update position according orientation
    _cameraOrientation += orientation;
    var cameraReference = Vector3.Forward;
    var cameraRotation =
        Matrix.CreateRotationX(MathHelper.WrapAngle(MathHelper.ToRadians(_cameraOrientation.X))) *
        Matrix.CreateRotationY(MathHelper.WrapAngle(MathHelper.ToRadians(_cameraOrientation.Y))) *
        Matrix.CreateRotationZ(MathHelper.WrapAngle(MathHelper.ToRadians(_cameraOrientation.Z)));
    _cameraPosition += Vector3.Transform(position, cameraRotation);

    // update matrices
    var cameraPosition = _cameraPosition;
    var cameraTransformedReference = Vector3.Transform(cameraReference, cameraRotation);
    var cameraTarget = cameraPosition + cameraTransformedReference;
    var cameraUpVector = Vector3.Transform(Vector3.Up, cameraRotation); // Vector3.Up;
    _matrixView = Matrix.CreateLookAt(cameraPosition, cameraTarget, cameraUpVector);
    _matrixProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45),
        _graphics.GraphicsDevice.Viewport.AspectRatio, 0.01f, 100000f);

    base.Update(gameTime);
}

```

# Answer
This answer works properly : beginner: camera quaternion rotation (space sim)
> 1 votes

---
Tags: c#, camera, monogame
---


# Question
Title: What can I do in Unity3D to optimize the way I'm calculating contrast of a texture2D?
I have this contrast script right now in Unity:

```
public void ApplyContrast(string contrast)
    {
        try
        {
            double contrastD = Convert.ToDouble(contrast);

            //Make an empty Texture the same same as the original
            bitmapImage = new Texture2D(imgTexture.width, imgTexture.height);

            if (contrastD < -100) contrastD = -100;
            if (contrastD > 100) contrastD = 100;
            contrastD = (100.0 + contrastD) / 100.0;
            contrastD *= contrastD;
            Color color;

            //Access each pixel in the image (with three values per pixel (R,G,B)
            for (int i = 0; i < bitmapImage.width; i++)
            {
                for (int j = 0; j < bitmapImage.height; j++)
                {
                    //get the pixel from the original image
                    color = (imgTexture as Texture2D).GetPixel(i, j);

                    //Alpha value
                    double pA = color.a;

                    //Red
                    double pR = color.r;
                    pR -= 0.5; //subtract 0.5
                    pR *= contrastD;
                    pR += 0.5;
                    if (pR < 0) pR = 0;
                    if (pR > 255) pR = 255;

                    //Green
                    double pG = color.g;
                    pG -= 0.5;
                    pG *= contrastD;
                    pG += 0.5;
                    if (pG < 0) pG = 0;
                    if (pG > 255) pG = 255;

                    //Blue
                    double pB = color.b;
                    pB -= 0.5;
                    pB *= contrastD;
                    pB += 0.5;
                    if (pB < 0) pB = 0;
                    if (pB > 255) pB = 255;

                    //Set the new image's pixel to the contrast version from the new color object
                    bitmapImage.SetPixel(i, j, new Color((float)pR, (float)pG, (float)pB, (float)pA));
                }
            }

            //Apply all SetPixel changes
            bitmapImage.Apply();

            //Connect texture to material of GameObject this script is attached to
            Image.renderer.material.mainTexture = bitmapImage as Texture;
        }
        catch (Exception ex)
        {
            Log.Item(ex);
        }
    }

```

and my brightness is:

```
public void AdjustBrightness(string brightness)
    {
        int brightnessInt = Convert.ToInt32(brightness);
        int mappedBrightness = (51 * brightnessInt) / 10 - 255;
        //Make an empty Texture the same same as the original
        bitmapImage = new Texture2D(imgTexture.width, imgTexture.height);

        if (mappedBrightness < -255) mappedBrightness = -255;
        if (mappedBrightness > 255) mappedBrightness = 255;
        Color32 color;
        for (int i = 0; i < bitmapImage.width; i++)
        {
            for (int j = 0; j < bitmapImage.height; j++)
            {
                color = (imgTexture as Texture2D).GetPixel(i, j);
                int cR = (int)color.r + mappedBrightness;
                int cG = (int)color.g + mappedBrightness;
                int cB = (int)color.b + mappedBrightness;

                if (cR < 0) cR = 0;
                if (cR > 255) cR = 255;

                if (cG < 0) cG = 0;
                if (cG > 255) cG = 255;

                if (cB < 0) cB = 0;
                if (cB > 255) cB = 255;

                bitmapImage.SetPixel(i, j,
    new Color(cR/255f, cG/255f, cB/255f));
            }
        }
        //Apply all SetPixel changes
        bitmapImage.Apply();

        //Connect texture to material of GameObject this script is attached to
        Image.renderer.material.mainTexture = bitmapImage as Texture;
    }

```

However this is slow and the brightness/contrast doesn't look right.

Can I use Image Effects in Unity Pro or something else to manipulate brightness/contrast for my uploaded Texture2D image?

I have a slider with values from 0% to 100% and I am adjusting the brightness/contrast using the above scripts and double checking the input ranges match the algorithm above.

# Answer
> 1 votes
The biggest optimization you can do is to calculate this on the graphics card -- one way to do that is to use Graphics.Blit and a shader to do the brightness/contrast effect. The result has to be a RenderTexture, but if you need the result in a Texture2D, you can use Texture2D.ReadPixels to copy the data from a RenderTexture to a Texture2D, in about 3 lines of code, apparently:

`RenderTexture.active = myRenderTexture;
 myTexture2D.ReadPixels(new Rect(0, 0, myRenderTexture.width, myRenderTexture.height), 0, 0);
 myTexture2D.Apply();`

As long as you're using Unity 5, you can do this without the Pro version.

---
Tags: unity, c#, image-processing, image-effects
---


title: How to make TMXTiledMap responsive?

text:
# Question
Title: How to make TMXTiledMap responsive?
I've been struggling with Cocos2d-x (C++) and finally I got to the point I feel more or less comfortable with that.

My game is a 2D car-based one, with a straight infinite map where I've finally been able to add some random obstacles. There are only 3 positions the car can be at, and everything is working fine.

The point is that I've recently noticed that it is not responsive, and tried to make it **responsive** by adding a line like these one to the *AppDelegate.cpp*:

```
glview->setDesignResolutionSize(1024.0, 600.0, kResolutionFixedWidth);

```

I've tried to use *kResolutionFixedWidth*, *kResolutionFixedHeight* and all others 5 variables you can put there, but I only got black lines along the screen and every single screen breakdown you can imagine -.-'

I can figure out I need to resize my TMXTiledMap manually because of the nature of tiles (I did it with Tiled), but I don't know how to face this problem.

Note that I'm currently developing for a 1024x600 Android device but I would want to support at least the most common resolutions for both tablets and smartphones.

Thanks in advance to anyone who can help me in some way.

# Answer
> 1 votes
This is my method for supporting multiple resolutions:

### My AppMacro.h

```
#ifndef __APPMACROS_H__
#define __APPMACROS_H__

#include "cocos2d.h"

#define DESIGN_RESOLUTION_480X320    0
#define DESIGN_RESOLUTION_480X320    1
#define DESIGN_RESOLUTION_1024X768   2
#define DESIGN_RESOLUTION_1280X800   3
#define DESIGN_RESOLUTION_2048X1536  4

/* If you want to switch design resolution, change next line */
#define TARGET_DESIGN_RESOLUTION_SIZE  DESIGN_RESOLUTION_1280X800

typedef struct tagResource
{
    cocos2d::CCSize size;
    char directory[100];
}Resource;

static Resource smallResource  =  { cocos2d::CCSizeMake(480, 320),   "iphone" };
static Resource mysmallResource  =  { cocos2d::CCSizeMake(800, 480),   "iphone" };
static Resource mediumResource =  { cocos2d::CCSizeMake(1024, 768),  "ipad"   };
static Resource myResource =  { cocos2d::CCSizeMake(1280, 800),  "ipad" };
static Resource largeResource  =  { cocos2d::CCSizeMake(2048, 1536), "ipadhd" };

#if (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_480X320)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(480, 320);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_480X320)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(800, 480);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_1024X768)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(1024, 768);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_2048X1536)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(2048, 1536);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_1280X800)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(1280, 800);
#else
#error unknown target design resolution!
#endif

// The font size 24 is designed for small resolution, so we should change it to fit for current design resolution
#define TITLE_FONT_SIZE  (cocos2d::CCEGLView::sharedOpenGLView()->getDesignResolutionSize().width / myResource.size.width * 24)

#endif /* __APPMACROS_H__ */

```

### And my AppDelegate.cpp:

```
#include "AppDelegate.h"

#include "AppMacros.h"
#include "SimpleAudioEngine.h"
#include "cocos2d.h"

#include "GameLayer.h"
USING_NS_CC;

AppDelegate::AppDelegate() {

}

AppDelegate::~AppDelegate() {

}

bool AppDelegate::applicationDidFinishLaunching() {
    CCLOG("%s","applicationDidFinishLaunching ");
    // initialize director
    CCDirector* pDirector = CCDirector::sharedDirector();
    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();

    pDirector->setOpenGLView(pEGLView);

    // Set the design resolution
    pEGLView->setDesignResolutionSize(designResolutionSize.width,
            designResolutionSize.height, kResolutionFixedWidth);

    //CCSize frameSize = pEGLView->getFrameSize();
    CCSize frameSize = pDirector->getVisibleSize();

    // if the frame's height is larger than the height of medium resource size, select large resource.
    if (frameSize.width > myResource.size.width) {

        pDirector->setContentScaleFactor(
                largeResource.size.width / designResolutionSize.width);

    }
    // if the frame's height is larger than the height of small resource size, select medium resource.
    else if (frameSize.width > mediumResource.size.width) {

        pDirector->setContentScaleFactor(
                myResource.size.width / designResolutionSize.width);

    } else if (frameSize.width > mysmallResource.size.width) {

        pDirector->setContentScaleFactor(
                designResolutionSize.width / mediumResource.size.width);

    } else if (frameSize.width > smallResource.size.width) {

        pDirector->setContentScaleFactor(
                designResolutionSize.width / mediumResource.size.width);

    }
    // if the frame's height is smaller than the height of medium resource size, select small resource.
    else {

        pDirector->setContentScaleFactor(
                designResolutionSize.width / smallResource.size.width);

    }

    // turn on display FPS
    pDirector->setDisplayStats(false);

    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);

    // create a scene. it's an autorelease object
    CCScene *pScene = GameLayer::scene();

    // run
    pDirector->runWithScene(pScene);

    return true;
}

// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
    CCDirector::sharedDirector()->stopAnimation();

    // if you use SimpleAudioEngine, it must be pause
    CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();

}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
    CCDirector::sharedDirector()->startAnimation();

    // if you use SimpleAudioEngine, it must resume here
    CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();

}

```

---
Tags: opengl, android, tilemap, cocos2d-x, resolution
---


# Question
Title: My runtime mesh is not being created where it's vertices are located, need help
I'm trying to create a quad at runtime and I'm encountering an issue where the mesh does not show up in the scene where it's vertices where set. In the following picture you can see the ship, and to the far right the mesh.

The 4 white dots around the ship where drawn after the mesh was made using the 4 vertices of the mesh.

My Code:

```
//Handles the method calls for the mesh creation
private void BoundingMeshCreation()
{
    Quaternion currentRotation = ResetPosition(new Quaternion(0, 0, 0, 0));
    BoundingPointsType boundingPoints = DetermineBounds();
    Mesh boundingMesh = CreateBoundingMesh(boundingPoints);
    AssignMesh(boundingMesh);
    ResetPosition(currentRotation);
}

//Creates the mesh filter and assigns the mesh
private void AssignMesh(Mesh boundingMesh)
{
    MeshFilter newMeshFilter = gameObject.AddComponent<MeshFilter>();
    newMeshFilter.mesh = boundingMesh;

    VectorLine testPoint = new VectorPoints("testPoint", boundingMesh.vertices, null, 5);
    testPoint.Draw3D();
}

//Creates a bounding mesh for the unit
private Mesh CreateBoundingMesh(BoundingPointsType boundingPoints)
{

    Mesh boundingMesh = new Mesh();
    boundingMesh.name = "Bounding Quad";

    Vector3[] vertices = new Vector3[4]
    {
        boundingPoints.LowerLeftPoint,
        boundingPoints.LowerRightPoint,
        boundingPoints.UpperRightPoint,
        boundingPoints.UpperLeftPoint
    };

    int[] triangles = new int[6]
    {
        0,
        2,
        1,

        0,
        3,
        2
    };

    boundingMesh.vertices = vertices;
    boundingMesh.triangles = triangles;

    return boundingMesh;
}

//Resets the units rotation to the specific quaternion and returns the quaterion from before the reset. Bit of a hack for now to make sure that the original box is the proper size.
private Quaternion ResetPosition(Quaternion toResetTo)
{
    Quaternion currentRotation = transformV.rotation;
    transformV.rotation = toResetTo;
    return currentRotation;
}

//Determines and returns the bounding box points
private BoundingPointsType DetermineBounds()
{
    Vector3 maxBounds = childSprite.GetComponent<Renderer>().bounds.max;
    Vector3 minBounds = childSprite.GetComponent<Renderer>().bounds.min;

    BoundingPointsType boundingPoints = new BoundingPointsType(new Vector3(maxBounds.x, 1, maxBounds.z),
                                                               new Vector3(minBounds.x, 1, maxBounds.z),
                                                               new Vector3(maxBounds.x, 1, minBounds.z),
                                                               new Vector3(minBounds.x, 1, minBounds.z));
    return boundingPoints;
}

```

I've even tried manually setting the vertices like the following:

```
    Vector3 UpRight = transformV.position;
    Vector3 UpLeft = transformV.position;
    Vector3 LowRight = transformV.position;
    Vector3 LowLeft = transformV.position;

    UpRight.z += 1;
    UpRight.x += 1;

    UpLeft.z += 1;
    UpLeft.x -= 1;

    LowRight.z -= 1;
    LowRight.x += 1;

    LowLeft.z -= 1;
    LowLeft.x -= 1;

    Vector3[] vertices = new Vector3[4]
    {
        LowLeft,
        LowRight,
        UpRight,
        UpLeft
        //boundingPoints.LowerLeftPoint,
        //boundingPoints.LowerRightPoint,
        //boundingPoints.UpperRightPoint,
        //boundingPoints.UpperLeftPoint
    };

```

I'm at a loss, and have no idea what I'm doing wrong. My dynamic meshes seem to work perfectly fine for everything else in the game.

Thanks.

# Answer
> 1 votes
The vertices of a mesh are always in **local space**. In your DetermineBounds function you are returning *world space* coordinates, and the solution to this is to just use InverseTransformPoint. Somewhat like this:

```
Vector3 maxBounds = transform.InverseTransformPoint(childSprite.GetComponent<Renderer>().bounds.max);

```

Do the same for minBounds too. The rest of your code should remain the same. The quad should now be properly overlaying your sprite, unless the position of the quad and the sprite is different.

---
Tags: unity, mesh
---


# Question
Title: How do I make the ui button to move my character?
How do I make my character move left,right and jump when click ui buttons using this code?

```
using UnityEngine;
using System.Collections;

public class Player: MonoBehaviour {

public float maxspeed = 10f;
bool facingRight = true;

Animator anim;

bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public Vector2 jumpDirection = new Vector2(1f, 1f);
public Vector3 groundCheckOffset = new Vector3(0f, -1f, 0f);
public float jumpFocre = 500f;
bool doubleJump = false;

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

void FixedUpdate () {
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    grounded = Physics2D.OverlapCircle(transform.position + groundCheckOffset, groundRadius, whatIsGround);
    anim.SetBool ("Ground", grounded);

    if (grounded)
        doubleJump = false;

    float move = Input.GetAxis ("Horizontal");

    anim.SetFloat ("Speed", Mathf.Abs (move));

    GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
}
void Update()
{

    if((!doubleJump) && Input.GetKeyDown ("up"))
    {
        anim.SetBool("Ground", false);

        float move = Input.GetAxis ("Horizontal");

        jumpDirection.x = move;
        GetComponent<Rigidbody2D>().AddForce(jumpDirection.normalized * jumpFocre);

        if(!doubleJump && !grounded)
            doubleJump = true;
    }

}

    void Flip()
{
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}
}

```

# Answer
> 1 votes
Make the `float move` variable a class variable. Then create 2 methods which the left and right UI buttons will call on Pointer Down, e.g. `MoveLeft()` and `MoveRight()`. Inside them, set `move = -1` for left and `move = 1` for right.

If you want the character to stop if the buttons aren't pressed, you can also make a `StopMoving()` method on Pointer Up for both buttons that sets `move = 0`.

---
Tags: c#, unity, scripting, unityscript
---


# Question
Title: Trying to make a box move around the screen with the arrow keys
I have a box and it moves around the screen when the user presses the arrow keys. It seems a bit bulky and awkward though. Any thoughts on how to make it more efficient/less resource intensive?

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;

public class Box {

private float boxWidth, boxHeight;
private int gameWidth, gameHeight;
private Color boxColor;

private Vector2 position;
private Vector2 velocity;
private Vector2 acceleration;

private boolean goRight, goLeft, goUp, goDown, stopRight, stopLeft, stopUp, stopDown;

public Box(int boxWidth, int boxHeight, Color boxColor, int gameWidth, int gameHeight) {
    this.boxWidth = boxWidth;
    this.boxHeight = boxHeight;
    this.boxColor = boxColor;

    this.gameWidth = gameWidth;
    this.gameHeight = gameHeight;

    position = new Vector2(gameWidth/2 - boxWidth/2, gameHeight/2 - boxHeight/2);
    velocity = new Vector2(0, 0);
    acceleration = new Vector2(0, 0);
}

public void update(float delta) {

    velocity.add(acceleration.cpy().scl(delta));

    if(velocity.x >= 100) {
        velocity.x = 100;
    }

    if(velocity.x <= -100) {
        velocity.x = -100;
    }

    if(velocity.y <= -100) {
        velocity.y = -100;
    }

    if(velocity.y >= 100) {
        velocity.y = 100;
    }

    if(stopRight) {
        if(velocity.x > 0) {
            velocity.x -= velocity.x/20;
            if(velocity.x <= 0) {
                velocity.x = 0;
                stopRight = false;
            }
            if(goLeft) {
                acceleration.x = -100;
            }
        }
        else {};
    }

    if(stopLeft) {
        if(velocity.x < 0) {
            velocity.x -= velocity.x/20;
            if(velocity.x >= 0) {
                velocity.x = 0;
                stopLeft = false;
            }
            if(goRight) {
                acceleration.x = 100;
            }
        }
    }

    if(stopUp) {
        if(velocity.y < 0) {
            velocity.y -= velocity.y/20;
            if(velocity.y >= 0) {
                velocity.y = 0;
            }
            if(goDown) {
                acceleration.y = 100;
            }
        }
    }

    if(stopDown) {
        if(velocity.y > 0) {
            velocity.y -= velocity.y/20;
            if(velocity.y <= 0) {
                velocity.y = 0;
            }
            if(goUp) {
                acceleration.y = -100;
            }
        }
    }

    if(position.x >= gameWidth - boxWidth) {
        position.x = gameWidth - boxWidth;
    }

    if(position.x <= 0) {
        position.x = 0;
    }

    if(position.y >= gameHeight - boxHeight) {
        position.y = gameHeight - boxHeight;
    }

    if(position.y <= 0) {
        position.y = 0;
    }

    position.add(velocity.cpy().scl(delta));

}

public Box getBox() {
    return this;
}

public Color getBoxColor() {
    return boxColor;
}

public void goRight() {
    goRight = true;
    acceleration.x = 100;
    stopRight = false;
}

public void goLeft() {
    goLeft = true;
    acceleration.x = -100;
    stopLeft = false;
}
public void goUp() {
    goUp = true;
    acceleration.y = -200;
    stopUp = false;
}
public void goDown() {
    goDown = true;
    acceleration.y = 200;
    stopDown = false;
}

public float xPos() {
    return position.x;
}

public float yPos() {
    return position.y;
}

public void stopRight() {
    acceleration.x = 0;
    stopRight = true;
    goRight = false;
}

public void stopLeft() {
    acceleration.x = 0;
    stopLeft = true;
    goLeft = false;
}

public void stopUp() {
    acceleration.y = 0;
    stopUp = true;
    goUp = false;
}

public void stopDown() {
    acceleration.y = 0;
    stopDown = true;
    goDown = false;
}

}

```

Any ideas on how to do this with fewer lines of code? Thanks!

# Answer
> 0 votes
Well.. goRight, goLeft, goUp and goDown could be one single function called move. This function would receive a direction(between -1 and +1 to both axis) and add acceleration to velocity according to the direction received. In lieu of the stops, you could make one single function called deceleration which would test the box direction and decrease it by a constant if not zero. This function would be called every X time period. If the deceleration constant is smaller than the acceleration constant in move, it'll work. So you can do it in 2 functions.

---
Tags: efficiency
---


title: No RenderWindow class in SFML?

text:
# Question
Title: No RenderWindow class in SFML?
In their official tutorials it is said that to draw graphics on screen, i have to use RenderWindow instead of Window. But when i write sf:: RenderWindow window, error pops up saying that there is no RenderWindow in sf:: . I copy-pasted the code but it still does not works. What could possibly be the reason behind this ?

# Answer
sf::Window is part of the SFML Window module but sf::RenderWindow is part of the SFML Graphics module. Hence you have to include SFML/Graphics.hpp in order to use it.
> 1 votes

---
Tags: sfml
---


title: How to set up bloom in Unity

text:
# Question
Title: How to set up bloom in Unity
Last time I used image effects in Unity it was back when 3.0 was released and for *bloom* you used the object's alpha to indicate whether it should glow or not. Now in 4.2 I couldn't grasp how to apply the image effect properly. It seemed to put the whole scene to glow and alpha did not affect it.

There was no help from the Unity docs which are pretty much just spec sheets for the effects and no proper tutorials around. This leads to couple of questions:

1. How do you create something like the screenshots in the Bloom page in the docs? Only the car windows and metal parts glow, but no glow on the concrete.
2. How do you make a light source like the second image on the above link? I tried different shaders and lights on a gameobject but none of them produced anything like that.
3. What does the `HDR` checkbox in the camera actually do?

# Answer
> 3 votes
# 0.) Setup

Since the Release of Unity 5, Bloom (and quite a few other Image effects eg `Ambient Occlusion`, `Blur`, `Color Correction` etc) have also become available to Personal (Non-Pro/Non-Paid) Users.

To start you need to import the `Effects` Package into your project: `Assets -> Import Package -> Effects`

Once you've imported this package you will see the "Standard Assets" folder in your Project Tab, within it will be a sub-folder "Image Effects" where you will find C# scripts named appropriately after their effects. Simply drag and drop the `Bloom.cs` script (or any other image effects you want) onto the camera you want to apply them to.

If for some reason you don't have the Standard Assets Package installed in your platform you will need to either include that manually or first upgrade your project to become Unity 5 Compatible.

# 1. & 2.) Specular Mapping

Specular Shader Documentation

This image you are referencing is utilizing Diffuse and Specular materials as well as Specular mapped shaders. These allow you to define the areas of a model / mesh that will reflect or absorb light. In its simplest form you chose whats shiny and whats not. In combination with the Bloom Effect, correct Lighting / Intensity and HDR (High Dynamic Range Rendering) camera attribute seen in that image, you could achieve a similar appearance.

To achieve the effect you want, you probably aren't even looking for the Bloom effect at all. You just need:

1. Specular & Diffuse Materials -to accurately apply a Specular Map your materials to define some as "Shiny" and others as "Flat" / "Diffuse". Concrete is a non reflective Diffuse material, while the glass a fully reflective Specular.
2. Higher Intensity Light - Do this in conjunction with a more powerful light source, a Directional light often is suitable when trying to emulate the sun for outdoor modeling.
3. Reflection Probes (optional) - These may not be necessary but when I am dealing with Specular / Metallic materials and the Standard Shader these can go a long way!

# 3.) High Dynamic Range

In photography HDR is a technique used to attempt to composite multiple images in order to increase the range of "Light" or "Luminosity" that can be seen. This is an artistic technique to make images more vivid or dramatic then we perceive those scenes in real life. As humans (I am assuming we're all human here) our eyes attempt to adjust to the lighting conditions surrounding us, restricting or increasing the level of light intake. So in effect our eyes adjust the range of light we perceive based on the overall lighting conditions.

*How it works:* When we read HDR, we are assuming a process of taking multiple "photos" or "passes" at a single shot/frame with multiple light settings (at minimum three: low, medium, high; sometimes many more) and composting the data together into something more. See below for a normal shot and a HDR composite:

---
Tags: unity, bloom, hdr, image-effects
---


# Question
Title: Draw many flashlights' focused lights' "circles" on a voxel engine map (and other objects)
So, I've been searching the internet for a while and I still didn't understand how to create a flashlight's "circle" in front of the camera over other objects.

I found the following links:

using shader;

multi pass effect;

forum question about multiple passes and multiple effects;

shader example with multiple lights (which I can't open because its an old project).

And they give me examples and solutions about how to draw lights or other effects on objects.

But it's not clear to me yet. I'm newbie with HLSL (and still a little with XNA itself) and I don't get what should I do. I need help with the steps I should take to modify my HLSL effect\* of the voxel engine to draw a white circle where the cursor points and shine the light around the camera position as the flashlight is on.

\*I created a voxel engine that uses a effect (modified a little) I found in a project called TechCraft. It changes the light on the map depending of the time of the day and the sun position. But I'm not sure how it works neither, I just read a little but I'm not used to HLSL as I said. (Where could I find good HLSL tutorials?)

Do I need to make many passes and make a pixel shader and a vertex shader for each one? Or should I create many techniques? What's the difference?

Or is that a bad idea? Should I create another effect and draw again the voxel with its technique and pass?

And maybe it's not only one light. If I'm able to create a multiplayer someday, or NPCs, the game will have more than one light on at the same time. How to draw more than one circle?

I'm really lost with this, and I have no idea where should I start from. I appreciate any help; even showing already answered questions is helpful to me.

# Answer
> Where could I find good HLSL tutorials?

Reimer's

Two ways off the top of my head:

**Light volume**
After rendering, switch to a flashlight shader and draw a cone (some triangles), with the tip located at the camera's position and the circular base pointing in the camera's forward direction, with arbitrary dimensions. You literally render a cone containing the volume you want lit and apply the flashlight "effect" to the affected pixels.

**3D "Stencil"**
Obtain a circular stencil texture from Paint (transparent, with centered white circle, blurred). During the flashlight pass, render a billboarded quad with the stencil texture applied. The quad can be resized to modify the beam. Output transparent anywhere the stencil is transparent. The values you put into the stencil and the resulting output do not have to be directly related. As a built-in bonus, UV (0.5, 0.5) corresponds to the center of the quad, so you can use the 2D distance from the center to diminish the alpha near the edges, if desired. If you don't need anything other than circular, you can probably just use that distance instead of a texture.

**Diagram:**
Both produce similar effects. The cone geometry is outlined in gray. Notice the stencil creates the same cones that geometry can; it's up to you. Stenciling gives you unlimited flexibility in describing the "lens" of the flashlight. With a little modification, inverting the stencil I've shown would produce a beam of "unlight" in an otherwise well-lit world.

**Multiple lights:**
Both methods use rendered geometry, so the draw calls for them can be optimized like any other geometry. If you have 58 cones to render, draw the same unit-cone over and over with 58, per-instance, world matrices, instead. You can render all cones with one call to DrawIndexedInstanced(...).

For many lights, it will be preferable to use "deferred rendering/lighting". Instead of rendering the scene directly to the backbuffer, you render a *description* of the scene to one or more rendertargets, a lightmap to another 1+ rendertarget(s), and then combine them at the end by drawing a fullscreen quad (2D) and sampling the textures to re-construct, and simultaneously light, the entire scene at once.

The best link I have
> 2 votes

# Answer
So, after @Jon helped me understand HLSL and render targets, I could understand more tutorials on the internet and I found my answers in the following links, if anyone is interested:

First I read some of the Riemer's tutorials of HLSL to understand its basics.

Second I read RB Whitaker's HLSL/Effect tutorials to get some more information.

Third I read the example project of XBox Create of multipass lighting so I understood how to draw many lights with additive render state. I had to change some semantics and update some old code, as it's written with XNA 2.0.

Then finally I read Advanced Lighting in 3D Graphics with XNA Game - spotlights and point lights with HLSL so I could get the math codes for applying light in the right vertices and pixels.

With all those links and the example diagram given by Jon, I could program my own HLSL effect with multipass.

The code I had to update from XNA 2.0 I searched in XNA blogs on the internet.

Thanks for all the help!
> 0 votes

---
Tags: xna, c#, hlsl, graphic-effects
---