# Question
Title: Random Between: using random with the instance_create function in GML
Hopefully this should be a simple one; I want to restrict the points that instances enter the screen from so they don't come in at the edges.

In Game Maker I'm using the following code `instance_create(random(room_width), random(-100) - 50, obj_enemy1);` to create the instance off screen (create(x, y, ...))

At the moment I'm just using the room\_width to define the max width for the random on x, but ideally I want to find a way of defining a max AND min width for the random. I can't figure out how to restrict the range on the x axis to *between* say 100 and 350.

Any help would be appreciated.

Cheers

# Answer
after some poking around I've found a working solution, if anyone can suggest an easier way I'd greatly appreciate it.

```
//adds extra planes to the room

//create a collection of temp variables to difine the range as a min and max
//create a random number variable based on the room size
//find the location of the random value and if it falls outside of the min or max
   //move move it to the min or max
//create an enemy plane within the restricted x axis of the room and between 50 and
   //100 pixels above the screen

var minrand, maxrand, randnumber, realrand;
minrand = 50;
maxrand = room_width - 50;
randnumber = random(room_width);
realrand = 0;

if randnumber < minrand
{
realrand = minrand
}
   else
   if randnumber > maxrand
   {
   realrand = maxrand
   }
    else
    {
    realrand = randnumber
    };

 instance_create(realrand, random(-100) - 50, obj_enemy1);

```

Thanks
> 1 votes

# Answer
You can use the median function:

```
point = median(smallestValue, randomValue, largestValue)

```
> 1 votes

# Answer
Try this:

instance\_create(random\_range(50,room\_width - 49), random(-100) - 50, obj\_enemy1);

It does everything your script does, and it is more evenly balanced.
> 0 votes

# Answer
I think you may have overcomplicated a few things in your code.

So assuming you want enemies to come in, say, from the top of the screen downwards, then you can achieve spawning a single enemy with one line of code:

`instnace_create(view_xview[0]-enemy.sprite.width+irandom(view_wview[0]),view_yview[0]-enemy.sprite.height,obj_enemy);`

(This code assumes that you have views enabled and are using view 0, and that the origin point for the object's sprite is set at (0,0))

(Replace enemy.sprite.height and enemy.sprite.width with whatever the height and width of the enemy's sprite is. If the sprite\_index is the exact same sprite for what's being shown on screen then I'd advise using `sprite_get_width(obj_enemy.sprite_index)`)
> 0 votes

---
Tags: random, game-maker
---


# Question
Title: Heightmap using Simplex noise with octaves: help with parameters and interpretation
I've found a few pieces of code around, where Java code for Simplex noise (based on this widely quoted paper) was coupled with octaves to get a heightmap. However those classes/snippets are NOT in the -1,1 range despite saying so, so I had to add some modifications.

By trial and error and some brain work I got to a version that produces an output within -1 and 1, here **(could you sanity check it please? It this correct?)**:

```
public static float[][] generateOctavedSimplexNoise(final int width,
                                                    final int height,
                                                    final int octaves,
                                                    final float roughness,
                                                    final float scale)
{
    final float[][] totalNoise = new float[width][height];
    float layerFrequency = scale;
    float layerWeight = 1f;
    float weightSum = 0f;

    for (int octave = 0; octave < octaves; octave++)
    {
        // Calculate single layer/octave of simplex noise, then add it to total noise
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                totalNoise[x][y] += (float) noise(x * layerFrequency, y * layerFrequency) * layerWeight;
            }
        }

        // Increase variables with each incrementing octave
        layerFrequency *= 2f;
        weightSum += layerWeight;
        layerWeight *= roughness;
    }

    // scale output between -1 and 1, as we are doing
    // a weighted average
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            totalNoise[x][y] /= weightSum;
        }
    }

    return totalNoise;
}

```

My understanding is that **"roughness" must vary between 0 and 1**, and influences the "flatness" of the final image. **What "scale" is I cannot fathom yet - any help?**. Also, more than 6-7 octaves seems useless in my tests, hopefully this is expected.

But most of all my question is: **how do I work in a top-down way?** That is, knowing the kind of map I roughly want (a big island in the ocean, with a few lakes and a few mountains, but mostly plain and hills) how do I choose parameters and the thresholds for terrain types?

I've tried a lot, but I can't seem to control the function to produce a nice map..

# Answer
> 0 votes
A long search brought me to this tutorial and respective code of the C++ library libnoise. With pictures, formulas and code it's a bit clearer (although much work and study still has to go into this, for me to understand how to create a map with specific characteristics.. but that's beyond "noise", I fear).

This does use Perlin noise instead of Simplex noise, so I'm not sure I'll be able to reproduce all I'm reading.. but well, hopefully this is useful to someone else.

---
Tags: java, heightmap, simplex-noise
---


# Question
Title: How to implement 'Fog of War' in SpriteKit or Cocos2D?
Take a look at the image below from the game Warcraft 2. There's a darkened area (like a fog) that represents the limits of the 'field of view' -- to the effect that you would not see any enemy characters in the fog.

**How would you implement this 'fog' in iOS (SpriteKit, Cocos2d, etc)?** Mostly interested in hearing high-level strategies on implementing the fog itself -- within the node-based hierarchy of something like SpriteKit or Cocos2d.

***And bonus:*** *what do people call this 'fog' in the game industry?*

**\[Update\]** *'Fog of War' (thanks @Jon)*

# Answer
One option is to overlay a texture that has a blend mode of Multiply set to it over your tiles. The overlay texture would be almost black (dark shades of grey) all around, except for the area you want to be fully visible, which would be white.

Multiply blend mode will darken all the black areas and the white areas would remain unaffected.

Here is a sample of what you would see if you have a texture that is white in the center and has a circular gradient fill that eventually becomes dark gray. This texture (in SpriteKit) is added to a SKSpriteNode on top of everything else; it's z-position is the highest in the scene.

Here's an online demo you can check out, where this concept is taken even further for more effects.

To get a result as highlighted in your question - assuming the viewable area is dynamic, you would need to generate such a texture on the fly - fill it with white tiles for areas you want to be visible, and dark tiles for areas you want to shade out. You can generate textures on the fly using SpriteKit's SKView's `textureFromNode` method, for example.
> 3 votes

---
Tags: 2d, ios, cocos2d-iphone, spritekit
---


# Question
Title: GameMaker: Studio - Slow down calculations
I currently have an orbital simulator, with a brilliant answer in another Game Development question **here**, and would like to know how to slow down the calculations of Game Maker, to be able to do more precise ones as my orbits suffer variably intense **Apsidal Precession**.

Examples of this can be found in games such as Kerbal Space Program and
Universe Sandbox 1/2. In KSP, you have the **Max Physics Delta Time** which allows slower gameplay, but more calculations. In Universe Sandbox you are able to change the accuracy of calculations causing orbits to go crazy and extremely precise.

**How am I able to implement such a thing into GameMaker: Studio?**

# Answer
> 2 votes
You can implement a global variable that flips between each mode.

You can reduce the amount of frames that are being rendered per second.

So for example, for a manager object you can have this code in the create event:

```
//Slow mode
if(global.gameplayMode == 0)
{
    room_speed = 30;
}
//Fast mode
else if(global.gameplayMode == 1)
{
   room_speed = 60;
}

```

And for calculations

```
some_stuff = irandom(9001);
if(global.gameplayMode == 0)
{
   moreCalculations();
}

```

**EDIT**

```
//Declare the variable
global.worldPace;

//If you'd like the game to run at half speed then set it to 0.5
global.worldPace = 0.5;

//But if you'd like the game to run at regular speed then just set this to 1
global.worldPace = 1;

```

And for all of the calculations, just multiply everything by this variable so for example

```
runningSpeed = 9.8 * global.worldPace;

```

I've never fiddled with this idea but this is where I'd start. I'd consider the amount you have to add for geometric functions. You'll have to make sure that whatever value you add, you distribute in the exact same manner when slowed down.

A good example and simple example would be as follows:

If over one frame you move a bullet 2 pixels to the left, with this slow-mo mode you'd now have to split this simple action into two, which means that the action of bullet moving would span over two frames, and in each frame the bullet would only move 1 pixel.

I'd imagine this would be harder to nail down with more complicated functions, so be careful with how you approach them.

---
Tags: physics, frame-rate, game-maker, orbit
---


# Question
Title: Java delaying commands in a method with time (Sys.getTime)
LWJGL 2.9.3 and Slick2D Hello, so Im making this game and its going quite well, but I cant figure this out: Ive got a 2d tile based map (wich is stored in a 2d array) and each tile has a coresponding class and an arrayList for it. Here is what I try to make: I want to be able to click on a stone tile (I have this part done), and then I want the stone tile to disapear after a set ammount of time (e.g. 10 seconds). The code:

```
    last = (int) (Sys.getTime() / Sys.getTimerResolution());
    globaltimed = last - (int) (Sys.getTime() / Sys.getTimerResolution());

    last = (int) (Sys.getTime() / Sys.getTimerResolution());
    globaltimes = last - (int) (Sys.getTime() / Sys.getTimerResolution());

    lastn = (int) (System.nanoTime() / 100000000);
    timesn = lastn - (int) (System.nanoTime() / 100000000);

```

^^ This is the part wich goes in the init method in my Play state class. ^^

```
    timesn = (System.nanoTime() / 100000000);
    // Global time w/ millisecond
    globaltimed = (timesn - lastn) / 10;
    // Global time in seconds
    globaltimes = (timesn - lastn);

    sec = (int) (globaltimed % 60);
    min = (int) (Math.floor(globaltimed/60));
    hour = (int) (Math.floor(min/60));

```

^^ This part goes in the update method of the Play state class. ^^ Thats all the time stuff.

```
if(Mouse.isButtonDown(1)){
        for(Stone ss : blocks){
            if(Collision.playerCBlock(new Point(mx, my), ss)){
                if(ss.selected && ss.selectable){
                    //map[Collision.contxy(new Point(ss.x / 32, ss.y / 32), ss, 0)][Collision.contxy(new Point(ss.x / 32, ss.y / 32), ss, 1)] = 3;
                    //blocks.remove(ss);
                    //ss.setSolid(false);
                    //ss.setSelectable(false);
                    ss.addMine(globaltimed, gc);
                    //dirt.add(new Dirt(ss.x,ss.y,false));
                }
            }
        }
    }

```

^^ Ignore the comments, but here I go through the stone tiles, check if the mouse is on that tile, if that tile is selectable and selected (I select it when left clicking, same for loop pretty much). I want to be able to say ss.addMine(whatever) and then in the stone class to make it wait some time (while displaying that time on the tile) and after that time has passed I want to replace the stone tile with a dirt tile. ^^

```
    if(!dead){
        //timedl = timed;
        minig = true;
        if(timed + minetime >= Play.getTimed()){
            //gc.sleep(minetime * 1000);
            setSolid(false);
            setSelectable(false);
            Play.dirt.add(new Dirt(x,y,false));
            dead = true;
        }
    }

```

^^ This is the addMine method in the stone class. I played with this for about an hour but I dont really have any time left now. setSolid and setSelectable baisicly remove its collision and make it unselectable. play.dirt.add(...) adds a dirt tile ontop of the stone tile (Replaces it; not efficiently, but it works for now). ^^ Thats all the important code, now, does anyone have a concept to delay the replacement of the tile(setSolid(false)...dead=true that part) for some time in seconds w/ or w/o milliseconds (globaltimed is w/ millis, and globaltimes is in seconds only(and int)). Thank you

# Answer
It looks like you're only checking your timing logic when the user clicks a stone.

Move the timing logic in your addMine method to a different function in your stone class, something like this:

```
public void UpdateStone()
{
    if(timed + minetime >= Play.getTimed()){
        setSolid(false);
        setSelectable(false);
        Play.dirt.add(new Dirt(x,y,false));
        dead = true;
        minig = false;
    }
}

```

Then in your update method, iterate over all your stones and call the UpdateStone method for all stones in the "minig" (mining?) state.

```
for(Stone ss : blocks)
{
     if(ss.IsMining())
     {
          ss.UpdateStone();
     }
}

```

I'm assuming that somewhere you are updating the "minetime" inside your stones. Hard to say without being able to see all the code.
> 0 votes

---
Tags: java, lwjgl, slick
---


# Question
Title: How do I quantify the curvature of a touch swipe?
I'm implementing a touch controller for my game.

I am attempting to imitate *Tiki Taka Soccer*'s "ball shooting" controls (gameplay video), where the curvature of the player's swipe affects the curve of the shot's trajectory.

Basically, I want to move the object to where the user raised their finger, but also apply a curve to the movement, corresponding to the curve of the swipe.

How can I do this?

---

I'm using Unity 5, and I'll be using the Lean Touch plugin from the asset store to capture swipes.

# Answer
## Detecting swipe curvature

Treat the finger swipe as a polyline. Approximate its curvature, and use that as a multiplier for how much to “curl” the resulting shot either left or right.

Let's say a swipe path has ***no*** *curvature* if it goes linearly from the start (the circle), to the end, or curvature value `0`.

I'll emphasise other swipes' differences to this baseline with blue and red colours.

One that makes a 90° right turn has a *maximum **right** curvature*, or curvature value `1`.

One that makes a 90° left turn has a *maximum **left** curvature*, or curvature value `-1`.

We can hence find any *intermediate* curvature by calculating the proportion of the area it covers on either side of the baseline path, as a proportion of that maximum!

When the line curves partially to either side, just add the signed areas to get the overall curvature.

Of course, you might still get particularly insane swipes that make a really far-out turn, tighter than 90°.

It's up to you how you handle these. Maybe you want to clamp them to the \[-1, 1\] range to prevent people from doing a Fire Tornado Spin Kick—but then again, maybe that would be fun!

## Applying curvature to object motion

To apply a curve to an object's forward motion, apply an impulse in its intended direction (the red arrow to the right; to create the forward motion), then an impulse perpendicular to it (the red arrow upward; to push it "outward"), then apply a constant force perpendicular to it in the other direction (the green arrow downward; to pull it "in" again). For a motion curve in the other direction, just flip the perpendicular impulse and force directions.

You can find the perpendicular of a 2D vector by exchanging its `x` and `y` components and negating one of them. Here, you probably want to normalise the perpendicular vectors and multiply them by the curvature value.

Tweak the strength of the forces and impulses to get the effect you want.
> 3 votes

---
Tags: unity, movement, touch, controllers, curves
---


# Question
Title: Example formula for current level from total EXP?
This question may already have been asked, but, nonetheless, what would an example formula be for getting the current level from the total amount of EXP a player has? As in the variable that's known is the EXP, the one I'm trying to get from the formula is the current level.

# Answer
> 0 votes
There isn't really a best way to do this, so I'll give you one way it could be done. Assuming you had experience represented as a number you would want to:

* Define an experience curve you're going to want to use. Normally subsequent levels take increasing amounts of experience to reach.
* In your game have a map data structure that maps an experience value to a given level based on your curve.
* Find the map key closest to but not over the current experience value. Display the mapped level as your current level.

Example experience curve.

```
var experience_curve = {};
experience_curve['0'] = 1;
experience_curve['100'] = 2;
experience_curve['300'] = 3;
experience_curve['700'] = 4;
experience_curve['2100'] = 5;

```

Bonus: To display progress towards the next level.

1. Find the map key closest to but not over the current experience value
2. Subtract the key found in 1. from the next map key, this is how much total xp is needed for the next level.
3. Subtract 1. from the player's current experience value, this is how much progress has been made into the next level.
4. Divide 3. by 2. and you now have the percentage of how far you are into the level.

---
Tags: mathematics
---


title: Get all points of a parabola

text:
# Question
Title: Get all points of a parabola
I'm wondering how to get all points (x,y) that constitute a given parabola. It's barely to simulate a jump of an object from point A to point B. I know: -The coordinate of point A -The coordinate of point B -The coordinate of the parabola's top

What i'm trying to do is to loop from *start\_x* to *dest\_x* to calculate the Y-coordinate at that moment, but I don't know how to do that part.

```
pixels = []
for x in start_x to dest_x
   y = (calculate the Y-coord here based on x )
   pixels.push( [x,y] )
end
return pixels

```

My math skills are not exceptional. Thank you.

# Answer
In general, there is no parabola that goes through three given points. However, if you loosen the problem constraints and only define the Y coordinate of the parabola’s top and allow its X coordinate to be free, there is usually a solution.

Given \\$A\_x\\$, \\$A\_y\\$, \\$B\_x\\$, \\$B\_y\\$ (A and B’s coordinates) and \\$C\_y\\$ (the parabola’s top), one can find a parabola formula of the form:

$$f(x) = C\_y - u (x - v)^2$$

One needs to find \\$u\\$ and \\$v\\$ in this formula. The constraints give us, after some maths:

$$ \begin{align} k &= \sqrt{\frac{C\_y - A\_y} {C\_y - B\_y}} \\ v &= \frac{k B\_x - A\_x}{k + 1} \\ u &= \frac{C\_y - A\_y} {(A.x - v)^2} \end{align} $$

For instance if \\$A = (0, 0)\\$, \\$B = (10, 5)\\$ and \\$C\_y = 15\\$:

$$ \begin{align} k &= \sqrt{\frac{15 - 0} {15 - 5}} &= 1.2247448714 \\ v &= \frac{(1.2247448714 \times 10 - 0)} {1.2247448714 + 1} &= 5.505102572 \\ u &= \frac{15 - 0}{(0 - 5.505102572)^2} &= 0.494948974 \end{align} $$ Hence the formula:

$$ f(x) = 30 - 0.494948974 \times (x - 5.505102572)^2 $$

You can see this parabola going from \\$(0,0)\\$ to \\$(10,5)\\$ with a peak at \\$Y = 15\\$, as expected:

The following code should work:

```
pixels = []
k = sqrt((top_y - start_y) / (top_y - dest_y))
v = (k * dest_x - start_x) / (k + 1)
u = (top_y - start_y) / ((start_x - v) * (start_x - v))
for x in start_x to dest_x
   y = top_y - u * (x - v) * (x - v)
   pixels.push( [x,y] )
end
return pixels

```
> 1 votes

---
Tags: mathematics
---


# Question
Title: Started work on a time based business game- one similar already exists... What should i do?
Yeah so like i said, i started to work on a time based game that involves business investments, and as it turns out, there is a game called adventure capitalist that has pretty much the same idea about it. I planned to greenlight my game on steam and i found that adventure capitalist is on steam. Im not sure what i should do. Should i continue but make changes to the game (and if so, what sort of changes) or should i give up and work on something else. I should have mentioned this earlier but in the game, you make investments in the electronic industry, and each type of investment will have a different payout per second and a different base investment price to other types. For example, investing in computers will cost you £500 and have a payout of £5/second but investing in smartphones will cost only £100 and have a payout of £1/second. When you can afford it, you can level up your investment. I havent really added any more to the game than that so any advice would be appreciated, thanks.

# Answer
> 2 votes
Game mechanics are not patentable, trademarkable, or copyrightable. Hence if your game is distinct in implementation, branding, and naming, you should be OK from a legal perspective.

From a marketing perspective though, the existing game has some first-mover advantage, unless you can differentiate. Can you deliver a game so much better than the competitor's that you can steal their whole market? If so, go for it. If not, it might be easier to look for a less occupied niche.

---
Tags: adventure-games
---


# Question
Title: Unity - Raycast not hitting to BoxCollider2D objects
I'm working on 2D and I have a Quad as background.

And some wall sprites over this quad :

I'm instantiating wall prefab sprites over quad when user click to somewhere. But I don't want to instantiate a wall over another wall, so I'm sending a ray from camera to click point and if hit object is a **wall** object I won't instantiate.

Here my code :

```
RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Physics.Raycast(ray, out hit,Mathf.Infinity);
        // If it hits ground, not another objects (like walls)
        if(hit.transform.name == "GroundQuad")
             Instantiate (wall, Input.mousePosition, Quaternion.identity)

```

But it's still creating wall objects. Tried `Debug.Log()` to print hitted object's name to console and moved pointer all over game screen, it's always GroundQuad. So ray not hitting to wall objects.

Can you tell me what is I'm missing? Is it a problem with Layer Collision Matrix ?

# Answer
> 2 votes
Just figured out the problem. I was using `Physics.Raycast` instead of `Physics2D.Raycast` . Changed my code like this:

```
RaycastHit2D hit;
        hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),Vector3.back);
        // If it hits ground, not another objects (like walls)
        if(hit.transform.name != "Wall")
             Instantiate (wall, Input.mousePosition, Quaternion.identity)

```

Now it's detecting all collisions with objects **but** not detecting collision with Quad . You can send a comment if you know why it's not detecting quad.

# Answer
> 0 votes
Try to attach the normal Box Collider with your sprite ray cast will detect that. I have also faced the same issue with this 2D Box Collider so i just used the normal box collider.

Performance wise its 2d collider only best but you dont get that much performance lag.

---
Tags: unity, collision-detection, raycasting
---


title: How to fix flare in unity?

text:
# Question
Title: How to fix flare in unity?
I have a simple sun flare that I would like to appear on my directional light (sun). However I cannot see the flare, I have tried setting the ignore layers to everything and checked and double checked that there is a flare layer on my camera. The light is also rotating constantly as I have a day/night cycle too if that means anything for the flare... Anyway, could someone show me how to fix this?

# Answer
You can attach the flare as-

Select light(in the Game)-\> Go to add component-\> Select Effects-\> Select Lens Flare Now you will get Flare's field, where you can attach your Sun Flare by simply select the flare that you want. In this you can also set the size of flare.
> 2 votes

# Answer
Sorted it out now, just had to add a Lens Flare component to my directional light, didn't realise you had to do that!
> 0 votes

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


title: xna split tileset into individual tiles

text:
# Question
Title: xna split tileset into individual tiles
I am trying to break a tileset image from my content folder into individual tiles during program. What I would like to have happen is that i can fill a list (of thing) with each possible tile so I can reference it by calling list(x).

However, in XNA I can't access the bitmap class and I can't Import it either (I might be doing it wrong) nor can I create a texture2d since where this is being called at comes from a different class file.

How do I split apart the tileset image into the separate tiles that I need and store them into a list?

# Answer
Instead of breaking up the tileset in individual tile textures you should keep a list of rectangles that make up the tiles. The Draw function has a source rectangle parameter that cuts out the part of the larger texture for you to use. So instead of a `List<Texture2d>()` use a `List<Rectangle>()` and have the SpriteBatch.Draw() use the source texture and rectangle as parameters.

The main advantages here are:

* Rectangles take up less resources (you could use a tile class that holds more tile properties than just the rectangle).
* Performance wise the tileset works as an sprite-atlas: this greatly reduces the required number of draw calls on your GPU because there is less texture switching required (all draw calls that use the same texture can be bundled).

Generally speaking there are very, very few reasons to split up a tileset in indivisual bitmaps and generally shouldn't be done. You'll notice that many games use sprite atlasses (or even generate them from individual sprites) instead of breaking them back up to separate bitmaps.

See also:

Especially tilemaps benefit greatly from having everything in one texture. Learn about atlasses and how to use them, it probably solves your problem.
> 1 votes

# Answer
I'm using this extention method to cut part of any texture:

```
public static class Texture2DExtention
{
    public static Texture2D GetPart(this Texture2D pSourceTexture, Rectangle pSourceRectangle)
    {
        Texture2D texture = new Texture2D(pSourceTexture.GraphicsDevice, pSourceRectangle.Width, pSourceRectangle.Height);
        Color[] data = new Color[pSourceRectangle.Width * pSourceRectangle.Height];
        pSourceTexture.GetData<Color>(0, pSourceRectangle, data, 0, data.Length);
        texture.SetData<Color>(data);
        return texture;
    }
}

```
> 0 votes

---
Tags: xna, tilemap
---


title: OpenGL pitching problem

text:
# Question
Title: OpenGL pitching problem
I've been trying to implement several camera movements for my application. So far yawing, rolling, strafing, walking has been working properly, but I can't get my pitching to work properly. If I continue pitching upwards, it doesn't rotate back 360 degree, and instead gets stuck looking at the top of the screen.

Here's my code for `Camera` class

```
class Camera
{
    float m[16];
    Vector dirForward, dirUp, dirRight;

    void loadCameraDirections()
    {
        glGetFloatv(GL_MODELVIEW_MATRIX, m);
        dirForward = Vector(m[2], m[6], m[10]).unitVector();
        dirUp = Vector(m[1], m[5], m[9]).unitVector();
        dirRight = Vector(m[0], m[4], m[8]).unitVector();
    }

public:
    Vector position;
    Vector lookAt;
    Vector up;

    Camera()
    {
        position = Vector(300, 0, 100);
        lookAt = Vector(0, 0, 100);
        up = Vector(0, 0, 1);
    }

    void rotatePitch(double rotationAngle)
    {
        glPushMatrix(); {
            glRotatef(rotationAngle, dirRight.x, dirRight.y, dirRight.z);
            loadCameraDirections();
        } glPopMatrix();

        lookAt = position.repositionBy(dirForward.reverseVector());
    }
}cam;

```

I call the `gluLookAt` funtion by-

```
gluLookAt(cam.position.x, cam.position.y, cam.position.z, cam.lookAt.x, cam.lookAt.y, cam.lookAt.z, cam.up.x, cam.up.y, cam.up.z);

```

# Answer
Found the problem. It was needed to update the `up` vector during pitching.

```
void rotatePitch(double rotationAngle)
{
    glPushMatrix(); {
        glRotatef(rotationAngle, dirRight.x, dirRight.y, dirRight.z);
        loadCameraDirections();
    } glPopMatrix();

    lookAt = position.repositionBy(dirForward.reverseVector());
    up = dirUp;
}

```

This solved the problem.
> 1 votes

---
Tags: opengl, camera, glut
---


# Question
Title: How do I create a jet engine exhaust effect with a shader?
How would I create a jet engine exhaust effect, as shown in the image from Fzero GX below.

GLSL and OpenGL examples/solutions are prefered, though other resources are also welcome.

**Requirements**

* The jet engine should have a straight exhaust flame, that does not bend when the vehicle turns.
* Some color variations in the flame are desirable, due to flame temperature variations.
* The flame is only seen in a view directly behind the vehicle, and slightly from the side.
* The flame should move slightly and also become bigger/brighter when the vehicle is thrusting.
* Performance is more important than physical correctness.

More inspirational images and a video of the desired effect:

# Answer
I can't provide you with specific code or a tutorial, because I've never done it before. But if you're at the stage where you're going to be trying different effects, you should be able to do the coding, but I'll tell you how I'd do it. It's also been a long time and no one has answered, so I hope this helps.

First, because you want:

1. Straight exhaust
2. Flame is only seen from behind and to the *side*
3. Performance is important

I would go with a textured cone. Or maybe a cone + a cylinder. The texture could be animated somewhat if you really wanted; but most likely I would use my frag shader to offset the texture lookup coordinates in a repeating ring according to time. So this "ring" of offset texture coords moves down the cone+cyclinder over time and repeats a bit. Probably start with a function of sin. This would be like a heat wave repeatedly washing down the length of the exhaust. Maybe add some other offsets to give the whole thing a slight wiggle as well.

This will mean that from directly behind, you would see very little except a ring from the inside of the cylinder and the smaller cone nestled inside. So from behind it would basically be two circles.

As your view moves to the side you can see more.

Now, to make it non-visible from other angles you can just use the camera position in the frag shader to determine the view vector and change opacity accordingly.

These simple shapes would have more performance than particles.

As for the texture, I wouldn't actually use one. But it helps to think of the above with texture lookups (in my opinion). Instead, I'd just use a colour ramp in the frag shader to colour texels different colours based upon how far the are.

An additional variable, "thrust", could be used to determine how far down the colour ramp it should be sampled. This way, one end of your colour ramp is always going to have alpha 0. With low thrust, this alpha 0 part starts half-way down your cylinder. At high thrust the alpha 0 is further toward the tip.

The values closer to the rocket could be more orange or something.

Finally, I'd use the thurst variable to bring the overall luminance of the colour up. So higher thrust drives us closer toward a white-hot flame.
> 3 votes

---
Tags: opengl, shaders, glsl, graphic-effects
---


# Question
Title: How can I recover polygons and normal maps from compiled games through emulation of D3D or OpenGL?
I am trying to generate labeled training data for an artificial visual cortex to learn on. I'm looking for a tool that will, instead of rendering the scene at each pixel just give me the pre-rendered data associated with each pixel. Presumably something like:

\[x,y\] -\> \[normal, depth, color, lighting, (lens flares?), texture, etc\]

# Answer
> 1 votes
RenderDoc can get you a lot, if not all, of that info.

I've previously used it during development to pull out my normal-maps, light maps etc. It also pulls out all the textures used in any fragment shaders etc.

---
Tags: opengl, directx, graphics, rendering, graphics-programming
---


# Question
Title: Unity Texture2D raw data TextureFormat problem
I am trying to load raw image data into a Texture2D in Unity using `LoadRawTextureData` but I can't get it to work correctly.

First I receive an array of bytes from an unmanaged function that captures a window. I am pretty sure these bytes represent an image in BGRA32 format.

```
int dataSize = width * height * 4;
byte[] imgData = new byte[dataSize];
bool success = CaptureWindow(windowInfo, imgData, (uint)(dataSize));

```

Then I try to create a new Texture2D with this data

```
Texture2D tex = new Texture2D(width, height, TextureFormat.BGRA32, false, true);
tex.LoadRawTextureData(imgData);
tex.Apply();

```

And finally I create a new plane and assign this texture to its material.

```
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
plane.GetComponent<MeshRenderer>().material.mainTexture = tex;

```

This doesn't work (Notice how the color channels are mixed up):

However, when I reverse the byte array before loading it into the texture as ARGB32, it does work:

```
Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
Array.Reverse(imgData);
tex.LoadRawTextureData(imgData);
tex.Apply();

```

The problem with this solution is that `Array.Reverse` is too slow.

Why doesn't loading it as BGRA32 work? Isn't BGRA32 just the reverse of ARGB32?

FYI: I am using Unity 5.1.2f1 on Windows and `SystemInfo.SupportsTextureFormat` returns true for both BGRA32 and ARGB32.

# Answer
> 3 votes
I think the key point is that the Array.Reverse just reverses the whole array but ARGB just reverses the order per pixel.

For example, I have 3 pixels with BGRA32 like (1,2,3,4), (5,6,7,8), (9,10,11,12). Notice that the semicon does not exist, it just helps to identify the pixels.

If you use Array.Reverse, it'll be (12,11,10,9), (8,7,6,5), (4,3,2,1). When using ARGB32, it'll be (4,3,2,1), (8,7,6,5), (12,11,10,9).

That's the difference, I hope this'll help you.

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


title: Implementing a 4x4 Game Board

text:
# Question
Title: Implementing a 4x4 Game Board
I struggle with efficiency in code, and I want to start my game off on the right foot.

I have a game that I'm making a 4 x 4 map of 'tiles' that a user can build their 'town' on. To keep track of the tiles, I'm planning on simply having a size-16 array of the type of my 'mapTile' enum. EX:

```
enum MapTiles { defaultTile, homeBase, farm1, farm2 /*...and so on...*/ };
static MapTiles playerMap[] = MapTiles[16] { /* ... default map setup ... */ };

```

Is there a way that is more efficient or more easy-to-extend way to implement such a map?

I'm using Unity and C# mostly, though i'm willing to work with any Unity-capable language if you have a clever answer.

# Answer
> 3 votes
`enum` is actually a good idea here, but what you want is for the enum to be:

`enum MapTileBuilding { defaultTile, homeBase, farm1, farm2 /*...and so on...*/ };`

and a class

```
class MapTile
{
   MapTileBuilding building;
   ... //other members e.g.
   //structuralStrength
   //isOnFire
   //troopCount
   //incomeGenerated
   //etc.
}

```

...which gives you the ability to support your initial building type property, as well as other properties you may wish to add to each tile later.

Finally, your array:

```
MapTile[,] map = new MapTiles[4, 4];

```

*Do not* inherit when composition will do (i.e. what you are already doing), otherwise you end up restricting yourself into narrowly-defined class hierarchies as you continue to try to extend the system. You want your tiles to be composable and inheritance is at odds with that idea. You'll begin adding new components as other concepts come into play (see examples above), and you don't want inheritance chains in your way at that point.

Re array dimensionality, the only time you will ever use a 1D array for a 2D concept is when you want precise control over memory access in low-level code (say in C or ASM), that is, in your case and in C# in general, just use the conceptually simpler 2D array.

P.S. Sorry if syntax is slightly off, C# isn't my first language these days.

# Answer
> 3 votes
Maybe enum is not the best choice in this case. You could try building a "tile" class and derive several subclasses from it (farm from your example). This way you could implement some sort of levelling system (instead of having to create a value for each level (farm1, farm2 etc)) inside the class and give the several kinds of tiles unique abilities in form of functions.

What you could also do is replacing the one-dimensional array with a two dimensional one. `MapTiles[,] playerMap = new MapTiles[4, 4]`

Long story short: Try to stay objectoriented and use classes, makes expansion of functionalities much easier.

---
Tags: unity, c#, game-mechanics, efficiency
---


# Question
Title: ID3D11Buffer and std::array : buffer looks empty
I am having trouble at rendering vertices stored in a `std::vector`.

```
// Create and initialize the vertex buffer.
D3D11_BUFFER_DESC vertexBufferDesc;
ZeroMemory(&vertexBufferDesc, sizeof(D3D11_BUFFER_DESC));
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.ByteWidth = sizeof(VertexData) * this->vertex_data.size();
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;

D3D11_SUBRESOURCE_DATA resourceDataVertex;
ZeroMemory(&resourceDataVertex, sizeof(D3D11_SUBRESOURCE_DATA));
resourceDataVertex.pSysMem = &(this->vertex_data);

HRESULT hr = pDevice->CreateBuffer(&vertexBufferDesc, &resourceDataVertex, &(this->pVertexBuffer));
if (FAILED(hr)) return false;

```

`this->vertex_data` being a `std::vector<VertexData>` with `VertexData` being:

```
// Vertex data
struct VertexData {
    XMFLOAT3 v;
    XMFLOAT2 vt;
    XMFLOAT3 vn;

    VertexData(XMFLOAT3 v, XMFLOAT2 vt, XMFLOAT3 vn) : v{ v }, vt{ vt }, vn{ vn } {}
};

```

Now I'm not sure doing `resourceDataVertex.pSysMem = &(this->vertex_data);` is a good idea. I can render another mesh without problem just by changing the `ID3D11Buffer` vertex buffer (said mesh being known at compile-time and stored in a C-Array).

This time around I simply get no render at all. I triple checked my object is in sight and `vertex_data` is fully populated.

# Answer
`&(this->vertex_data)` is the address of the `std::vector` container object itself, *not* the address of the data you stored in it.

Instead use `&(this->vertex_data.front())`
> 1 votes

---
Tags: directx11, vertex-buffer
---


# Question
Title: Event error: "...can only be called from the main thread"
I have some custom networking classes which I'm trying to use in a unity game (c#). The network class raises events, which I want to subscribe to in the game code. However, whenever I try to do anything substantial in response to an event, I'm running into and error like this:

> SomeFunction can only be called from the main thread

How can I get this to work? Presumably I have to communicate the event back to the main thread in some synchronous fashion. Is there a 'best practice' way of doing this in Unity?

# Answer
> 3 votes
So I solved this by writing the events to a queue, and then processing the queue synchronously during an update in the main thread. If there are other/better approaches though, I'd be happy to hear them.

# Answer
> 1 votes
I had a similar issue and this post helped me solve the same problem, I will share the specifics of the solution as I understand them.

My System.Process event-listening function triggered the "can only be called from the main thread" issue when I tried to call the delegate function.

```
private static void RunningProcess_OutputDataReceived (object sender, DataReceivedEventArgs e) {
    if(dataCallback != null) {
        dataCallback(e.Data);
    }
}

```

So instead of calling it from that function, I assign it to a static variable:

```
private static void RunningProcess_OutputDataReceived (object sender, DataReceivedEventArgs e) {
    if(dataCallback != null) {
        outputDataToSend = e.Data;
    }
}

```

And then call the delegate from Update():

```
void Update () {
    if(!string.IsNullOrEmpty(outputDataToSend)) {
        dataCallback (outputDataToSend);
        outputDataToSend = null;
    }
}

```

This solution is not reliable as the above one is, because if the OutputDataReceived function gets called multiple times before Update, only the most recent data packet will be forwarded. Enqueuing the incoming callbacks as UpTheCreek did is a good way around that, but this solution is very simple and lets you get past the fundamental issue.

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


# Question
Title: In Unity, why does my Hose particle system only show up in the scene preview?
I added particle system package from assets, selected hose particle system and put it in the scene. When I select 'Water Shower', it works in the scene preview, but on play, it just appears and vanishes in a fraction of a second. I set Looping, Play on awake enabled already, no result.

I also get the same result in a separate otherwise empty project.

Is this the problem with the prefab or there is something else I need to set to make it work properly?

I am trying to use hose particle system to create fountain like effect. I have used Steam particle system from same package, and it renders in play mode fine.

I know this is similar to this StackOverflow question. I have already tried the solutions provided there, and the asker also has not yet marked answer as a solution.

I've also made a video of what is happening.

# Answer
You can fix that issue by disabling the scripts on the parent object of hose, Happy Game Development.

**As directed below in picture, disable both red circled scripts.**

*If still problem persist you can ask in detail.*
> 1 votes

---
Tags: unity, particles
---


# Question
Title: How to loop background music through splash screen, main menu, options menu?
I am making a small game to sort of test the waters with Game Maker and I'm trying to have an mp3 play when the splash screen loads - and persist until the game either ends or the game starts (meaning splash, menu, options all play the background mp3).

I've created an object that isn't visible, but is present in my rooms (Menu, Splash, Options) that reads:

```
if (!sound_isplaying(BGM_Menu))
{
    sound_loop(BGM_Menu);
}

```

Which will, to my understanding, go through and check for whether or not the background music is playing, if not, start it. Well no music plays on any of the menu screens.

I figured I'd try something simple, to even just get my background music to play:

```
play_sound(BGM_Menu);

```

Nothing.

So then I decided I'd go to drag and drop since sound\_loop and sound\_play don't seem to want to work for me. What happens is, the BGM\_Menu will start to play on my splash screen, then as soon as as it transfers over to my Menu room (from Splash) it starts to loop the same song over the one that's still currently playing from the splash screen.

I've tried to solve this issue for about an hour and figured I'd come here to see if anyone else has experienced this or knows a fix.

Thanks!

# Answer
> 2 votes
I found out how to do it.

First of all, I was using the wrong (outdated / legacy) functions to play audio. Once I fixed that, I removed my object and instead made some creation code in my splash screen that will play / loop the music.

```
audio_play_sound(BGM_Menu, 10, true);

```

From there, I just had to make sure it closed when I entered the first stage of the game, so in my first room's creation code I put:

```
audio_stop_sound(BGM_Menu); //stops music from the menu
audio_play_sound(BGM_Ambient_Level1, 128, true);

```

Which will stop the sound from the menu and start playing the appropriate music for the level.

---
Tags: game-maker
---


# Question
Title: Calculating torque required to turn an object to a target rotation, depending on timestep
The function below works fine, when the timesteps of the physicsengine are short enough for the function to update often. It determinates when the ship(the object) needs to start decelerating to reach 0 angular velocity by the time it reaches the target rotation. (Always using maximum torque of the ship to turn)

However, I want to simulate this in a scenario with longer timesteps. Since my function checks for when to start decelerating each update, it will miss this moment when the timesteps are longer and move past the target rotation. The ship then starts swaying back and forth (obviously).

What I need is some way to determinate the torque I need to apply to the body for it to end up at that sweetspot where it needs to decelerate. That way the ship can start decelerating when the next update occurs and hopefully end up facing the target rotation with almost 0 angular velocity!

```
private void TurnTowardsTarget(Vector2 target, float deltaTime)
    {
        Vector2 delta = target - body.Position;
        float targetRot = (float)Math.Atan2(delta.Y, delta.X);
        float dRot = (float)Math.Atan2(Math.Sin(targetRot - body.Rotation),
            Math.Cos(targetRot - body.Rotation));
        float angularAcceleration = maxTurnForce / body.Inertia;
        float avgDecelerationVelocity = body.AngularVelocity / 2;
        float time = dRot / avgDecelerationVelocity;
        float decelerationRequired = body.AngularVelocity / time;

        //Target rotation is to the right (positive rotations are to the right)
        if (dRot > 0)
        {
            //If the ship is rotating to the right
            if (body.AngularVelocity >= 0)
            {
                //Should we start decelerating?
                if (decelerationRequired >= angularAcceleration)
                {
                    //Decelerate
                    TurnLeft();
                }
                else
                {
                    //Keep on accelerating towards the target
                    TurnRight();
                }
            }
            else
            {
                //The ship is rotating the wrong way, turn towards the target
                TurnRight();
            }
        }

        //Target rotation is to the left (negative rotations are to the left)
        if (dRot < 0)
        {
            if (body.AngularVelocity <= 0)
            {
                //Should we start decelerating?
                if (-decelerationRequired >= angularAcceleration)
                {
                    //Decelerate
                    TurnRight();
                }
                else
                {
                    //Keep on accelerating towards the target
                    TurnLeft();
                }
            }
            else
            {
                //The ship is rotating the wrong way, turn towards the target
                TurnLeft();
            }
        }
    }

```

I hope I made myself quite clear, all the TurnLeft() and TurnRight() do is to apply "maxTurnForce" in the corresponding direction. Please respond if you find a solution, my brain is melting (x.

/Kimmeh!

Edit:

This is how the code looks now after implementing Sam's suggestion, it slightly overshoots the target rotation though, no matter the update-rate. And jitters back and forth from the target rotation.

I've put Math.Abs() around the time-calculation, changed sign of decelerationDecelerationRequired and changed sign of angularAcceleration depending on dRot.

```
        Vector2 delta = turnToTarget - body.Position;
        float targetRot = (float)Math.Atan2(delta.Y, delta.X);
        float dRot = (float)Math.Atan2(Math.Sin(targetRot - body.Rotation),
            Math.Cos(targetRot - body.Rotation));
        float angularAcceleration = maxTorque * -Math.Sign(dRot) / body.Inertia;
        float avgDecelerationVelocity = body.AngularVelocity / 2;
        float time = Math.Abs(dRot / avgDecelerationVelocity);
        float decelerationRequired = -body.AngularVelocity / time;

        float torque = (decelerationRequired - angularAcceleration) * body.Inertia;
        torqueToApply = MathHelper.Clamp(torque, -maxTorque, maxTorque);

```

Just to clarify, I'm using Farseer physics engine, and I apply the torque of the body right before calling the step() function of farseer. The body has a slight angular damping, so it should actually rotate a bit less than expected.

I think it's because it now smoothly adjusts to the decelerationRequired. (say if the decelerationRequired == angularAcceleration, the change of torque would be 0, when it should be +-maxTorque in order to stop in time.

# Answer
The problem is that `TurnLeft()` and `TurnRight()` basically work as on/off switches instead of continuously. You need to simulate what happens when the force is applied only during a fraction of the timestep. I suggest adding an argument to these functions indicating the force to be used instead of `maxTurnForce`: at a reasonably small scale, applying half the force is equivalent to applying it for half the time.

Assuming your current computations are correct, you already know the value of that force: it is `(decelerationRequired - angularAcceleration) * body.Inertia`, which should be clamped between `-maxTurnForce` and `maxTurnForce`.

Another nice thing is that the sign of the force already indicates the direction. You can therefore merge `TurnLeft()` and `TurnRight()` into a single `Turn(float Force)` function.
> 3 votes

# Answer
I know this is a very old question, but I recently tried to solve this problem too. I found that modeling the problem as a damped harmonic oscillator proved to be a fairly elegant solution with nice results. Here is a javascript implementation using an imaginary physics engine:

```
/**
 * Applies a torque to the body to rotate it towards the angle.
 */
function rotate(body, targetAngle) {
    k = 3.0; // Spring constant. Higher means faster rotation.
    m = body.momentOfInertia;
    d = 1.0; // Damping coefficient. Lower than 1.0 will overshoot.
    c = -Math.sqrt(4 * m * k) * d;
    v = body.angularVelocity;
    x = angleDelta(body.angle, targetAngle);
    springForce = k * x;
    dampingForce = c * v;
    body.applyTorque(springForce + dampingForce);
}

/**
 * Modulo that handles negatives properly.
 */
function mod(a, b) {
    return ((a % b) + b) % b;
}

/**
 * Return the difference between angles, normalized to [-pi, pi].
 */
function angleDelta(a, b) {
    diff = b - a;
    return mod(diff + Math.PI, Math.PI * 2) - Math.PI
}

```

This is a solution to a slightly different problem than the original, but it's the solution I was looking for when I came across this question, so hopefully it will be of some use to somebody else who was also in my situation.
> 2 votes

# Answer
i allways use something like this:

```
        if (keyboardManager.IsKeyDown(Keys.W))
        {
            if (Math.Abs(_car.AngularVelocity) < 10f)
            {
                totalRotation = 0 -_car.Rotation;
                while (totalRotation < -MathHelper.Pi) totalRotation += MathHelper.TwoPi;
                while (totalRotation > MathHelper.Pi) totalRotation -= MathHelper.TwoPi;
                _car.ApplyAngularImpulse(totalRotation * 0.01f);
            }
        }

```

in this case i try to turn my car to the angle 0 (totalRotation = 0 -\_car.Rotation;).
> 0 votes

---
Tags: c#, physics
---


title: What is Khronos EGL?

text:
# Question
Title: What is Khronos EGL?
I see that modern OpenGL related code uses EGL, i can't get good resources for this so i ask here:

* what exactly is EGL ?
* if a platform supports OpenGL ES 2.0+ or OpenGL 3.0+ i can presume that will support EGL too ?
* when is convenient to use EGL and when it's not?

for what i can tell by now it's something similar to FreeGLUT to me, but looks much more portable and standardized.

# Answer
> 5 votes
**CAVEAT**: This is from the perspective of desktop OpenGL development; things may be different on mobile platforms.

EGL is Khronos's attempt to create a unified official cross-platform standard to replace (or at least abstract around) the platform-specific windowing/context-creation APIs like Windows's WGL, Unix's GLX, and Apple's Core GL. It sounds great in theory, but in practice it isn't very widely supported yet. It's certainly not a *requirement* that modern OpenGL programs use EGL.

Right now, EGL is really only relevant if you're using multiple Khronos graphics APIs in the same application, and want them to share a window / rendering context. If you're not using OpenGL, OpenGL ES, OpenMAX|AL, and/or OpenVG simultaneously, EGL probably won't provide you any benefits over an existing cross-platform OpenGL-only windowing system like FreeGLUT/SDL/GLFW/etc.

# Answer
> 0 votes
* what exactly is EGL ?

Like postgoodism's answer states, it's Khronos api that basically does the same thing as WGL, GLX, and other platform-specific "gl bootstrapping" libraries do. It also provides some cross-api functionality, like using OpenCL with OpenGL while sharing some resources. In theory, at least. =)

* if a platform supports OpenGL ES 2.0+ or OpenGL 3.0+ i can presume that will support EGL too ?

No. Desktop OpenGL doesn't need EGL. Practically all mobile devices that support OpenGL ES are based on EGL, though (I haven't seen a single one where this isn't the case, but then again, I haven't played with iOS devices for example, so I may be wrong).

* when is convenient to use EGL and when it's not?

It's convenient when you're not using some higher-level bootstrapping library like SDL or GLFW, and EGL is available. On the other hand, platform-specific library example code is probably more easily available. YMMV.

# Answer
> 0 votes
Well, EGL is supposed to be an API that abstracts the platform specific stuff like window creation and context creation. But it fails miserably - it simply lacks the necessary functions for trivial window management primitives. You still have to create windows with platform specific code (eg. X11 or GBM) and then pass it as a void\* pointer. Oh, and you'll have to load the *correct* backend library, otherwise booom-bang.

Bottom line: pretty useless. Much worse than GLUT (which, on the other hand, doesn't support direct fs w/o window system). And the API design is really horrible. Broken by design.

---
Tags: opengl-es2, egl
---


title: Water effect using DuDv Map weird look

text:
# Question
Title: Water effect using DuDv Map weird look
I'm trying to apply a DuDv Map effect (distortions) on my water.

My texture is 512x512 in size.

I'm using the following code:

(Vertex Shader)

```
out vec2 texCoord0;

void main()...
{

texCoord0 = vec2(position.x / 2.0 + 0.5, position.y / 2.0 + 0.5) * 6.0;
}

```

(Fragment Shader)

```
in vec2 texCoord0;

void main()
{
    ...

        vec3 ndc = (clipSpace.xyz / clipSpace.w)/ 2.0 + 0.5;

    vec2 reflectTexCoords = vec2(ndc.x, -ndc.y);
    vec2 refractTexCoords = vec2(ndc.x, ndc.y);

    vec2 distorsion1 = (texture(dudvMap, vec2(texCoord0.x, texCoord0.y)).rg * 2.0 - 1.0) * waveStrength; // waveStrength = 0.02;

    refractTexCoords += distorsion1;

    reflectTexCoords += distorsion1;

    vec4 reflectColor = texture(reflectionTexture, reflectTexCoords);
    vec4 refractionColor = texture(refractionTexture, refractTexCoords);

      outColor = mix(reflectColor, refractionColor, 0.5);
}

```

As you can see when I add my distortion to my reflection and refraction texture coordinates, it seems that something is wrong and can't figure what, because I get this effect:

Do any of you have any idea how can I fix this? Thanks for your time!

# Answer
The texture sampling function expects texture coordinates to be normalized into the \[0 - 1\] range.

You can divide by the size of the DuDv map in pixels, to normalize your texture coordinate into the \[0 - 1\] scale. For the sake of efficiency, I prefer to evaluate `1 / Size` on the CPU, and use multiplication instead of division in your shader.

---

I arrived at my assumptions because your offsetting code in the vertex shader seems to indicate that your variable `texCoord0` is measured in pixels, not normalized:

```
...
texCoord0 = vec2(position.x / 2.0 + 0.5, position.y / 2.0 + 0.5) * 6.0;
...

```

Your screen capture appears to contain high frequency aliasing which supports this theory. Here I have zoomed in on the characteristic artifacts which often arise from *severe* undersampling:
> 2 votes

---
Tags: opengl, uv-mapping, water
---


# Question
Title: Unity - Where do Animation Events fit in the Script Lifecycle Flowchart
I was looking at the Script Lifecycle Flowchart and suddenly I got thinking about Animation events.

Where do they fit, inside this flowchart? In which position would they be executed?

# Answer
> 3 votes
I just did a quick test, and they appear to be called in the grey section labelled "Internal Animation Update" (as one might expect).

ie. after yield StartCoroutine and before LateUpdate.

Rendering happens after LateUpdate, so visible changes caused by the firing of an animation event should be seen immediately in the current frame.

You can verify this by writing a simple script that prints to Debug.Log in a coroutine (other than WaitForEndOfFrame or WaitForFixedUpdate), LateUpdate, and a public method called by an animation event, and observing the order in which the printed lines appear.

**Edit:** It looks like animation changes caused in response to an Animation Event function call do not get acted on by the animation system until the next frame.

I tested this by responding to an event with `Animation.Play(some other animation)` and pausing execution in the subsequent LateUpdate. The first frame of the new animation was not yet reflected in my object's state, and animation events on that first frame had not yet fired.

So, at least *with regard to the animation that triggers it*, animation events seem to occur strictly after the internal animation update. (Its possible they're interleaved between updates of different animations - I haven't checked this case)

I have not verified this for objects using an Animator controller, but I expect them to behave the same way. I'd appreciate a correction if your experiments show otherwise. :)

---
Tags: unity
---


title: masking with 3d object in unity

text:
# Question
Title: masking with 3d object in unity
I have a 3d plane in my scene and some 3d objects behind that plane. So, i want to render only the part behind the 3d plane.

So how should I do this, should I have to use custom shaders, plz help.

# Answer
This type of thing is typically done with the stencil buffer. This has a couple of downsides for your use case in Unity though:

1. It would require modifying the shaders used for all of your through-the-looking-glass objects to check the stencil buffer (which can get annoying if you're using a lot of materials, or relying on shaders you haven't authored yourself, such as from a library or generated by another tool)
2. If you're using deferred rendering, Unity will ignore your stencil settings for the base and lighting passes anyway and only use them for the final shading pass, so you won't save as much fill rate as you might expect by stencil testing.

So, I'd lean toward doing it in a slightly less elegant way with multiple cameras and a rendertarget, because it will be quicker to get up & running and flexible as you add new objects & materials to your scene. It also makes it straightforward to apply image effects selectively to the objects on the other side.

1. Create a new layer in your project, I'll call it "Other Side," and place all the objects that you want visible through the plane into this layer. (You can do this with multiple layers too, if you need to maintain layer distinctions between them, like Other Side Obstacles and Other Side FX...)
2. Duplicate your camera (or set up a script that automatically duplicates the camera at runtime and keeps the two copies' parameters in-sync) and make both copies children of one parent. Put any camera movement scripts on the parent so it moves the cloned cameras as one.
3. Set one camera to Depth -1 (so it renders earlier) and its CullingMask to see only the Other Side layer(s). Set the other camera's CullingMask so that it does not see the Other Side layer(s), and ensure its ClearFlags wipe whatever comes before it ("Skybox" is usually what you want).
4. Create a new RenderTexture at the resolution of your game. (If you need to support multiple resolutions, you can write a script that creates/replaces this texture at runtime). Select the camera that sees the Other Side and set its Target Texture to use this RenderTexture.
5. Create a new material for your portal plane, using a shader something like this:

```
Shader "Unlit/ScreenspaceTexture"
{
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
    Tags { "RenderType"="Opaque" "Queue"="Geometry"}
    LOD 100

    Lighting Off

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        // make fog work
        #pragma multi_compile_fog

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float3 screenPos : TEXCOORD0;
            UNITY_FOG_COORDS(1)
            float4 vertex : SV_POSITION;
        };

        sampler2D _MainTex;
        float4 _MainTex_ST;

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
            o.screenPos = o.vertex.xyw;

            // This might be platform-specific. Test with OpenGL.
            o.screenPos.y *= -1.0f;

            UNITY_TRANSFER_FOG(o,o.vertex);
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            // sample the texture
            float2 uv = (i.screenPos.xy / i.screenPos.z) * 0.5f + 0.5f;

            fixed4 col = tex2D(_MainTex, uv);

            // apply fog
            UNITY_APPLY_FOG(i.fogCoord, col);
            return col;
        }
        ENDCG
    }
}
}

```

(The fog stuff is part of Unity's default unlit shader, but you can delete it if you don't need to use fog in your scene)

Set this material's texture to be the RenderTexture you created in step 4. Now the contents of that RenderTexture will be visible "through" any geometry that has this material applied.

If you need to alpha-test or blend this content with stuff behind the plane in the second camera's view, that will require some modifications.

Note that this method looks correct from the perspective of the in-game cameras, but won't look correct in general in the Scene view, since it doesn't have a duplicate camera of its own. There are ways to fix this if you need, but they get a bit more complex.
> 6 votes

---
Tags: unity, 3d, shaders
---


# Question
Title: Unable to move character to right position using SDL?
I am currently having problem moving a character right and showing him like he's running but after i press right key it moves right for one time and then when i enter left it goes left again but pressing right again doesn't make it go to right again. Here is my code that i am using :

```
#include <SDL2/SDL.h>

#include "game.h"
#include "graphics.h"
#include "input.h"

/* Game class
*  This class holds all information for our game loop
*/

namespace {
    const int FPS = 50;
    const int MAX_FRAME_TIME = 5 * 1000/ FPS;
}
Game::Game() {
    SDL_Init(SDL_INIT_EVERYTHING);
    this->gameLoop();
}
Game::~Game() {

}
void Game::gameLoop() {
    Graphics graphics;
    Input input;
    SDL_Event event;

    this->_player = Player(graphics, 100, 100);

    int LAST_UPDATE_TIME = SDL_GetTicks();
    //Start the game loop
    while(true){
        input.beginNewFrame();

        if(SDL_PollEvent(&event)){
            if(event.type == SDL_KEYDOWN){
                if(event.key.repeat == 0){
                    input.keyDownEvent(event);
                }
            }
            else if(event.type == SDL_KEYUP){
                input.keyUpEvent(event);
            }
            else if(event.type == SDL_QUIT){
                return;
            }
        }
        if(input.wasKeyPressed(SDL_SCANCODE_ESCAPE) == true){
            return;
        }
        else if(input.isKeyHeld(SDL_SCANCODE_LEFT) == true) {
            this->_player.moveLeft();
        }
        else if(input.isKeyHeld(SDL_SCANCODE_RIGHT) == true) {
            this->_player.moveRight();
        }

        if(!input.isKeyHeld(SDL_SCANCODE_LEFT) && !input.isKeyHeld(SDL_SCANCODE_RIGHT)){
            this->_player.stopMoving();
        }

    const int CURRENT_TIME_MS = SDL_GetTicks();
    int ELAPSED_TIME_MS = CURRENT_TIME_MS - LAST_UPDATE_TIME;
    this->update(std::min(ELAPSED_TIME_MS, MAX_FRAME_TIME));
    LAST_UPDATE_TIME = CURRENT_TIME_MS;

    this->draw(graphics);
}

}
void Game::draw(Graphics &graphics){
    graphics.clear();

    this->_player.draw(graphics);

    graphics.flip();

}
void Game::update(float elapsedTime){
    this->_player.update(elapsedTime);
}

```

and for player.cpp

```
#include "player.h"
#include "graphics.h"

namespace player_constants {
    const float WALK_SPEED = 0.2f;
}

Player::Player() {}

Player::Player(Graphics &graphics, float x, float y) :
    AnimatedSprite(graphics, "MyChar.png", 0, 0, 16, 16, x, y, 100)
    {
        graphics.loadImage("MyChar.png");

        this->setupAnimations();
        this->playAnimation("RunRight");
    }
void Player::setupAnimations() {
    this->addAnimation(1, 0, 0, "IdleLeft", 16, 16, Vector2(0,0));
    this->addAnimation(1, 0, 16, "IdleRight", 16, 16, Vector2(0,0));
    this->addAnimation(3, 0, 0, "RunLeft", 16, 16, Vector2(0,0));
    this->addAnimation(3, 0, 16, "RunRight", 16, 16, Vector2(0,0));
}

void Player::animationDone(std::string currentAnimation) {}

void Player::moveLeft(){
    this->_dx = -player_constants::WALK_SPEED;
    this->playAnimation("RunLeft");
    this->_facing = LEFT;

}
void Player::moveRight(){
    this->_dx = player_constants::WALK_SPEED;
    this->playAnimation("RunRight");
    this->_facing = RIGHT;

}

void Player::stopMoving() {
    this->_dx = 0.0f;
    this->playAnimation(this->_facing == RIGHT ? "IdleRight" : "IdleLeft");
}
void Player::update(float elapsedTime) {
    //Move by dx
    this->_x += this->_dx * elapsedTime;

    AnimatedSprite::update(elapsedTime);
}

void Player::draw(Graphics &graphics) {
    AnimatedSprite::draw(graphics, this->_x, this->_y);
}

```

EDIT:

Input.cpp file

```
#include "input.h"

/* Input class
* Keeps track of keyboard state
*/
//This function gets called at the beginning of each new frame
//to reset the keys that are no longer relevant
void Input::beginNewFrame(){
    this->_pressedKeys.clear();
    this->_releasedKeys.clear();
}

void Input::keyDownEvent(const SDL_Event& event){
    this->_pressedKeys[event.key.keysym.scancode] = true;
    this->_heldKeys[event.key.keysym.scancode] = true;
}
//this gets called when a key is released
void Input::keyUpEvent(const SDL_Event& event){
    this->_releasedKeys[event.key.keysym.scancode] = true;
    this->_heldKeys[event.key.keysym.scancode] = true;
}
//check if a certain key was pressed during the current frame
bool Input::wasKeyPressed(SDL_Scancode key){
    return this->_pressedKeys[key];
}
//check if a certain key was released during the current frame
bool Input::wasKeyReleased(SDL_Scancode key){
    return this->_releasedKeys[key];
}
//check if a certain key is currently being held
bool Input::isKeyHeld(SDL_Scancode key){
    return this->_heldKeys[key];
}

```

The main functions are 'moveLeft()', 'moveRight()' and 'stopMoving()' in player.cpp file above.

I think there's some problem in player.cpp file, can anyone help me with this as i have been trying to fix the problem for more than 3 hours. Thank you.

# Answer
> 0 votes
Finally, after spending more than 2 days on this problem, i found the bug as you can see above in Input.cpp in the following line:

```
void Input::keyUpEvent(const SDL_Event& event){
    this->_releasedKeys[event.key.keysym.scancode] = true;
    this->_heldKeys[event.key.keysym.scancode] = true;
}

```

`_heldKeys` should be made `false` for it to work properly.

# Answer
> 1 votes
One obvious issue I see in your code is in the event loop of your `Game::gameLoop` method. You're using `if(SDL_PollEvent(&event))` where the common pattern for event **looping** in SDL is `while(SDL_PollEvent(&event))`. Without more code it's hard to say if something else might cause the problem, but that one line might just be your problem. Even if it isn't it's better to process more than one event per frame, otherwise the user might experience annoying input lag.

Just making a wild guess here, but I guess it also might be a problem with your `Input` class, perhaps not reseting some variables.

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


# Question
Title: Javascript - How and where to put game initialization data
I'm new to JS game programming. In the past, when coding games (in Java), I tend to make separate files for configuration and game data (maps, character stats, etc). This is for separation of code and data. How can I effectively implement this on JS?

**EDIT**: This is for browsers only.

# Answer
> 2 votes
In this answer I'm going to assume that your game is a web game, if it's a locally running game in a Node.JS wrapper or something similar then the answer would be a little different and I'll edit the answer.
To have a data file that is separate from the code that runs it you can create a JSON file and then load it from the code.
First let us define a file called classes.json that looks like this:

```
{ "classList":[{ "name": "Wizard", "health": 5 },{ "name": "Rogue", "health": 23 }] }

```

Now load the data file by requesting it from the site:

```
var request = new XMLHttpRequest();
request.addEventListener("load", function requestListener(){
    //TADA! Now I have the class data.
    var classes = JSON.parse(this.responseText);
    var wizard = classes.classList[0];
    var rogue = classes.classList[1];
});
request.open("GET", "http://www.userx01s-game.com/classes.json");
request.send();

```

Doing it this way also allows you to delay loading the classes information until it is absolutely necessary to have it, thus speeding the initial load of the game.
P.S. For more information about ajax requests you can check out https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using\_XMLHttpRequest
EDIT: Here I will also include an example of if you don't want to use AJAX and instead just want to have the data available upon initial page load.

First create a file called classes.js that looks like this:

```
var classList = [{ "name": "Wizard", "health": 5 },{ "name": "Rogue", "health": 23 }];

```

Then in your HTML you include this file like normal:

```
<html>
  <head>
    <script src="classes.js" ></script>
    <script src="game.js" ></script>
  </head>
</html>

```

Finally in your game use the data as a standard JavaScript object:

```
var wizard = classList[0];
var rogue = classList[1];

```

---
Tags: javascript
---


# Question
Title: What software to use to make games for free with commercial use?
I am going to make a 2D game, I need free software for my team of five or less people. I should be able to sell in-game currency but the game will be free. The software should be able to compile the game for a windows, linux(debian), Mac, Android and IOS. I have windows and dont want software which needs .net framework or sort of. I need something similar to visual basic but for commercial uses by an organisation. I also will need software for creating open-source server which users can download and monetize themselves(selling stuff or currency in their server). Edit: it will be in-brouser game with node-js but still thanks.

# Answer
> -1 votes
According to your requirement you should go through Unity (Game Engine) and you can feature it with Visual Studio Tools.

As Unity has Free version as well as Licensed Version but you can develop your game in free version as well. And you will able to compile the game for so many platform as you mentioned in your question. So best luck :)

# Answer
> 0 votes
MonoGame meets all of your requirements: http://www.monogame.net/

Unity free edition does as well, though if your organization makes more than $100,000 a year, you can no longer use unity without paying.

---
Tags: 2d, browser-based-games
---


# Question
Title: How to stop Follow Path steering behavior when reached target?
I'm using libgdx Follow Path Steering Behavior in my top-down game. When unit reaches the end of the path, it goes to the start (not directly, but following path), then to the end and so on. How to stop following path, when unit reached the end point?

# Answer
Try `FollowPath#setArriveEnabled(boolean)`. It allows you to set whether or not to use Arrive behavior to approach the end of an open path.

Additionally, you might want to take a look at `FollowPath#setArrivalTolerance(float)`
> 1 votes

# Answer
When unit reaches to the end point then you can simply reset the position of the unit as previous what it was and then continue like in this manner or you can simply destroy the path after you done with it if possible.

I don't know about your platform but the concepts are same for any platform.So if my answer is helpful then please vote. ;)
> 0 votes

---
Tags: java, libgdx, steering-behaviors, path
---


# Question
Title: Editor-only circular contour around prefab instances
I have a prefab with radius setting, which programatically controls circular area with some stuff. I want instances of this prefab to display a circle with this radius in editor for convenience. Instead of radius setting I can attach circle collider to get visual border and then read its radius at runtime, but this seems code smell (I will need to programmatically remove/disable it etc), and resource waste. Are there some good practices to implement things like this?

# Answer
> 2 votes
Found an answer myself. That's actually quite easy. There is some "Gizmos" stuff for things like that, and it's possible to just overload OnDrawGizmos (in a script attached to prefab) and use built-in function to draw circle in editor:

```
private void OnDrawGizmos()
{
    UnityEditor.Handles.color = Color.yellow;
    UnityEditor.Handles.DrawWireDisc(transform.position, Vector3.back, Radius);
}

```

---
Tags: unity
---


# Question
Title: Libgdx using Box2d with TiledMap to create collision detection
I'm fairly new to Libgdx and have some good basic knowledge on Java. Right now I am stuck on how to add collision to my TiledMap, I am using the Mapeditor to create the tilemap. I read so many different ways how to approach this problem, but it is very difficult to understand how exactly this works.

Then I read about using Box2d for collision detection. Transforming the tiles I want into static bodys and creating a dynamic body for my player.

Right now I have created a MapBodyBuilder, wich should transform a tile layer into a specific box2d object. My problem is now, I don't know where I load this mapBuilder, how I can make my already set up Player to a dynamic body, where to create the player and how to combine the static tile bodies and the player body.

Hope someone can help me out!

As you can see I already tried myself didn't work tho .... I didn't post the whole player class, because most of it is for animation and userInput.

EDIT :.... I don't know what to do anymore.

```
public class MapBodyBuilder {

    static Array <Body> bodies = new Array<Body>();

    private static float ppt = 0;       // pixels per unit

    public static Array<Body> buildShapes(Map map, float pixels, World world) {
        ppt = pixels;

        MapObjects objects = map.getLayers().get("Kachelebene 1").getObjects();

        for (MapObject object : objects) {

            if (object instanceof TextureMapObject) {

                continue;

            }

            Shape shape;

            if (object instanceof RectangleMapObject) {
                shape = getRectangle((RectangleMapObject) object);
            }

    //      else if (object instanceof PolygonMapObject) {
                //      shape = getPolygon((PolygonMapObject) objects);

            //}

        /*  else if (object instanceof CircleMapObject) {
                shape = getCircle((CircleMapObject) objects);
            }  */

    //      else if (object instanceof PolylineMapObject) {
    //          shape = getPolyline((PolylineMapObject) objects);
        //  }

            else {
                continue;

            }

            BodyDef bd = new BodyDef();
            bd.type = BodyType.StaticBody;
            Body body = (Body) world.createBody(bd);
            ((com.badlogic.gdx.physics.box2d.Body) body).createFixture(shape, 1);

            bodies.add(body);

            shape.dispose();

        }

        return bodies;

    }

    private static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
        Rectangle rectangle = rectangleObject.getRectangle();
        PolygonShape polygon = new PolygonShape();
        Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / ppt, (rectangle.y + rectangle.height * 0.5f) / ppt);

        polygon.setAsBox(rectangle.width * 0.5f / ppt, rectangle.height * 0.5f / ppt);

        return polygon;
    }

    /*private static CircleShape getCircle(CircleMapObject circleObject) {
        Circle circle = new circleObject.getCircle();
        CircleShape circleShape = new CircleShape();
        circleShape.setRadius(circle.radius / ppt);
        circleShape.setPosition(new Vector2(circle.x / ppt, circle.y / ppt));

        return circleShape;

    } */

    private static PolygonShape getPolygon(PolygonMapObject polygonObject) {
        PolygonShape polygon = new PolygonShape();
        float[] vertices = polygonObject.getPolygon().getTransformedVertices();

        float[] worldVertices = new float[vertices.length];

        for (int i = 0; i < vertices.length / 2; i++) {

            System.out.println(vertices[i]);
            worldVertices[i] = vertices[i] / ppt;

        }

        polygon.set(worldVertices);
        return polygon;

    }

    private  static ChainShape getPolyline(PolylineMapObject polylineObject) {
        float[] vertices = polylineObject.getPolyline().getTransformedVertices();
        Vector2[] worldVertices = new Vector2[vertices.length / 2];

        for (int i = 0; i < vertices.length / 2; i++) {
            worldVertices[i] = new Vector2();
            worldVertices[i].x = vertices[i * 2 ] / ppt;
            worldVertices[i].y = vertices[i * 2 + 1] / ppt;
    }

        ChainShape chain = new ChainShape();
        chain.createChain(worldVertices);
        return chain;

    }
}

```

---

```
public class WorldRenderer {

    // rectangle

    TiledMapTileLayer tilelayer;

    private ShapeRenderer sRDebugRectangel = new ShapeRenderer();

    private static final float UNIT_SCALE = 6 / 16f;
    public SpriteBatch batch;
    private OrthogonalTiledMapRenderer renderer;
    private OrthographicCamera camera;

    private World world;

    private MapBodyBuilder bodyBuilder;
    private Player player;
    private Level level;

    public WorldRenderer() {

        level = new Level("Leveltry.tmx");
        renderer = new OrthogonalTiledMapRenderer(level.getMap(), UNIT_SCALE);

//      int columns = tilelayer.getWidth();
    //  int row = tilelayer.getHeight();

        //Cell cell  =  tilelayer.getCell(columns, row);

         world  = new World(null, false);

        bodyBuilder = new MapBodyBuilder();

        player = new Player();

        /*BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyType.DynamicBody;

         Body body = world.createBody(bodyDef);

        CircleShape circle = new CircleShape();
        circle.setRadius(8); */

        //player.world = new World(null, false);

        camera = new OrthographicCamera();
        camera.setToOrtho(false, 200, 100);

        camera.update();

        batch = new SpriteBatch();

    //  Rectangle playerRect = new Rectangle(player.position.x, player.position.y, 32, 32);

    }

    public void render(float delta) {

       // bodyBuilder.buildShapes(level.getMap(), 32, world);
        //world.getBodies(null);

        camera.position.set(player.getX(), player.getY(), 0);
        batch.setProjectionMatrix(camera.combined);

        renderer.setView(camera);

        camera.update();

        renderer.render();

        player.render(batch, delta);

        //System.out.println(player.position.x + " " + player.position.y);
    }

    public void dispose() {
        batch.dispose();
    }

}

```

---

```
public Player() {

       // createBody();

        position = new Vector2(200, 100);

        createPlayer();
    }

    public void createPlayer() {

        tex = new Texture("angel.png");
        frames = TextureRegion.split(tex, 48, 48);

        walkingHorizontalLeft = new Animation(0.2f, frames[1]);
        walkingHorizontalRight = new Animation(0.2f, frames[2]);
        walkingVeritcalDown = new Animation(0.2f, frames[0]);
        walkingVerticalUp = new Animation(0.2f, frames[3]);

        animations = new Animation[4];

        animations[0] = walkingHorizontalLeft;
        animations[1] = walkingHorizontalRight;
        animations[2] = walkingVeritcalDown;
        animations[3] = walkingVerticalUp;

    }

public void render(SpriteBatch batch, float delta) {

        handleInput();

        frameTime += delta;

        position.x += velocity.x * delta; //distance travelled is equal to the velocity * the time taken
        position.y += velocity.y * delta;

        velocity.x = (float) (velocity.x * 0.8f);
        velocity.y = (float) (velocity.y * 0.8f);

        boolean idle;
        //Lets check current state
        if ((Math.abs(velocity.x) + Math.abs(velocity.y)) < 4f) { //Some small value)
            //Its idle
            idle = true;
        } else {
            //Its moving
            idle = false;
        }

        if (idle) {
            currentFrame = animations[facing].getKeyFrame(frameTime, false);//idleAnimation.getFRame(...), or maybe just a non moving region, whatever you want
        } else {

            currentFrame = animations[facing].getKeyFrame(frameTime, true);
        }
        //So Ive created the "facing" short variable, we can encode the facing direction to this variable
        //Value of 0 left
        //Value of 1 right
        //value of 2 up
        //value of 3 down

        // System.out.println(velocity.x + velocity.y);
        batch.begin();
        batch.draw(currentFrame, position.x, position.y, 15, 15);
        batch.end();

        //System.out.println("this is x   " + position.x + "this is y   "  + position.y);

    }

/*  private void createBody() {
             BodyDef bodyDef = new BodyDef();
             bodyDef.type = BodyType.DynamicBody;

             Body body = world.createBody(bodyDef);

             CircleShape circle = new CircleShape();
             circle.setRadius(8);

    }  */

```

# Answer
I realise this is five months old, but still relevant. The way I do it is by creating a `Physics` utility class for my unit calculation and conversion:

```
public final class Physics {

    public static final float PIXELS_PER_UNIT = 32f;

    private Physics() {}

    public static float toUnits(float pixels) {
        return pixels / PIXELS_PER_UNIT;
    }

    public static Vector toUnits(Vector2 pixels) {
        return new Vector2(toUnits(pixels.x), toUnits(pixels.y));
    }

    public static float toPixels(float units) {
        return units * PIXELS_PER_UNIT;
    }

    public static Vector2 toPixels(Vector2 units) {
        return new Vector2(toPixels(units.x), toPixels(units.y));
    }
}

```

I then create a `ShapeFactory` class which converts `MapObject`s into shapes of the same type:

```
public final class ShapeFactory {

    private ShapeFactory() {}

    public static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
        return getRectangle(rectangleObject.getRectangle());
    }

    public static PolygonShape getRectangle(Rectangle rectangle) {
        PolygonShape polygon = new PolygonShape();

        Vector2 size = new Vector2(
                Physics.toUnits(rectangle.x + rectangle.width * 0.5f),
                Physics.toUnits(rectangle.y + rectangle.height * 0.5f)
        );

        polygon.setAsBox(
                Physics.toUnits(rectangle.width * 0.5f),
                Physics.toUnits(rectangle.height * 0.5f),
                size,
                0.0f
        );

        return polygon;
    }

    public static CircleShape getCircle(CircleMapObject circleObject) {
        return getCircle(circleObject.getCircle());
    }

    public static CircleShape getCircle(Circle circle) {
        CircleShape circleShape = new CircleShape();
        circleShape.setRadius(Physics.toUnits(circle.radius));
        circleShape.setPosition(new Vector2(Physics.toUnits(circle.x), Physics.toUnits(circle.y)));

        return circleShape;
    }

    public static PolygonShape getPolygon(PolygonMapObject polygonObject) {
        return getPolygon(polygonObject.getPolygon());
    }

    public static PolygonShape getPolygon(Polygon polygon) {
        PolygonShape polygonShape = new PolygonShape();

        float[] vertices = polygon.getTransformedVertices();
        float[] worldVertices = new float[vertices.length];

        for (int i = 0; i < vertices.length; ++i) {
            worldVertices[i] = Physics.toUnits(vertices[i]);
        }

        polygonShape.set(worldVertices);

        return polygonShape;
    }

    public static ChainShape getPolyline(PolylineMapObject polylineObject) {
        return getPolyline(polylineObject.getPolyline());
    }

    public static ChainShape getPolyline(Polyline polyline) {
        ChainShape chain = new ChainShape();

        float[] vertices = polyline.getTransformedVertices();
        Vector2[] worldVertices = new Vector2[vertices.length / 2];

        for (int i = 0; i < vertices.length / 2; ++i) {
            worldVertices[i] = new Vector2();
            worldVertices[i].x = Physics.toUnits(vertices[i * 2]);
            worldVertices[i].y = Physics.toUnits(vertices[i * 2 + 1]);
        }

        chain.createChain(worldVertices);

        return chain;
    }
}

```

Because I use Ashley (an Entity Component System created for libGDX), I create a system which converts all `MapObject`s from my map's Collision layer into bodies:

```
public class TiledMapCollisionSystem extends EntitySystem {

    public TiledMapCollisionSystem() {
        MapObjects objects = LevelManager.getActiveMap().getLayers().get(Layers.COLLISION).getObjects();

        for (MapObject object : objects) {
            if (object instanceof TextureMapObject) {
                continue;
            }

            Shape shape;

            if (object instanceof RectangleMapObject) {
                shape = ShapeFactory.getRectangle((RectangleMapObject) object);
            } else if (object instanceof PolygonMapObject) {
                shape = ShapeFactory.getPolygon((PolygonMapObject) object);
            } else if (object instanceof PolylineMapObject) {
                shape = ShapeFactory.getPolyline((PolylineMapObject) object);
            } else if (object instanceof CircleMapObject) {
                shape = ShapeFactory.getCircle((CircleMapObject) object);
            } else {
                continue;
            }

            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyDef.BodyType.StaticBody;
            Body body = WorldManager.world.createBody(bodyDef);
            body.createFixture(shape, 1);

            shape.dispose();
        }
    }
}

```

Note that the map is already loaded and the Box2D world is already created before the system is instantiated. `Layers.COLLISION` is a simple constant String "Collision". You don't need to create a System if you aren't using Ashley, as you can simply create another utility class which does the same thing.
> 2 votes

# Answer
First of all you should use a DebugRenderer for testing your Box2D world. Otherwise you will have a hard time figuring out what your world is actually doing:

```
Box2DDebugRenderer debugRenderer = new Box2DDebugRenderer();

//the below code goes at the end of the render method:
debugRenderer.render(world, camera.combined);

```

Then another thing that catched my attention is that you never create a Fixture for your player. You just created the shape, but then you do nothing with it. A Fixture is what gives your Body a shape, mass etc. You will have to create a Fixture similar to this and add it to your Body:

```
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;

Body body = world.createBody(bodyDef);

CircleShape circle = new CircleShape();
circle.setRadius(8);

//now create fixture and add it to the body:
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = density;
fixtureDef.friction = friction;
fixtureDef.restitution = restitution;

body.createFixture(fixtureDef);

circle.dispose(); //dispose circle shape, you don't need anymore.

```

I didn't dig through all of your code but I think the above should get you started. Also check the box2d libgdx tutorial like for example this box2d-tutorial.
> 0 votes

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


# Question
Title: Detecting collision with walls (is this a good solution?)
I'm trying to make the collision smooth (it must open the animation, but not move the character).

I've implemented 'fake positions':

* int step = 20;
* fake\_left\_x = x-step;
* fake\_right\_x = x+step;
* fake\_up\_y = y+step;
* fake\_down\_y = y-step;

While updating player position, I'm checking if fake positions are out of the screen. If yes - nothing happens.

Is this a good solution? What do you think?

# Answer
This is a more typical way:

```
if (hit key left)
{
    animation.play();
    targetPosition.x = x - step; //this is where we propose to move to
}

//... repeat as above for right, up, down

//now only move if it's a valid move
//x axis:
if (targetPosition.x >= 0 && targetLocation < xPositionsCount) //target position is valid
{
    newPlayerPosition = targetPosition; //or gradually move move the sprite to target
}

//...y axis is similar to x axis

```
> 1 votes

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


# Question
Title: libGDX Error loading font file - Netbeans
I'm trying to load a font in libGDX. But I can't figure out want I do wrong.

Code:

```
white = new BitmapFont(Gdx.files.internal("fonts/white.font"), false);

```

Error:

```
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Error loading font file: fonts/white.font
    at com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.load(BitmapFont.java:657)
    at com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.<init>(BitmapFont.java:469)
    at com.badlogic.gdx.graphics.g2d.BitmapFont.<init>(BitmapFont.java:115)
    at scenes.GameMode.create(GameMode.java:61)
    at scenes.GameMode.<init>(GameMode.java:45)
    at com.circle.game.Circle.create(Circle.java:17)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:143)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1931)
    at com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.load(BitmapFont.java:480)
    ... 7 more
:desktop:run

```

# Answer
> 0 votes
With LibGDX, the **user.dir** property is used for the `Gdx.files.internal(...)` root directory. This property is, unless explicitly changed, set to the directory from which the app was launched.

With that being said, you should move your *assets* folder to your target platform's root dir (desktop for Desktop, android for Android, etc.).

Also, after the first step (Whatever it may be, you should use `assets/fonts/white.font` rather than `fonts/white.font`, as LibGDX does not automatically use the assets folder.

# Answer
> 0 votes
Everything is correct.. But Have you set the working directory of the desktop project? If not set working directory of desktop project to Android/assets Else, it is the error caused by the file itself which tool did you use to generate the font file? Use a tool called BMFont

---
Tags: java, libgdx
---


title: Java LWJGL inventory using ArrayList

text:
# Question
Title: Java LWJGL inventory using ArrayList
I'm making a game in Java with LWJGL 2.9.3 and Slick2D, and I'm working on creating an inventory. I managed to set it up almost completely, but I ran into a problem. When I'm rendering the slots, only the last slot gets render (I loop through an `ArrayList<InventorySlot>` and then render each element of it).

Here is the code for the Inventory:

```
package com.jarza.ageofquest.inventory;

import java.util.ArrayList;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

public class Inventory {

    public static int x, y;
    public static int slotnum;
    static Image invbg;

    public static ArrayList<InventorySlot> inventoryslots = new ArrayList<InventorySlot>();

    public Inventory(int slotNum){
        slotnum = slotNum;

        try {
            invbg = new Image("res/inv/invbg.png");
        } catch (SlickException e) {
            e.printStackTrace();
        }
        x = (1080/2) - invbg.getWidth();
        y = 20;
    }

    public static void init(){
        // Initializes all the slots
        int k = 0;
        for(int i = 0; i < (slotnum / 10); i++){
            for(int j = 0; j < 10; j++){
                inventoryslots.add(new InventorySlot((i * 32), (j * 32), k, 1));
                System.out.println((i * 32) + " / " + (j * 32) + " / " + k);
                k++;
            }
        }

        Item.init();
    }

    public static void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
        g.drawImage(invbg, x, y);
        for(InventorySlot s : inventoryslots){
            s.render(g);
            //System.out.println("ID: " + s.getID());
        }

    }

    public void update(Graphics g){
        for(InventorySlot s : inventoryslots){
            s.update();
        }
    }

    public static void addItem(int id){
        for(InventorySlot s : inventoryslots){
            if(s.getItem() == -1){
                s.setItem(id);
            }
        }
    }
}

```

In the init method I loop through the `ArrayList<InventorySlot>` and set each element to a new InventorySlot, which takes an x, y, an ID and a value (the item it contains; -1 for nothing). Then I render and update each InventorySlot, as shown here:

```
package com.jarza.ageofquest.inventory;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

import com.jarza.ageofquest.states.Play;

public class InventorySlot {

    Image slot;
    public static int x, y, id, item;

    @SuppressWarnings("static-access")
    public InventorySlot(int x, int y, int id, int item) {
        try {
            slot = new Image("res/inv/slot.png");
        } catch (SlickException e) {
            e.printStackTrace();
        }
        this.x = x;
        this.y = y;
        this.id = id;
        this.item = item;
    }

    public void render(Graphics g) {
        // Draws the slot, Ill later add drawing items
        g.drawImage(slot, x, y);
        g.drawImage(Item.getImg(item), x, y);
        //System.out.println("ID:" + id + " item: " + item);
    }

    public void update(){
        // To be continued...
    }

    public int getID(){
        return id;
    }

    public int getItem(){
        return item;
    }

    public void setItem(int iid) {
        item = iid;
    }
}

```

It's pretty much the most basic thing you would want. The part where it mentions the Item class is also actually simple. Here is the Item class:

```
package com.jarza.ageofquest.inventory;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

public class Item {

    public static int dmg, tier;
    public static int  maxItems = 2;
    public static String name;

    public static Image noitem;
    public static Image[] img = new Image[2];
    public static String[][] names = new String[maxItems][1];

    public Item(String name, int dmg, int tier){
        this.name = name;
        this.dmg = dmg;
        this.tier = tier;
    }

    public static void init(){
        try {
            noitem = new Image("res/inv/items/noitem.png");
        } catch (SlickException e1) {
            e1.printStackTrace();
        }

        for(int i = 0; i < maxItems; i++){
            try {
                img[i] = new Image("res/inv/items/" + i + ".png");
            } catch (SlickException e) {
                e.printStackTrace();
            }
        }
    }

    public static Image getImg(int itemid){
        if(itemid != -1){
            return img[itemid];
        }else{
            return noitem;
        }
    }

    public String getName(int itemid){
        return names[itemid][0];
    }

    public String getTier(int itemid){
        return names[itemid][1];
    }
}

```

Each Image is named with it's items ID .png. When I run the game, only the last slot appears. Although it works (I can put items into it) I do need all of them to work, so could anyone please help me with this?

# Answer
> 3 votes
The properties *x, y, id, item* of your **InventorySlot** class are declared as static, thus not being bound to single instances.
This results in overriding these values for all instances upon changes, which is, why only your last slot is being rendered. In fact, they are all being rendered, though, all at the same position.

Simply remove the *static* keyword in your declaration, to get unique values for each **InventorySlot** instance:

```
public int x, y, id, item;

```

---
Tags: java, lwjgl, slick, inventory
---