title: Make character move behind object

text:
# Question
Title: Make character move behind object
I used Tiled Editor for making maps for my own game, I do not run any engine or anything. I have separated terrain layer and object layer in TiledEditor.

However I have problem with trees I want to make my character move behind the tree. But I have no idea how because even if it is different layer I am still rendering it by 8x8 pixel blocks.

Now my character is always on top as it is the last thing that I render.

But if I change the render order my character would be behind the tree even if the character will stay in front of the tree like this:

# Answer
This is one of the main reasons why we don't use tiles for objects, like trees. Sprites are much easier to manage.

Anyhow, most engines, frameworks and APIs allow you to render the sprites based on a layer depth you supply to it. This value is usually between 0 and 1 by default, but it can be changed with projections. I'll use these values as a starting point, so if you have something different, then convert the values below to that system.

We need to dedicate a part of the layer depth range to the player and the terrain. I'll use the range `[0.4, 0.6]` and I'll give the player a layer depth of 0.5 (the center of the range). Now what we need is the following: When a tile is above the player's position, then it should have a bigger layer depth. If it's below the player, then it should have a smaller one (objects with smaller layer depths are closer to the "camera"). The topmost object should have a layer depth of 0.6 and the lowest should have a layer depth of 0.4. This is trivial if you know the height of the screen in the engine's/framework's/API's coordinate system (e.g. 2 in OpenGL, the screen height in pixels in MonoGame) and the projected coordinate of the object.

First of all, take the coordinate of the object, project it in the camera's coordinate system, then normalize the y coordinate (if the coordinates after the projection are between -1 and 1, then add 1 and divide by two, if it's between 0 and 800, then simply divide by 800). Now, there are two cases. If the camera's coordinate system has a lower y value the higher you draw something on the screen (like how most 2d frameworks do it), then do the following:

Take the normalized y coordinate, multiply it by 0.2 (or the size of the range you use), subtract 0.1 from it, then subtract the result from 0.5 to get the layer depth.

```
layerDepth = 0.5 - (normalizedY * 0.2 - 0.1)

```

If the camera's coordinate system has a higher value the higher you draw something on the screen (like how most APIs do it), then do the following:

Do the same as with the last case, but add the result to 0.5 instead of subtracting it:

```
layerDepth = 0.5 + (normalizedY * 0.2 + 0.1)

```
> 1 votes

---
Tags: movement, objects, depth
---


# Question
Title: How to delete a score after collecting all collectibles
I'm making a small game for my English class, and in the beginning, you have to collect rocks. I already have the code for counting how many rocks have been picked up, and the GUI to display while the game runs. After the player collects all 9 rocks I would like for the GUI to disappear or delete itself since it won't be used anymore throughout the game, and for new text to appear at the top of the screen saying "Go To The Lottery"

I'm still very new to Unity so posting the code, and then following up with a brief explanation as to what does what would be majorly appreciated (but not at all demanded)

Both codes are in JavaScript

```
#pragma strict

static var currentScore : int = 0;
var offsetY : float = 40;
var sizeX : float = 100;
var SizeY :float = 40;

function OnGUI () {
GUI.Box (new Rect (Screen.width/2-sizeX, offsetY, sizeX, SizeY), "Rocks Collected: " + currentScore);

}

```

^^ This is my GameMaster script, which is in a empty game object galled "\_GM" ^^

```
#pragma strict

function OnTriggerEnter (info : Collider)
{
    if (info.name == "Player")
    {
    GameMaster.currentScore += 1;
    Debug.Log ("Picked stone up");
    Destroy (gameObject);
    }
}

```

^^ This is my RockCollection script and it's what actually tells the GameMaster script to add 1 to the score and then delete the rock so you can't continuously pick it up

# Answer
Your GameMaster script needs to be made aware of how many rocks the player needs to collect in order to progress. The simple solution would be to simply hard-code the targetScore to 9 and then check whether or not it is reached in your OnGui function:

```
#pragma strict

static var currentScore : int = 0;
static var targetScore : int = 9;
var offsetY : float = 40;
var sizeX : float = 100;
var SizeY :float = 40;

function OnGUI () {
    var text : String;
    if (currentScore < targetScore) {
         text = "Rocks Collected: " + currentScore;
    } else {
         text = "Go To The Lottery";
    }
    GUI.Box (new Rect (Screen.width/2-sizeX, offsetY, sizeX, SizeY), text);

}

```

A better solution would be to initialize the `targetScore` to 0 and have each rock increment it in their `Start` function. That way your target score is automatically set to the number of rocks you have in the scene. Just keep in mind that when you restart the game you need to reset both the currentScore and the targetScore to 0.

This is how this start function of your `Rock` script would look

```
function Start() {
    GameMaster.targetScore += 1;
}

```
> 0 votes

# Answer
You change which text the GUI box will display. i don't know whats your code but it should be something like this

```
if (rocks = 9)
  text = "Go To The Lottery"
else
  text = rocks

```
> 0 votes

# Answer
I have followed the Roll-a-ball tutorial from Unity a while ago and I remember displaying a 'winning text' whenever I would collect all cubes.

In my player controller I had a method for the actual pickup which would also call `SetCountText()` upon picking up a cube.

```
void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
        if (count >= 17)
        {
            winText.text = "You Win! Yayy";
        }
    }

```

As you can see, I would display the actual score and if I would collect all objects (17) the win text would be set.

You could do something similar but then have whatever you want to achieve, happen inside the `if` statement.
> 0 votes

---
Tags: unity, gui, text
---


# Question
Title: Is it efficient to only store interface pointers for components in an entity-component system?
Let us say that I have a simple architecture, and I have implemented event-based communication between the objects and the components. In this architecture, `Game` has `GameObject`s, and the `GameObject`s have `Component`s. GameObjects have reference to Game and Components have reference to the GameObject.

There is no shared interface between these objects. Is it worth making an interface to implement `Update()` and `ReceiveMessage()`, and then only store these interface pointers?

For example, should I store `Component` pointers in a `GameObject`, or I should make an `EventListener` interface with `Update()` and `ReceiveMessage()`, and store `EventListener` pointers? I think this is a good way to force modularity, but maybe I am over complicating it.

# Answer
> 2 votes
I'd say that if you do indeed want *anything* that implements EventListener to be eligible for inclusion as a part of GameObject (or Game), then sure, that's a good way to go. However, that also means you could accidentally hook up a GameObject as a Component, or Component as a GameObject of Game. That's probably not what you want. Keep in mind that good design is not infinitely flexible, but imposes restrictions to keep the programming errors uncompilable.

If it were me, I would keep your current architecture, *and* use an EventListener interface that the base Component and GameObject classes implement (virtually). This will ensure your event handling is consistent while keeping your type safety. It also makes it so that your listeners can subscribe to other publishers than their container with their interface, if you need that functionality. For example, a Component that receives most events from GameObject could directly subscribe to some event from Game if it made sense to do so.

# Answer
> 1 votes
Two classes should implement the same interface when it makes sense to use both of these classes in the same context.

Also, when a method accepts an `EventListener` as an argument, that implies that it accepts *any* `EventListener`, not just those of a specific type (see Liskov Substitution Principle for more information). So when a GameObject has a `List<EventListener> components`, it implies that it can have `Component`s as components, but also other `GameObject`s and even other `Game`s as components. Does that make sense in your software architecture? Maybe it does. But when it does not and you only want to allow components to be components, you should use the correct type and declare it as a `List<Component>`.

# Answer
> 0 votes
> Is it worth making an interface to implement `Update()` and `ReceiveMessage()`, and then only store these interface pointers?

No.

The question is not about *worth* here, it's really about the design intents.

Although the three classes implement both `Update()` and `ReceiveMessage()`, these two method are not linked together conceptually. One is about communication between different objects, while the other is about changing the state on a regular basis. It *could* make sense to make *two* interfaces:

```
class IUpdatable
{
public:
  void Update() = 0;
}

class IEventListener
{
public:
  void ReceiveMessage() = 0;
}

```

but then you'd have to wonder, can any `IEventListener` be put in place of another? Most likely. Can any `IUpdatable` be put in place of another? Most unlikely. The other answers cover that.

So in your situation, I suggest you create the `IEventListener` interface for inter-object communication, but that you store `Component` pointers in your `GameObject`s, and `GameObject` pointers in your `Game`.

---
Tags: c++, architecture, events
---


# Question
Title: What is the game design lingo for the computer's ability to render shiny water?
What is the game design lingo for the computer's ability to render shiny water? I am new to game design and I'm trying to write a formal paper to a colleague.

# Answer
> 3 votes
It sounds like you're looking for "**per-pixel lighting**"

Previous/lower-spec shading modes often used "vertex lighting" where the shading function was evaluated only at the vertices of each triangle and interpolated in between. This made it impossible to get crisp specular highlights (the sharp bright spots you see on shiny objects that move with your view angle) or other forms of specular reflection (like reflection maps)

This is often paired up with techniques like **Phong/Blinn-Phong shading** (particular shading formulas that were popular for calculating specular highlights, before physically-based/inspired models became more prevalent) and **normal mapping** (a technique using textures to add fine surface detail smaller than the rendered triangles, which gives specular highlights and reflections more edges to catch and glint off of)

This is also related to consoles supporting a programmable fragment stage in their **programmable pipeline**, allowing developers to write custom **pixel shaders** / **fragment shaders** to implement these lighting and reflection models. Early rendering hardware (ones with a "fixed function pipeline") lacked a programmable fragment stage, limiting games to combinations of pre-configured shading options.

# Answer
> 0 votes
Depends on the tech you use.

For a mostly flat water surface you can use bump mapping (adjusting the normal vector based on location on the mesh and some algo to create waves) to add reflective highlights to give appearance of waves. This means sampling a non-color texture in the fragment shader.

For bigger movement you'll need to actually change the surface geometry. This can be done with tesselation shading or it's predecessor geometry shading. Or you can just send a lot of triangles to the gpu. Doing the per-vertex displacement+normal manipulation requires sampling a texture in the vertex stages.

# Answer
> 0 votes
That would depend on how good you want it to look. If you just want to look wet and shiny and reflect only the light, look for Phong model lighting. If you want to the water to reflect everything else, look for reflection mapping.

Phong model lighting performs lighting calculations per pixel, which makes for reasonably accurate lighting effects

Reflection mapping requires rendering to a temporary texture then sampling later when rendering the water. This can either by static, i.e. a skybox, or dynamic, which is a version of a skybox which is redrawn each frame.

Combining both of these effects along with some messing around with surface normals, and some refraction computation, can create a reasonably convincing water effect. This video, which I made a few years ago demonstrates this reasonably well.

---
Tags: terminology
---


# Question
Title: How can I implement world generation like in Don't Starve?
I am working on a game similar to Don’t Starve. Mechanics of the game are all also pretty similar. You craft things, you can explore a random open world and you need to survive. Because I really like the way Don’t Starve generates worlds with biomes, and this branch like structure:

I want my world generator to generate worlds similar to this on a large tilemap, with custom biomes, but I don’t think they use perlin noise for it. Here you can see different biome sections of the game:

Also I want to explore other possibilities than noise to generate worlds, so I don’t want to use it for this project.

# Answer
I'm gonna give another shout out to RRTs (rapidly exploring randomized trees). It looks to me that you could generate this terrain using an RRT in the following way:

1. Randomly sample a point in the play area and add it to a tree T. Assign it a random biome B.
2. Randomly sample another point in the play area called P2 and label it biome B2.
3. Find the closest point in the tree T to point P2, and call it Pt.
4. Grow a branch from Pt toward P2 a random length up to the distance between Pt and P2. At the end of this branch, add another node to the tree T called P3. Label P3 using the following rule: if it closer to P2, label it B2. Otherwise, label it whatever the biome was of Pt.
5. Repeat step 2 until some number of nodes is in the tree T.
6. Post process the tree to create the world. Create a grid of tiles that covers the same area that the tree covers plus or minus some margin.
7. For each grid cell, determine the closest node in T called Pt, with biome label Bt. The biome of the this grid cell is Bt. If you are above a certain distance from Pt, instead your biome will be ocean.

EDIT: Here is the output of this algorithm that I've sketched up in Python. I had to modify step 4 so that it only labels with Bt if Pt is ten times closer to the new node than the random sample. You can play with that parameter to get biomes of different sizes. Here is a gist of that algorithm.
> 4 votes

# Answer
You can achieve a very similar result by using voronoi diagrams:

You'll need to generate a set of points (one for each biome) with a seeded pseudo random generator (if you want the maps to be repeatable), then when you generate the tiles, get the distance between that tile and the points and set the biome of the tile to the one represented by the closest point.
> 9 votes

---
Tags: procedural-generation
---


# Question
Title: How can I make my button do something when clicked?
I'm trying to create a game with libGDX in Android Studio, and I am struggling with my code to add a command to the program to do something when I press the button.

I have added an `ImageButton`, but now I struggle to get it to do something when I click on it.

Here's my code:

```
 bplay.addListener( new ClickListener(){
        public void clicked(InputEvent event, float x, float y){
            batch.begin();
            batch.draw( splash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() );
            batch.end();
        }
    });

```

# Answer
You need to draw stuff in the rendering loop. Try doing the following:

```
// On the class level
boolean drawImage = false;

// When setting the listener
bplay.addListener( new ClickListener(){
    public void clicked(InputEvent event, float x, float y){
        drawImage = true;
    }
});

// In the render method
if (drawImage) {
    batch.begin();
    batch.draw( splash, 0, 0, Gdx.graphics.getWidth(),
    Gdx.graphics.getHeight() );
    batch.end();
    drawImage = false;
}

```
> 1 votes

---
Tags: libgdx, android-studio
---


title: Unity: Texture huge areas with decals

text:
# Question
Title: Unity: Texture huge areas with decals
I'm using 1024 textures for smaller buildings and 2048 for larger one's. Basic workflow:

1) Unwrap in Blender

2) Smack a concrete texture on it

3) paint some dirt here and there.

Result:

This only works for small buildings. Here is an example from Battlefield 2, they put a small 128x128 brick texture and tiled it across the entire building and added Dirt on top of that.

Is there a way to do this using Unity or do I have to create my own custom shaders? (God forbid)

# Answer
> 2 votes
Yes, this can be done with the **Unity Standard Shader**.

Check the section labelled "**Secondary Maps"** \- here you can specify an additional albedo (surface colouration) and normal (bump) texture to layer with the Main Maps above, at a different tiling frequency and offset. You can even specify a different UV set for these maps to use, if they need to wrap around your model differently than the main texture (eg. to preserve visual continuity at UV seams at a different scale)

Usually this is done at a higher tiling rate, to add detail maps that help hide texture interpolation when the camera gets very close to the surface. But you can also use a fractional tiling amount to add this larger-scale grime to break up surfaces from a distance.

---
Tags: unity, textures, blender, uv-mapping
---


title: Screen size independent movements

text:
# Question
Title: Screen size independent movements
I am developing a simple game for Android.

It is a really simple game, with only one object - a ball.

I am using the game loop based on delta time. However I have noticed that my game runs not in the same on different devices and I have realized that this may be caused by the following code

```
currentPosition.x+= velocityVector.x * deltaTime

```

As far as all dimensions are just simple pixels, as a result it runs slower on devices that have higher screen resolution as the ball should pass more distance with the same velocity vector.

So to conclude, could you please suggest any good algorithm or approach to implement independent movement of an object ?

Thanks.

# Answer
This is usually handled by decoupling the game's simulation space from the screen pixels.

Your game physics and logic then operate in a "world coordinate system" of arbitrarily-chosen measurement units (1 world unit = 1 tile width or 1 in-game meter are common choices) which represent the ground truth of what's happening in the game's universe.

Then displaying a view of this world on the player's screen becomes a matter of transforming from world coordinates to screen or pixel coordinates. Many such schemes are possible, depending on whether your game is top-down or side-scrolling, or some form of 2.5D / oblique / isometric perspective. What's great about this decoupling is that you can even support multiple display perspectives for different situations without re-implementing your game logic.

A simple display scheme is something like this:

```
Vector2 ToScreenPoint(Vector2 worldPoint) {

    // Adjust for your current "camera" viewpoint, if you have one.
    Vector2 relativeToView = worldPoint - currentView.worldspaceCenter;

    // Scale by a translation factor that maps some controllable number
    // of world-space units to always match the full height of the screen.
    Vector2 pixelOffset = relativeToView * Screen.pixelHeight / currentView.worldHeight;
    // (You could also choose to match the width instead, or some compromise formula)

    // Add (Screen.pixelWidth, Screen.pixelHeight)/2 to convert into a range
    // from 0 to the screen's extents. Now we have a pixel position.
    return pixelOffset + Screen.center;
}

```

Note that if your game uses pixel art or needs pixel-perfect display, then you may need to make additional changes to your world-to-screen scaling logic or visual asset selection to keep it looking crisp on different resolutions. Pixel art does not handle arbitrary scales cleanly.

(As an aside: I think this question has been asked and answered before, but the keywords show up in so many other questions that I haven't been able to find the match. Please feel free to suggest duplicates if you find one)
> 2 votes

---
Tags: java, physics, movement, game-loop
---


title: Quad sphere subdivision algorithm

text:
# Question
Title: Quad sphere subdivision algorithm
I like to generate some planets like Kerbal Space Program does. By some videos of the developers I know that they use a quadsphere, which consists of six “entities” as a minimum. These are all plane meshes, which get subdivided the closer you get. This allows a ground to orbit level of detail. However, I have some problems understanding this subdivision algorithm:

1. Since I have six separate meshes, how do I know where I have to subdivide them, if they are all separate?
2. If I always just subdivide the quad the camera is over and I end up with something like this:

even though I want something like:

.

So how can I ensure a sense full 2:1 subdivision with neighbour quads?

# Answer
Implementing LOD subdivision on terrain is quite complicated, I rather recommend to use a library or something. But if you prefer to learn the hard way here are the principal steps you need to do:

First, unlike your assumption, you do not start with 6 meshes like the most zoomed out version, but you define your geometry at highest resolution *(most zoomed in version)*. So if we assume you implement 4 levels (0: lowest, 3: highest) you start with a sphere consisting of 43 * 6 = 384 meshes that is the entire sphere at level 3. Then you need the meshes for the lower levels. There are 42 * 6 meshes for level 2, 41 * 6 for level 1 and 40 * 6 for level 0, the simple cube. That gives you in total 510 meshes for all levels.

At runtime, you just determine the distance of each of your 384 level 3 meshes to the camera *(you may check only a subset)*. If the distance is long enough you render it with a lower level *(notice that you always join 4 predefined higher meshes into one lower level mesh)*. That's a basic LOD implementation.

Once you have finished this, you'll notice that the meshes at the border from one level to another are not properly connected and expose artifacts *(graphical glitches)*. To solve that too, you need **stitching**. The real pain of this topic *(interestingly your sphere image does show stitching already)*. So for stitching, you need extra border meshes for each level and side and corner which gives you an additional 8 fold mesh count ⇒ ~4590 meshes in total.

Actually, it's better you do not use something like generic meshes but using directly OpenGL *(or whatever)*. Which gives you additional flexibility (maybe some of those mesh implementations offer it too). In OpenGL this would result in just 384 buffer objects (sort of mesh container) and ~28 index buffers (sort of mesh layouts) and those can be combined at runtime to all the necessary *'meshes'*.

As I said, it is rather an advanced topic, you'll better searching for a guide to follow, or if you lost your need for pain, take a library already implementing it.
> 2 votes

---
Tags: procedural-generation, procedural, sphere, quadtree
---


# Question
Title: Transform world space using Kinect FloorClipPlane to move origin to floor while keeping orientation
The Kinect SDK provides a property SkeletonFrame.FloorClipPlane that describes the orientation of the floor plane relative to the camera. MSDN contains slightly more information in the Coordinate Spaces page for Kinect.

I want to determine a matrix that transforms the camera coordinate space to a 'world space'. In this world space the origin would correspond be a projection of the camera position on the floor, ie straight below the camera.

* The X axis is to the sides of the camera, but rotated to be parallel to the floor, compensating for pitch
* The Y axis is straight up from the ground to the Kinect, compensating for yaw
* The Z axis is straight forward from the camera/origin, but rotated to be parallel to the floor, compensating for tilt

The 2 steps in the transformation would be

1. Translate from the camera position to the ground
2. Rotate around the origin while keeping orientation

Unfortunately my linear algebra is rusty and always has been.

Solution update:

I adapted the solution below to create the following method that creates a transformation matrix based on the floor normal and camera height:

```
Matrix CameraTransform(Vector3 normal, float scalar)
{
    // Note the first three coefficients of the plane equation are the normal
    Vector3 yNew = new Vector3(normal.X, normal.Y, normal.Z);
    Vector3 zNew = new Vector3(0, 1, -normal.Y / normal.Z);
    zNew.Normalize();
    Vector3 xNew = Vector3.Cross(yNew, zNew);

    // assumes column vectors, multiplied on the right
    Matrix rotMatrix = new Matrix(
        xNew.X, yNew.X, zNew.X, 0,
        xNew.Y, yNew.Y, zNew.Y, 0,
        xNew.Z, yNew.Z, zNew.Z, 0,
        0, 0, 0, 1);

    Matrix translationMatrix = Matrix.CreateTranslation(0, scalar, 0);

    return rotMatrix * translationMatrix;
}

```

# Answer
You're looking for a change of basis. The way to do it is to find the coordinates of the new basis in the old one.

For simplicity, we'll say that the `FloorClipPlane` represents the equation `Ax+By+Cz+D=0`

Let's do the rotation first, and then we can translate it to the floor.

1. We'll find the coordinate of the Y axis, which happens to be the normal of the floor plane.
2. In order to find the coordinate of the Z axis, we're looking for a unit vector in the line that represents the intersection of the floor plane (translated to the origin) and the x=0 plane; if the planes are `Ax+By+Cz=0` and `x=0`, the line will be `z=-B/C*y`. Fixing y to 1, we can then normalize.
3. Finally, the X axis is just the cross product of Y and Z (in that order, assuming a right-hand coordinate system).

Now, we'll translate the basis to the floor. The vertical distance is the fourth parameter of the floor plane equation. We'll have to use a 4x4 matrix to support translation, and we'll combine them so the rotation matrix is applied first, the translation second.

Let's see some pseudocode:

```
// Note the first three coefficients of the plane equation are the normal
yNew = vector(floorPlane.A, floorPlane.B, floorPlane.C);
zNew = vector(0, 1, -floorPlane.B/floorPlane.C);
zNew.Normalize();
xNew = CrossProduct(yNew, zNew);

// assumes column vectors, multiplied on the right

rotMatrix = matrix(xNew.x, xNew.y, xNew.z, 0,
                   yNew.x, yNew.y, yNew.z, 0,
                   zNew.x, zNew.y, zNew.z, 0,
                   0,      0,      0,      1);

translationMatrix = matrix(1, 0, 0, 0,
                           0, 1, 0, -floorPlane.D,
                           0, 0, 1, 0,
                           0, 0, 0, 1);

transform = translationMatrix * rotMatrix;

```

Hopefully it all makes sense. Unfortunately, I haven't been able to test this as I don't have a Kinect setup. Let me know if you have issues.
> 4 votes

# Answer
I have tried to implement what's described in Sergio's answer, in Matlab.

I wanted my `yNew` joint height to be the distance from the floor. But when I put `-floorPlaneD` in the translation matrix, I didn't obtain what I expected.

The solution for me was to put `+floorPlaneD` instead.
> 1 votes

---
Tags: transformation, kinect
---


# Question
Title: Loading texture from constructor doesn't work but does from function call
I am trying to load a SDL texture through my class's constructor. All I'm doing is calling a function from the constructor to load the texture. As mentioned in the title, this does not seem to work. However, if I call the function directly then it loads fine and I can see it on the screen. I'm fairly new to C++ so please let me know what I'm doing wrong.

**Game.h**

```
#include "Player.h"

class Game {
  private:
   Player player;

  public:
   Game();
   ~Game();

   void update();
   void draw();
}

```

**Game.cpp**

```
#include "Game.h"

Game::Game() {
  this->player = Player("somefile.png", 0, 0, 10, 10);  // Doesn't draw
  this->player.load("somefile.png", 0, 0, 10, 10) // Will draw
}

void Game::update() { /* ... */ }

void Game::draw() { /* ... */ }

```

**Player.h**

```
class Player {
  private:
    SDL_Texture* texture;
    SDL_Rect source, destination;

  public:
    Player();
    Player(const std::string& filepath, const int x, const int y, const int w, const int h);
    ~Player();

    void load(const std::string& filepath, const int x, const int y, const int w, const int h);

    void update();
    void draw();
  }

```

**Player.cpp**

```
#include "Player.h"

Player::Player() {}

Player::Player(const std::string& filepath, const int x, const int y, const int w, const int h) {
  this->load(filepath, x, y, w, h);
}

void Player::load(const std::string& filepath, const int x, const int y, const int w, const int h) {
  this->texture = SDL_CreateTextureFromSurface(renderer, IMG_Load(filepath.c_str());

  if (this->texture != nullptr) {
    this->source = { x, y, w, h};
    this->destination = { 0, 0, w, h};
  }
  else {
    std::cout << "Could not load image." << std::endl;
  }
}

void Player::update() { /* ... */ }

void Player::draw() { /* ... */ }

```

In `Game.cpp`, if I use the line with the constructor then nothing draws in the window. If I use the line that has `load()`, then it works fine. I never get the `Could not load image.` error in either cases.

# Answer
> 2 votes
It seems that you implemented `~Player()` to deallocate your texture.

Anyway, it is rather bad style to copy objects which contain free able resources like here:

```
this->player = Player("somefile.png", 0, 0, 10, 10);

```

What here happens is:

* A new temporary `Player` object is constructed with given parameters. Here the constructor calls `Player::load(...)`
* The object is binary copied (field by field) into `this->player` *(notice that the texture pointer value is copied, no new texture is created)*
* The destructor `~Player()` is called on the temporary (presumably deallocating the texture)

**To fix this you have a few options:**

You could use generally just the `Player::load(...)` function for the image loading. And never do a create-copy assignment as above.

Or using the right constructor when you actually construct it:

```
class Game {
  Player player("somefile.png", 0, 0, 10, 10);
  ...
}

```

Or if you need arguments using the initializer list:

```
Game::Game(const std::string& filepath) : player(filepath, 0, 0, 10, 10) {

}

```

Here in both snippets is no temporary object involved which would cause an unwanted destructor call.

Alternatively if you have at least C++11 support, using move semantics. But like *Quentin* pointed out, you have to implement the move constructor yourself. It might be easier to just disable the copy-constructor.

The difference with *move semantics* is that the temporary object and `this->player` would be swapped so the destructor is called on the old swapped out content.

BTW since C++11 you could also disable the copy semantics on a class which should not be copyable: *(Quentin noted that in C++03 you might also just declare the copy-constructor private)*

```
class Player {
  Player(const Player&) = delete;
  Player& operator=(const Player&) = delete;
  ...
}

```

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


# Question
Title: How to Send Voice over Unity Networking - UNET
I am able to **Record and Run Audio** from my **Microphone** using this code snippet:

```
  void OnGUI() {
        if (GUI.Button(new Rect(0, 0, 100, 20), "record")) {
           // Microphone.End(Microphone.devices[0]);
            audsourceAttached.clip = Microphone.Start(Microphone.devices[0], false, 3, 44100);
        }
        if (GUI.Button(new Rect(0, 30, 100, 20), "Stop"))
        {
            //Microphone.End(Microphone.devices[0]);
            audsourceAttached.Play();
        }
    }

```

Now I am willing to **send this audio across Network** (on my local network-another instance of the game). How can I do this?

I tried to find this on google but unable to find any useful solution/links.

**How can I send audio through microphone like real-time Chat in a game/etc.**

# Answer
> 7 votes
TL;DR: You can't do it natively in Unity

`Microphone.Start` returns an `AudioClip` which has 3 load types, none of which fit your use case. All of them (even the `.Streaming` one) require the entire clip to be on the users computer already. Using `AudioClip.GetData()` and sending a file over the network (in Unity, using `Networking.NetworkTransport.Send()`) would be horribly unresponsive and can only actually occur after the recording finishes its clip. This ignores audio codecs, using multiple threads (Unity isn't thread safe), and dealing with the real time nature of audio device data.

What you need is a way to get the audio device data in real time which Unity provides no mechanism for and therefore cannot support RTC natively. This answer comes to the same conclusion

Third party solutions exist on the asset store. Here's one such solution mentioned in the above linked answer: Dissonance Voice Chat. Going through the files list it uses a native .dll, the Opus audio codec, and a bunch of C# files for interfacing with the native code.

Rolling your own, which I do not recommend, would require doing the following:

* Using a separate C# `System.Threading` thread to process your audio so that your framerate and audio playback aren't coupled together.
* Getting the audio data isn't trivial in C#. .NET uses `DirectSound` which is a Windows things. Mono doesn't support this. This means you either need to implement a cross platform solution yourself natively, or rely on a library that already does.
* Transporting it over the network requires a socket using .NET sockets. These seem robust and are supported in Mono.
* Your sockets should transport as a P2P multicast. This allows you to send one audio stream to multiple people all at once. It also skips a setup like `Client ==> Server ==> Client` which adds extra latency.
* You would also want a codec to make sure that you're not just sending uncompressed audio willy-nilly. There are many out there which most likely requires interfacing with another native library.

---
Tags: unity, c#, multiplayer, unet, voice
---


# Question
Title: Zooming in so a smaller portion of the game scene fills the entire screen
so i am creating a game similar to super-smash-bros, in which the camera should zoom in on players when they are close together, and scale back when they are apart. I create a window for my game via

```
m_pWindow = SDL_CreateWindow("First SDL game attempt", SDL_WINDOWPOS_UNDEFINED,
                SDL_WINDOWPOS_UNDEFINED, 1000, 1000, SDL_WINDOW_SHOWN);

```

and then initialise my render via

```
m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, SDL_RENDERER_ACCELERATED);

```

and when i call render for my buffer, it simply calls

```
SDL_SetRenderDrawColor(m_pRenderer, m_clearRed, m_clearGreen, m_clearBlue, 0xff);
SDL_RenderClear(m_pRenderer);
SDL_RenderPresent(m_pRenderer);

```

Now i am wondering where in this solution should i implement the camera, if you could point me in the right direction that would be great. For example, i have a player positioned at `{500, 800}`, and another at `{300,800}`. I want to zoom in on this point of the screen. The total window is 1000x1000, but rendering `{x = 200->600, y = 600->1000}` is what i want to achieve.

I have currently tried using

```
SDL_Rect rect;
rect.x = 0;
rect.y = 0;
rect.w = 900; //TEST VALUES
rect.h = 900; //TEST VALUES
SDL_RenderSetViewport(m_pRenderer,
    &rect);

```

But this simply doesn't render part of the screen, as opposed to scaling the entire view.

Any other help would be greatly appreciated

# Answer
> 1 votes
As it seems there is no thing like a camera in SDL you have to implement that by yourself. The call you found `SDL_RenderSetViewport(...)` is indeed for a very different purpose, it adjusts the size (and offset) of the area within your window to draw to. That is useful e.g. if the window is resized.

Where to implement the camera is rather simple, you just need to calculate the bounding box of the locations of your players and take its center and size for your rendering. This center (translation) and size (scale) are what defines a camera in 2D *(actually there could be also rotation but that's it)*.

How to apply is rather difficult, since (AFAIK) there is no pendant in SDL for it. You have to do it explicitly on your one. You should never change the actual position of your players, instead you have to calculate a *on screen* position for every render cycle (frame). One example for this can be found here.

If you want to do this more efficiently on the GPU, you could use OpenGL see here *(Notice this is about legacy OpenGL)*. You could also use modern (core profile) OpenGL, but I think that this is rather a bit too hard for a simple 2D game.

---
Tags: c++, graphics-programming, sdl2
---


title: undetected colission

text:
# Question
Title: undetected colission
I'm doing a simple grid based game, where the player should only be able to move on the grey cells. It works quite ok, but in this simple scenario, the player is able to walk through Wall(1), although there is a collider on it and I'm checking with a raycast before moving. When removing the (nonblocking) pickup, the collider works. I'm assuming, the raycast is hitting the collider of the pickup, when the player is on that position and therefor misses the collision with the wall. What is a good practice to handle this issue?

# Answer
> 0 votes
The best way is probably to or use different layers to differentiate between collectibles and obstacles. In the raycast function you can use the layerMask parameter to include only the layers you want to check.

An alternative is to use RaycastAll to get a list of collisions to check for your obstacles.

---
Tags: unity, raycasting, grid, collider
---


# Question
Title: creating a trigger to play multiple animations at once
I need a "button" like trigger. The player would walk within the invisible cube that is the trigger, once the player is in the trigger (and only in the trigger) they would be able to press 'e' on their keyboard which will cause the animations to play at once. After the animation plays, the screen fades to black and loads the next scene.

I'm still incredibly new to Unity so a brief summary of the code you provide would be much appreciated! (but not at all demanded!)

Personally I'm a lot more comfortable with C# so if the code can be in that, it would really help. Thank you!

# Answer
For the inside trigger and only trigger and nothing but the trigger part you can use `OnTriggerStay(Collider)` function which is a built-in MonoBehaviour Message handler, and inside this handler check if the player presses the "E" key.

To check if the trigger you're staying in is the one you want, you can give the trigger a tag (or put it on a specific layer, or attach a specific "Activation" component, etc.)

```
void OnTriggerStay(Collision col)
{
    if(Input.GetKeyDown(KeyCode.E) && col.gameObject.CompareTag("SomeTag"))
    {
        Animator anim = this.gameObject.GetComponent<Animator>();
        anim.Play("SomeAnim");
        DoFade();
    }
}

```
> 1 votes

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


title: Creating a random lottery system

text:
# Question
Title: Creating a random lottery system
I would like the game to give all 16 characters (15 NPC + 1 player) a number: 1-16. This number stays the same no matter what and is unique only to that character so two characters cannot have the same number. At a point in the game, the character presses a button.

I need this button to generate a random number and load a scene based on the number. Example: Player's pre-determined number is "8", if the number generator generates an "8" as well, it would load the next scene (where the player has to run away from a mob) If the generator generates anything else other than "8" It will load a different scene (where the player chases an NPC)

Just to clear it up if the number generator generates 1-7 or 9-16 it will load the same scene no matter what. (Getting "9" from the generator would load the same scene as "2" would. Only when "8" is generated, would there be a separate scene)

I'm still incredibly new to Unity and coding in general, so a brief summary of what each line of code is doing would be majorly appreciated! (but not at all demanded!)

I'm most comfortable with C# so if you could have the code in that would be great!

# Answer
> 1 votes
First I will suggest that you google specific things before you ask questions. Such as for the random number you could google "unity random int" or "c# random int". https://docs.unity3d.com/ScriptReference/Random.Range.html https://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c

Either way you could do this by having an object with a scrip that gives numbers to your characters. You could either find the characters in your script or add them to your number giver object. Let's assume the latter.

```
// Lists are like arrays but has an Add
public GameObject[] characters;
// Lists are like arrays but has an Add function (worth a google)
private List<int> usedNumbers;

void Start() {
    // Random number from 1 to the amount of characters in the array
    int randomNumber = Random.Range(1, characters.Length);
    // Loop that takes every single object in the characters array
    foreach (GameObject character in characters) {
        // Loop until we have a random number that isn't in usedNumbers
        while (usedNumbers.Contains(randomNumber) {
            randomNumber = Random.Range(1, characters.Length);
        }
        // Add the unique random number to usedNumbers list
        usedNumbers.Add(randomNumber);
        // Give number to your character (CharacterController can simply be a script with a public int)
        character.GetComponent<CharacterController>().number = randomNumber;
    }
}

```

That script can do the job but I haven't tested it myself as I can't right now.

It will do the job but I'd still advice googling for a method on how to exclude numbers from your random number generation as simply **looping until you find a new number isn't a good way of doing it.**

Maybe have a look at this: http://answers.unity3d.com/questions/452983/how-to-exclude-int-values-from-randomrange.html

I'd assume if you use the method which is shown in the link you should get rid of the while loop and simply write code that says "don't use usedNumbers"

---
Tags: unity, c#, random, content-generation
---


title: Shaders vs renderers: Photorealism

text:
# Question
Title: Shaders vs renderers: Photorealism
What is Renderer? How it is different from a shader?

For Photorealism which one is more important?

# Answer
> 1 votes
Shaders and renderers are two different things. A renderer is simply a piece of code written on top of a rendering API (such as OpenGL or DirectX) and it handles the model rendering (hence the name).

A shader is also a piece of code, but it runs on the GPU. It's optimized to work on hundreds of threads at once and it's usually used to figure out the position of a vertex (a point of a 3d model) relative to the camera (vertex shader) or to figure out the color of a certain pixel (fragment shader).

Your third question makes no sense currently. None of them are required to achieve photorealism. You can make photorealistic images with just shaders (like here) and you can also achieve it without using a shader, in fact, ray tracing is the current standard in movie making and it doesn't have to involve the usage of shaders.

---
Tags: shaders, rendering, terminology
---


# Question
Title: How to render a model that consists of individually transformable parts?
Consider a 3D model for a spider that consists of a body and eight legs. The legs can be transformed (rotated) relative to the body. I am not sure what the common ways of rendering such a scene are, at a low level. Two ways I could think of:

1. Render the body and legs separately, using different VBOs (or different indices) (one for the body, one for the leg) and separate draw calls.
2. Encode in each vertex which body part it belongs to, and decide based on this information how to transform the vertex in the vertex shader.

I searched a bit and could find some tutorials on skeletal animation and similar techniques, but they still boil down to this question.

# Answer
> 0 votes
Your second guess is almost correct. Skeletal based animation usually uses a weight map to bind certain vertices to certain bones (a single vertex can have multiple parent bones, there's usually an upper limit though). Then a vertex shader is used to move the vertices based on their parent bones.

Basically, the files include the skinning values for the separate bones, you process them and send them to the shader somehow. I've seen people using a vec4 and 4 matrices to store the transformations to do this, which limited the weights per vertex to 4 (you usually don't have much more), but it's up to the programmer to decide how he does it.

You can still do the same if you don't want to use this for animation, but instead of using bones, just use a pseudo element with a position and an id

# Answer
> 0 votes
I think skeletal animation is only really possible if you have the bones set up and have the animation frames available. If you have all of that, the skeletal is the way to follow.

If you do not, then I would go forward with your first option, but set it up as a scene graph, to learn about scene graphs I would take a look at this info on scene graphs

---
Tags: opengl, glsl, graphics-programming
---


# Question
Title: Processing large multi layered images with SharpDX
I'm currently working on an image processing project that pans and zooms on multi-layer high resolution images.

The goal is colorize (including color, gain and noise) `n` layers (`n` having a minimum of 5) and merge them via shaders. On top of that, there are 5–6 layers of 2D geometry each colored and merged as well.

The normal image size is 7440 x 7440.

These are then merged and rendered on a single Quad. I've been able to get this working very well and the results are good.

This is being processed on a Xeon based workstation with a M4000 Nvidia Quadro or a Xeon based Lenovo p51 with M2200 Nvidia Quadro.

The issue comes when I need to process a very large image (34,992 x 34,992) that requires splitting the image over 9 quads on the same systems.

These images must go through the same process of colorization and merging. The images are 11,664 x 11,664 per quad.

When zoomed in, we are still processing areas we can't see—can I apply some form of frustum culling here?

And, when zoomed out, is there a way to process a lower resolution image so the GPU is not pegged and none responsive?

# Answer
Instead of merging everything into a large temporary texture if you render all the temporaries and 2D mesh to a frame buffer the same size and render-offset as your final window the GPU would be culling all the unseen pixels on its own.

But I recommend switching to **OpenCL**. You can better split down the tasks into smaller GPU commands (kernel executions) and then add artificial software-controlled delays to let the GPU do other work by using `clFinish` and putting your thread to sleep for a hundred milliseconds or so before issuing more commands to the queue. This would give the rest of the system a chance to access the GPU.

You can fine-tune this by profiling the time those OpenCL kernel executions take on a particular system to balance the pause and execution queue length.

But with OpenCL you will need to calculate the frustum culling yourself from the zoom factor and scrolling offset.

With the `cl_khr_gl_sharing` extension or `cl_khr_dx9_media_sharing`, `cl_khr_d3d10_sharing`, or `cl_khr_d3d11_sharing` you can put the result directly into a GPU texture without doing a round-trip over the PCIe bus, leaving everything in GPU RAM.

With this more complex system you can even use OpenCL to calculate into one texture (or set of smaller tile textures) while the GPU is also drawing using another previous result texture-set during the software-controlled OpenCL pauses making the app feel more responsive.

As an extra step, you can watch for mouse movements and app focus to dynamically re-tune the pause/work ratio for maximum performance or improved responsiveness.

A side-effect of using OpenCL is that GPU drivers are more likely to be tuned to give priority to render commands (OpenGL or DirectX) than OpenCL commands. Using draw calls to do your processing puts those commands on the same priority (user-responsiveness) as other graphic draw calls. It is not guaranteed but using OpenCL can help the GPU drivers maintain system responsiveness.
> 1 votes

---
Tags: c#, directx, hlsl, image, sharpdx
---


# Question
Title: How to calculate all points in a 2D grid defined by an arc, given a starting point and range
I've an unit in a 2d (integer) grid-based game, which has a bearing. Now I want to display an arc, with a given radius (for instance simulating a 90 degree cone of a sensor with respect to the bearing of the unit, attaching this sensor).

How can I efficently get all points in the 2d grid to draw that 'cone' arc ?

This question actually is about a similar issue but in contrast I want to get all points and not only check if a given point is located in that sector.

# Answer
> 2 votes
To get every point, loop through the points between `(px - r; py - r)` and `(px + r; py + r)` where px and py are the player's x and y coordinates and r is the radius of the circle. For each point, do the following:

1. Given the point `(x; y)` calculate the distance of this point and the player's position (`d = √((x - px)^2 + (y - py)^2)`). Save this somewhere because you'll need it.
2. If `d` is less than or equal to the radius of the circle, then this point is inside the main circle and you can continue. Otherwise just go to the next point.
3. Normalize the vector pointing from the player position to the current point using the distance you calculated earlier. The new vector should be `((x - px) / d, (y - py) / d)`. Then get the dot product of this vector and `(1, 0)` to get the cosine of the angle between the (It'll be `(x - px) / d` if you did everything correctly).
4. The point is inside the cone if the arccosine of the value you get after the dot product is between the angles.

In pseudo code:

```
getPoint(px, py, angle1, angle2, r) do
    output = empty set

    for each x between px - r and px + r) do
        for each y between py - r and py + r) do
            d = sqrt((px - x)^2 + (py - y)^2)
            if d > r then
                continue
            end

            d = acos((x - px) / d)
            if d >= angle1 and d <= angle2 then
                add (x, y) to output
            end
        end
    end
    return output
end

```

# Answer
> 2 votes
If you think of your grid as pixels in an image/raster display, you could use the midpoint circle algorithm for rasterizing circles.

Wikipedia's page for the algorithm has a section on drawing incomplete octants that could do the job.

---
Tags: 2d, mathematics, grid
---


# Question
Title: Drawing a grid over a terrain using a mesh - Shader Depth and Z-Buffer
What I'm trying to achieve is rendering a (huge) tile grid over a terrain. For that I'm using a generated mesh of quads, one for every tile, whose vertices Y value is the same of the terrain to "shape" this mesh like the terrain.

My problem is that this mesh should be rendered always over the terrain, keeping every other object rendered on top of this grid. As you should guess I'm a beginner in shader programming. So here are some caps:

Rendering the mesh with simple **unlit transparent shader** (with ZTest, ZWrite and Cull values):

As you can see there are problems with the z-fighting, when the grid should always be drawn on top. Rising the terrain won't solve it, since the terrain have lots of "peaks" and the quads should be planes with lots of vertex to be able to follow the terrain (or rising a lot the grid which will cause it to float over the terrain).

Changing the **ZTest to Always**:

Here I've the problem that the tiles behind the mountains are still drawn when they shouldn't, which make sense since it's ignoring z-ordering, and therefore rendering over other objects too.

I've tried using a another shader pass to first write to the z buffer to avoid rendering the tiles behind the mountains with no success. I guess I'm missing something related to the terrain shader, but I have no clue what it may be.

Any help will be much appreciated.

# Answer
You can use a pixel shader for this.

Pass the size of a single grid square and the radius of a circle to the shader, divide it by the gridSize, round it then multiply by gridSize to get the closest grid point. If the distance between the current fragment and the closest point is less than or equal to the radius, then it's inside the circle:

```
gX = round(fragX / gridSize) * gridSize
gY = round(fragY / gridSize) * gridSize
d = sqrt((x - gX)^2 + (y - gY)^2)
if (d <= radius)
    color = (0, 1, 0, 1) // green

```

No postprocessing or addional rendering needed
> 1 votes

---
Tags: unity, shaders, terrain, grid, depth-buffer
---


title: Character on platform move slowly

text:
# Question
Title: Character on platform move slowly
I'm having a problem similar to this link: http://answers.unity3d.com/questions/1295955/character-on-a-moving-platform-slows-down.html

But...

My 2D character is on an elevator (which does not have any physics) and is being moved up and down through an animation (transform). But when my character is on the elevator, the colliders2D overlaps another, as my character's RigidBody2D stands still as I move the game object elevator (crossing each other). My solution was to try to attach my character as the child of the elevator (SetParent), and this solved the problem of overcoming the colliders, but it gave me a new problem.

The new problem consists of a certain slowness in the movement of the character while it is on the elevator. I believe the problem is because the transform of my character is in motion while the elevator goes up and my rigidbody don't add any force.

Do I need move the elevator with physics to stay movent? Or am I thinking the wrong way?" How to solve this problem? See the player movement script:

```
 using UnityEngine;
 using System.Collections;

 public class Move : MonoBehaviour {

     public float speed;
     public float jump;
     public GameObject rayOrigin;
     public float rayCheckDistance;
     Rigidbody2D rb;

     void Start () {
         rb = GetComponent <Rigidbody2D> ();
     }

     void FixedUpdate () {
         float x = Input.GetAxis ("Horizontal");
         if (Input.GetAxis ("Jump") > 0) {
             RaycastHit2D hit = Physics2D.Raycast(rayOrigin.transform.position, Vector2.down, rayCheckDistance);
             if (hit.collider != null) {
                 rb.AddForce (Vector2.up * jump, ForceMode2D.Impulse);
             }
         }
         rb.velocity = new Vector3 (x * speed, rb.velocity.y, 0);

     }
 }

```

# Answer
Instead of adding the character as a child of the lift it would be better to get the lift to push the player up with rigidbody and add force. The animation of the lift will update on update but all other physics will work on the fixedupdate.
> 1 votes

---
Tags: unity, collision-detection, rigidbody
---


# Question
Title: Adjusting arms of character while moving
I'm working on a test game in Cocos2d for Python (code is a little dirty). I'm trying to run and shoot at the same time without having my character's (running) legs go back to the beginning position every time I fire. So as it runs it will have freedom to shoot.

The code uses a custom action class (PlatformerController) that's implemented on a sprite, which is placed on its own layer. There are three sprites that represent the character: its running arms and the body.

The code checks if the player is running. If it is, then it removes the player's running arms, and replaces them with its shooting arms. This works fine if I replace the running body as well, but if I just remove the arms and replace them while keeping the running body, the arms are added right behind the body. Maybe someone has a better suggestion on doing this?

What I've tried:

* using a separate platformer controller for the arms
* aligning each arm sprite with the character's body rect
* using the same .position of the body on the arms
* using the built-in moving (interval action, different than the custom action class) classes

Here is the full code (it should be noted that I added the "tag" parameter to sprite):

```
import pyglet
from pyglet.window import key
from pyglet.image import load_animation

import cocos
from cocos import layer, mapcolliders, actions, tiles, sprite, scene

from cocos.director import director
import cocos.euclid as eu
import cocos.collision_model as cm

class evaHero(layer.ScrollableLayer):

    def __init__(self):

        super(evaHero, self).__init__()
        theAnim = load_animation("evaStanceArmless.gif")
        self.sprite = sprite.Sprite(theAnim)
        self.sprite.tag = 5
        self.add(self.sprite,z=2)
        self.sprite.do(PlatformerController())
        self.spriteLeftArm = sprite.Sprite(load_animation("evaLeftArm.gif"))
        self.spriteRightArm = sprite.Sprite(load_animation("evaRightArm.gif"))
        self.add(self.spriteLeftArm,z=1)
        self.add(self.spriteRightArm,z=3)
        self.spriteLeftArm.do(PlatformerController())
        self.spriteRightArm.do(PlatformerController())
        # self.shot = sprite.Sprite("pulseShot.png")
        # return is done automatically when you init

    def evaStance(self,mapCollider, collideTiles, is_left, is_shooting):

        if is_left:
            if is_shooting:
                anim = load_animation("evaStanceArmless.gif")
                animL = load_animation("shootRunLeftArm.gif")
                animR = load_animation("shootRunRightArm.gif")
            else:
                anim = load_animation("evaStanceArmless.gif")
                animL = load_animation("evaLeftArm.gif")
                animR = load_animation("evaRightArm.gif")
        else:
            if is_shooting:
                anim = load_animation("evaStanceArmless.gif")
                animL = load_animation("shootRunLeftArm.gif")
                animR = load_animation("shootRunRightArm.gif")
            else:
                anim = load_animation("evaStanceArmless.gif")
                animL = load_animation("evaLeftArm.gif")
                animR = load_animation("evaRightArm.gif")

        tempSprite = sprite.Sprite(anim)
        tempArmLeft = sprite.Sprite(animL)
        tempArmRight = sprite.Sprite(animR)
        for x in [tempArmLeft, tempSprite, tempArmRight]:
            x.position = self.sprite.x, self.sprite.y
            if x == tempSprite:
                x.do(PlatformerController())
                self.sprite = tempSprite
            else:
                x.do(PlatformerController())
            x.collision_handler = mapcolliders.make_collision_handler(mapCollider, collideTiles)
        self.spriteLeftArm = tempArmLeft
        self.spriteRightArm = tempArmRight

        for x in self.children:
            if x[1].tag == 1 or x[1].tag == 2: # does not remove shots
                pass
            else:
                self.remove(x[1])

        zPos = 1
        for x in [tempArmLeft, tempSprite, tempArmRight]:
            self.add(x,z=zPos)
            zPos += 1

    def evaRun(self,mapCollider,collideTiles,is_left,is_shooting):

        if is_shooting:

            if is_left:
                # runSprite = sprite.Sprite(load_animation("runLeft.gif"))
                leftArmRun = sprite.Sprite(load_animation("shootRunLeftArm.gif"))
                rightArmRun = sprite.Sprite(load_animation("shootRunRightArm.gif"))
            else:
                # runSprite = sprite.Sprite(load_animation("evaRun.gif"))
                leftArmRun = sprite.Sprite(load_animation("shootRunLeftArm.gif"))
                rightArmRun = sprite.Sprite(load_animation("shootRunRightArm.gif"))

                # if x == runSprite:
                #     x.do(PlatformerController())
                # else:
            for x in self.children:
                if x[1].tag == 1 or x[1].tag == 2 or x[1].tag == 5:
                    pass
                else:
                    self.remove(x[1])

            # self.sprite = runSprite
            self.spriteLeftArm = leftArmRun
            self.spriteRightArm = rightArmRun
            self.sprite.stop()
            self.sprite.do(PlatformerController())
            for x in [self.spriteLeftArm,self.spriteRightArm]:
                x.collision_handler = \
                    mapcolliders.make_collision_handler(mapCollider, collideTiles)
                x.position = self.sprite.position
                x.do(PlatformerController())

            zPositions = 0
            for y in [self.spriteLeftArm, self.spriteRightArm]:
                self.add(y,z=zPositions)
                zPositions += 2

        else:

            if is_left:
                runSprite = sprite.Sprite(load_animation("runLeft.gif"))
                leftArmRun = sprite.Sprite(load_animation("runLeftArmL.gif"))
                rightArmRun = sprite.Sprite(load_animation("runRightArmL.gif"))
            else:
                runSprite = sprite.Sprite(load_animation("evaRun.gif"))
                leftArmRun = sprite.Sprite(load_animation("runLeftArm.gif"))
                rightArmRun = sprite.Sprite(load_animation("runRightArm.gif"))

            for x in [leftArmRun,runSprite,rightArmRun]:
                x.position = self.sprite.position
                if x == runSprite:
                    x.tag = 5
                    x.do(PlatformerController())
                else:
                    x.do(PlatformerController())
                x.collision_handler = \
                    mapcolliders.make_collision_handler(mapCollider, collideTiles)

            self.sprite = runSprite
            self.spriteLeftArm = leftArmRun
            self.spriteRightArm = rightArmRun
            for x in self.children:
                if x[1].tag == 1 or x[1].tag == 2:
                    pass
                else:
                    self.remove(x[1])

            zPositions = 0
            for y in [leftArmRun, runSprite, rightArmRun]:
                self.add(y,z=zPositions)
                zPositions += 1

class PlatformerController(actions.Action):

    on_ground = True
    is_running = False
    is_left = False
    MOVE_SPEED = 300
    JUMP_SPEED = 400
    GRAVITY = -1200
    deltaTime = 0.0

    def start(self): #actions don't need __init__
        self.target.velocity = (0,0)
        #no need for target.gravity because the "walls" layer stops the sprite

    def step(self, dt):
        global keyboard, scroller
        if dt > 0.1:
            return #if dt is too big, collision will suffer
        self.deltaTime = dt
        # print("before ",self.target.x, self.target.y)
        # print("target: ",self.target.tag, " velocity: ",self.target.velocity, dt)
        vx, vy = self.target.velocity

        #update velocity
        vx = (keyboard[key.RIGHT] - keyboard[key.LEFT]) * self.MOVE_SPEED
        vy += self.GRAVITY * self.deltaTime

        if self.on_ground and keyboard[key.SPACE]:
            vy = self.JUMP_SPEED

        #with updated velocity calculate (tentative) displacement
        dx = vx * self.deltaTime
        dy = vy * self.deltaTime

        #player's current bounding rectangle
        last = self.target.get_rect()

        #build the tentative displaced rect
        new = last.copy()
        new.x += dx
        new.y += dy

        #account for hitting obstacles, it will adjust to new vx, vy
        self.target.velocity = self.target.collision_handler(last, new, vx, vy)

        #update on_ground status
        self.on_ground = (new.y == last.y) #gives you False

        #update player position; player position is anchored to the center of the image rect
        self.target.position = new.center
        #move the scrolling view to center on the player
        if self.target.tag == 5:
            scroller.set_focus(*new.center)

class GameScene(layer.ColorLayer):

    is_event_handler = True

    def __init__(self):

        super(GameScene, self).__init__(102, 102, 255, 255)
        # create a layer to put the player in
        self.player_layer = evaHero()
        self.is_run_and_gun = False
        self.mapcollider = mapcolliders.RectMapCollider
        self.colliderList = set()

        if __name__ == '__main__':
            self.main()

    def main(self): #did move to view
        global keyboard, tilemap, scroller, fullmap
        self.schedule(self.update)

        # NOTE: the anchor for this sprite is in the CENTER (the cocos default)
        # which means all positioning must be done using the center of its rect

        #add the tilemaps and the player sprite layer to a scrolling manager
        scroller = layer.ScrollingManager()
        print("loading tiles")
        fullmap = tiles.load_tmx("firstLevel.tmx")
        self.tilemap_walls = fullmap["walls"]
        scroller.add(self.tilemap_walls,z=2)
        tilemap_decoration = fullmap["decoration"]#this is the tmx object layer
        scroller.add(tilemap_decoration,z=0)

        self.tilemap_other = fullmap["other"]#this is the trees, grass, sky, and clouds
        scroller.add(self.tilemap_other,z=1)

        scroller.add(self.player_layer,z=3)

        #baddie
        self.baddie = sprite.Sprite(load_animation("redPUThingy.gif"))
        self.baddie.tag = 2
        self.player_layer.add(self.baddie)

        #set the player start using the player_start token from the map
        start = tilemap_decoration.objects[0]
        start2 = tilemap_decoration.find_cells(player_start=True)

        baddieRect = self.baddie.get_rect()
        baddieRect.midbottom = start.midbottom
        self.baddie.position = baddieRect.center
        self.baddie.x *= 8
        self.baddie.cshape = cm.CircleShape(eu.Vector2(self.baddie.x,self.baddie.y),
                                            32)

        self.colliderList.add(self.baddie)
        self.collman = cm.CollisionManagerGrid(0,self.tilemap_other.px_width,
                                               0,self.tilemap_other.px_height,32,32)

        print("start: ", start.midbottom)
        print("start2: ", start2)

        r = self.player_layer.sprite.get_rect()

        #align the midbottom of the player rect to the mid bottom of the start cell
        r.midbottom = start.midbottom

        # player image anchor (position) is in the center of the sprite
        self.player_layer.sprite.position = r.center
        self.player_layer.spriteLeftArm.position = r.center
        self.player_layer.spriteRightArm.position = r.center

        #give a collision handler to the player
        self.mapcollider = mapcolliders.RectMapCollider(velocity_on_bump="slide")
        self.player_layer.sprite.collision_handler = \
            mapcolliders.make_collision_handler(self.mapcollider, self.tilemap_walls)
        self.player_layer.spriteLeftArm.collision_handler = \
            mapcolliders.make_collision_handler(self.mapcollider, self.tilemap_walls)
        self.player_layer.spriteRightArm.collision_handler = \
            mapcolliders.make_collision_handler(self.mapcollider, self.tilemap_walls)

        #construct the scene with a background layer color and scrolling layers
        self.add(scroller)

        #track keyboard presses
        keyboard = key.KeyStateHandler()
        director.window.push_handlers(keyboard)

        def on_key_press(key, modifier):
            if key == pyglet.window.key.D:
                print("debug walls!")
                self.tilemap_walls.set_debug(True)
            if key == pyglet.window.key.LEFT:
                print("left")
                self.is_run_and_gun = True
                self.player_layer.evaRun(self.mapcollider,self.tilemap_walls,True,False)
            elif key == pyglet.window.key.RIGHT:
                print("right")
                self.is_run_and_gun = True
                self.player_layer.evaRun(self.mapcollider, self.tilemap_walls,False,False)
            elif key == pyglet.window.key.A:
                print("fire!!")
                if self.is_run_and_gun == True:
                    print("run shoot")
                    self.player_layer.evaRun(self.mapcollider, self.tilemap_walls, False, True)
                    shot = sprite.Sprite("pulseShot.png")
                    shot.tag = 1
                    shot.position = self.player_layer.spriteLeftArm.get_rect().midright
                    shot.velocity = 800, 0
                    shot.cshape = cm.CircleShape(eu.Vector2(shot.x,shot.y),12)
                    self.colliderList.add(shot)
                    shot.do(actions.Move())
                    self.player_layer.add(shot, z=0)
                elif self.is_run_and_gun == False:
                    print("stand shoot")
                    self.player_layer.evaStance(self.mapcollider, self.tilemap_walls, False, True)

                if PlatformerController.on_ground == True:
                    #: stops from having player jumping higher and higher
                    PlatformerController.on_ground = False

        def on_key_release(key, modifier):

            if key == pyglet.window.key.LEFT:
                print("release left")
                self.player_layer.evaStance(self.mapcollider, self.tilemap_walls,True,False)
                self.is_run_and_gun = False
            elif key == pyglet.window.key.RIGHT:
                print("release right")
                self.player_layer.evaStance(self.mapcollider, self.tilemap_walls,False,False)
                self.is_run_and_gun = False
            elif key == pyglet.window.key.A:
                print("stuff")

        director.window.push_handlers(on_key_press, on_key_release)

    def update(self,dt):
        self.colliderList.clear()
        for x in self.player_layer.children:

            if x[1].tag == 1: #: remove shot if x passes beyond bounds
                x[1].cshape.center = x[1].position #update shot position
                if x[1].x > (self.player_layer.sprite.x + self.width) or x[1].x < 0:
                    print("removed!")
                    self.player_layer.remove(x[1])

            if x[1].tag == 1 or x[1].tag == 2:
                self.colliderList.add(x[1])

        self.collman.clear()
        # numCheck = 0

        for x in self.colliderList:
            # numCheck += 1
            # print(numCheck)#this shows that it's the moment I intro the shot that causes the error
            self.collman.add(x)
        try:
            for shot, badguy in self.collman.iter_all_collisions():
                print("hit")
                self.player_layer.remove(badguy)
                self.player_layer.remove(shot)
        except TypeError:
            print("no overlap")

if __name__ == "__main__":

    director.init(width=800, height=600, autoscale=False, resizable=True)
    director.run(scene.Scene(GameScene()))

```

# Answer
> 1 votes
I was able to get what I was asking for by copying the sprite, then removing it and adding it back. I also made sure to not "add" another action on top on top of the copied sprite, as Cocos2d keeps the action on the copied sprite.

---
Tags: animation, movement, python, cocos2d, pyglet
---


title: Game compression?

text:
# Question
Title: Game compression?
I want to know the right and good way to compress my game when I build it. I made 3 levels with all my enemies there. The size of the game file 3GB in the desktop. When I build my game I get 1GB. All textures quality 1024\*1024. But in unity I get 2048 on the settings window? do I need to change anything?

Is there any thing wrong? Also, some of my enemies have more that 10 materials. Is it OK or not?

What do you suggest or advise me to do?

# Answer
Overall those settings look fine, the Max Size is only there to be an upper limit. It won't make the texture larger it's only doing as it says and setting it as a max size. For example, I make almost every texture as 4096x4096 but then set the max size to 2048x2048. This resizes my large textures to the smaller size in the actual build, but your 1024x1024 textures will remain that size because it's not hitting the limits.

Materials are fine, many models have multiple materials.

If you are concerned about build size I would check for asset packages you've imported. You may have something from the asset store that is larger than you expected. As others have mentioned, if you don't use an asset it doesn't get packed into the game so it's already doing what it can.

Some additional info like target platform etc would help.
> 1 votes

---
Tags: unity, compression
---


# Question
Title: How can I create a 'flaming' effect like in Ocarina of Time's title screen?
I'd like to recreate a flaming effect like the one from the logo on the title screen of the N64 game 'The Legend of Zelda: Ocarina of Time,' shown below:

A quick look into the textures used in the ROM provide a single 32x32 texture that looks similar to the effect but I don't know how that image (assuming that's the right one) is transformed into the effect seen on the logo.

How can I implement something similar?

# Answer
> 245 votes
First make a white-on-black mask of your logo/text and blur it.

Then create a repeating (tileable) solid noise texture (GIMP used here)

Use the Map-\>Tile... filter to create a 3x3 tiled pattern (in this example, 128x128 x 3 = 384x384) for the next step to ensure our texture is still repeatable - we'll keep only the center part.

Use Blur-\>Motion Blur... to blur the texture upward and keep only the center 1/3rd (back to 128x128)

**Multiply** both textures together on the GPU and use this for opacity.

Then animate it by moving the pattern texture upward over the mask texture:

Done for the animation part.

Then you can apply a **gradient map** (black -\> red -\> yellow -\> white) to give it fire colours:

Other colours can be used create a ghastly blue fire, a light yellow aura field, a more smoky effect, etc.

Now if you combine this as **additive** over your logo and the 3D render you get the wanted effect:

\+  \+  =

The effect can darkened by adjusting the mask and/or pattern brightness, and/or vertex color, and/or gradient color map to the designed level.

You can even use two textured patterns together (Mask * Fire Pattern * Fire Pattern) at different speeds and directions to create a more complex fire effect.

---

Technically on the N64 they may have created an approximation of the mask using a triangle mesh and vertex color instead of the mask texture due to the N64's hardware limitation regarding textures but the end result is the same ((vertex color * pattern texture) vs (mask texture * pattern texture)).

We can still use vertex colour but 20 years later we can make our lives easier and just use 2 textures or more, even today's mobile GPUs can handle an extra 256x128 gray texture without problem.

# Answer
> 2 votes
There are a few ways you could do it but off the top of my head,

1) Have the flames + logo all in one image and essentially sprite sheet animate it.

2) Render the logo in a UI layer and place some UI layer particle effects around it.

From the looks of that image, it looks like there are 3ish layers shield&sword, flames, text (ordered from back to front).

There will be many ways to get a similar effect, which you chose will be down to what engine you are developing in and what you are able to implement.

# Answer
> 0 votes
If the ROMs include a small flame texture, then I would guess this is being done with some kind of particle effect.

This would be done by first putting a sprite on the screen for the title and logo. Then place a number of particle emitters that create a flame effect behind the title sprite. That is, their Z/screen depth is such that they render behind the title.

Here's an example of using GameMaker particle effects to create flames that might give you some thoughts on the potential of this approach...

http://martincrownover.com/gamemaker-examples-tutorials/particles-fire/

---
Tags: graphic-effects
---


# Question
Title: SlimDX Direct3D10 Sprite stretches with window size
I'd like to draw a sprite bitmap with **SlimDX** **Direct3D10**, but I'm stuck at this problem, where I can see my image on screen, but it gets stretched depending on the window size.

## The issue looks like this:

I got the same general idea of drawing sprites in *Direct3D9* and *Direct2D* working fine, because there I simply resize the *RenderTarget* or reinitialize the *Device* with a new *BackBuffer*.

How do I fix this, so that the sprite remains the same dimensions independent from window size?

I'm seeing two potential issues:

* I don't know if and how I need to set the different *Transforms* to adjust for window size (I'd rather resize the backbuffer, and only transform sprites for positioning and scaling)
* I suppose I need to update the backbuffer or do something in the form's resize event.

---

## Here is my rendering code:

```
using DiscSim;
using SlimDX;
using SlimDX.Direct3D10;
using SlimDX.DXGI;
using System.Windows.Forms;
using System.Drawing;
using Device = SlimDX.Direct3D10.Device;
using Vector2 = SlimDX.Vector2;
using Resource = SlimDX.Direct3D10.Resource;

namespace DiscSimSlimDX
{
    class Camera_DX10 : Camera
    {
        private RenderTargetView renderTarget;
        private Device device;
        private SwapChain swapChain;
        private Sprite sprite;
        private SpriteInstance[] spriteInstances;

        public Camera_DX10(ISimulation simulation, Form form, string spritePath)
            : base(simulation, form, spritePath)
        {
            var swapChainDescription = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(null,
                DriverType.Hardware,
                DeviceCreationFlags.Debug,
                swapChainDescription,
                out device,
                out swapChain);

            using (var backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0))
            {
                renderTarget = new RenderTargetView(device, backBuffer);
                RenderTargetViewDescription r = renderTarget.Description;
            }

            device.OutputMerger.SetTargets(renderTarget);
            device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0, 1));

            device.OutputMerger.BlendState = BlendState.FromDescription(device,
                new BlendStateDescription()
                {
                    IsAlphaToCoverageEnabled = true,
                });

            sprite = new Sprite(device, 512 * 512); // How big should the buffer size be?
            sprite.ProjectionTransform = Matrix.Identity; // ?
            sprite.ViewTransform = Matrix.Identity; // ?

            ShaderResourceView texView = ShaderResourceView.FromFile(device, "Resources/World.png");
            var spriteInstance = new SpriteInstance(texView, Vector2.Zero, new Vector2(1, 1));
            spriteInstance.Transform = Matrix.Identity; // ?

            spriteInstances = new SpriteInstance[1] { spriteInstance };

            form.ResizeEnd += (s, e) =>
            {
                // How do I resize the backbuffer or what do I need to do
                // to adjust for the new window size?

            };
        }

        public override void Draw()
        {
            device.ClearRenderTargetView(renderTarget, Color.Black);
            sprite.Begin(SpriteFlags.None);
            sprite.DrawBuffered(spriteInstances);
            sprite.End();
            swapChain.Present(0, PresentFlags.None);
        }
    }
}

```

# Answer
> 1 votes
After some experimentation I've found this to work:

```
// Buffer-size = number of sprites in this case. Max 4096
sprite = new Sprite(device, sim.discs.Count)
{
    ViewTransform = Matrix.Identity,
    ProjectionTransform = Matrix.OrthoOffCenterLH(
        0, form.ClientSize.Width, -form.ClientSize.Height, 0, 0, 1)
};

```

I honestly don't exactly understand my solution. The sprite is probably the render target and can be transformed to project from model to world space. I'm guessing, that I don't need the view transform in my case, because the camera is supposed to be orthographic.

To scale and move the individual sprite instances I do:

```
spriteInstance.Transform = Matrix.Scaling(size, size, 1) * Matrix.Translation(d.x, -d.y, 0);

```

Where *size* is in pixels on the screen and *d.x, d.y* are the position in pixel coordinates.

Another thing I don't understand: I had to flip the projection matrix y-axis to make anything appear on screen, but as I understand it, this would be different than how Direct3D internally handles it. It works, but it's weird to have to invert my translation.

---

Although my particular problem was solved through experimentation, I'd be very happy about responses with a better (or more correct) approach to help me understand.

---

**Additions** (after more experimentation):

I've been implementing sprite-drawing in DX11 in the meantime and understood the underlying convention better: DirectX commonly uses a left-handed coordinate system in 3D (with the y-axis pointing up), but I thought of 2D coordinates (as with sprites) going from top to bottom. Everything is easier, when I stick to the 3D convention.

```
viewProjection =
    Matrix.Scaling(zoom, zoom, 1f) *
    Matrix.Translation(PositionX, -PositionY, 0f) *
    Matrix.OrthoLH(ScreenWidth, ScreenHeight, 0f, 1f);

```

This way, I don't have to flip any position vectors, I just assume positive y values mean going to the screen top. Additionally, I found that the SlimDX method *Matrix.OrthoLH* gives me correct results, where *OrthoOffCenterLH* seems to flip the y-axis, not sure if I wasn't using it correctly or if it might even be a bug.

Everything works now, but I'm a little unsure about what common practice would be. Currently, I'm multiplying scale, translation and aspect ratio (window size) all into the same matrix and assign it to the *ViewTransform* property. It might be more common to separate those transformations into view, projection and world space.

---
Tags: c#, sprites, transformation, directx10, slimdx
---


title: Textures problem in LWJGL VBO`s

text:
# Question
Title: Textures problem in LWJGL VBO`s
I\`m working at VBO terrain renderer. Now i have two troubles:

1. While try to render 100x100 terrain I have a 50x200 terrain
2. Textures is not rendering.

I spent really much time about it, and I have really no ideas...

How can I fix this?

Image:

https://i.stack.imgur.com/5SLUh.png

My part of code:

```
public class NGINE2 {
public static int MAX_PICKING_DISTANCE = 20;
public static int RAY_RADIUS = 5;
static int w = 640;
static int h = 480;
static float oldX = 0;
static float oldY = 0;
static float oldZ = 0;

static FloatBuffer cBuffer;
static FloatBuffer vBuffer;
static FloatBuffer tBuffer;

static double[][] map;

int heightmapExaggeration = 7;
static int Size = 100;

Texture floor;

public static void main(String[] args) throws Exception {
    NGINE2 ng = new NGINE2();
    ng.start();
}

void initContext() throws Exception {
    Camera.create();

    w = 800;
    h = 600;

    Display.setDisplayMode(new DisplayMode(w, h));
    Display.setFullscreen(false);
    Display.create();
    glViewport(0, 0, w, h);
    Mouse.setGrabbed(true);

    floor = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("grassy.jpg"));
}

void renderLoop() {
    long time = 0;
    int frames = 0;
    Random rand = new Random();
    cBuffer = BufferUtils.createFloatBuffer(9 * (Size * Size * 2));
    vBuffer = BufferUtils.createFloatBuffer(9 * (Size * Size * 2));
    tBuffer = BufferUtils.createFloatBuffer(9 * (Size * Size * 2));

    for (int x = 0; x < Size - 1; x++) {
        for (int y = 0; y < Size - 1; y++) {
            tBuffer.put(x * 0.25f).put((float) (map[x][y] * heightmapExaggeration)).put(y * 0.25f);
            tBuffer.put((x + 1) * 0.25f).put((float) (map[x + 1][y] * heightmapExaggeration)).put(y * 0.25f);
            tBuffer.put(x * 0.25f).put((float) (map[x][y + 1] * heightmapExaggeration)).put((y + 1) * 0.25f);
            tBuffer.put((x + 1) * 0.25f).put((float) (map[x + 1][y + 1] * heightmapExaggeration)).put((y + 1) * 0.25f);

            cBuffer.put(rand.nextFloat()).put(rand.nextFloat()).put(rand.nextFloat());
            cBuffer.put(rand.nextFloat()).put(rand.nextFloat()).put(rand.nextFloat());
            cBuffer.put(rand.nextFloat()).put(rand.nextFloat()).put(rand.nextFloat());

            vBuffer.put(x * 0.25f).put((float) (map[x][y] * heightmapExaggeration)).put(y * 0.25f);
            vBuffer.put((x + 1) * 0.25f).put((float) (map[x + 1][y] * heightmapExaggeration)).put(y * 0.25f);
            vBuffer.put(x * 0.25f).put((float) (map[x][y + 1] * heightmapExaggeration)).put((y + 1) * 0.25f);

            cBuffer.put(rand.nextFloat()).put(rand.nextFloat()).put(rand.nextFloat());
            cBuffer.put(rand.nextFloat()).put(rand.nextFloat()).put(rand.nextFloat());
            cBuffer.put(rand.nextFloat()).put(rand.nextFloat()).put(rand.nextFloat());

            vBuffer.put((x + 1) * 0.25f).put((float) (map[x + 1][y + 1] * heightmapExaggeration)).put((y + 1) * 0.25f);
            vBuffer.put((x + 1) * 0.25f).put((float) (map[x + 1][y] * heightmapExaggeration)).put(y * 0.25f);
            vBuffer.put(x * 0.25f).put((float) (map[x][y + 1] * heightmapExaggeration)).put((y + 1) * 0.25f);
        }
    }
    cBuffer.flip();
    vBuffer.flip();
    tBuffer.flip();
    IntBuffer ib = BufferUtils.createIntBuffer(3);

    glGenBuffersARB(ib);
    int vHandle = ib.get(0);
    int cHandle = ib.get(1);
    int tHandle = ib.get(2);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, vHandle);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, vBuffer, GL_STATIC_DRAW_ARB);
    glVertexPointer(3, GL_FLOAT, /* stride */3 << 2, 0L);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, cHandle);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, cBuffer, GL_STATIC_DRAW_ARB);
    glColorPointer(3, GL_FLOAT, /* stride */3 << 2, 0L);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, tHandle);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, tBuffer, GL_STATIC_DRAW_ARB);
    glTexCoordPointer(2, GL_FLOAT, /* stride */3 << 2, 0L);

    floor.bind();
    while (!Display.isCloseRequested()) {

        preRender();
        render();

        Display.update();
        Display.sync(60 /* desired fps */);

        // Calc FPS
        frames++;
        if ((System.currentTimeMillis() - time) >= 1000) {
            Display.setTitle(" FPS: " + (int) ((frames * 1000) / (System.currentTimeMillis() - time)));
            time = System.currentTimeMillis();
            frames = 0;
        }
    }
    floor.release();
    glDeleteBuffersARB(ib);
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    ib.put(0, vHandle);
    ib.put(1, cHandle);
    Display.destroy();
}

void preRender() {

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    // GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    GLU.gluPerspective(45.0f, ((float) w / (float) h), 0.1f, 100.0f); // fix na błąd z kamerą

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void render() {
    glClearColor(1, 1, 1, 1);

    Camera.acceptInput(0.6f);
    Camera.apply();
    // camera.vector.y = calculateHeight(camera.vector.x*4,
    // camera.vector.z*4)*heightmapExaggeration;

    for (int x = 0; x < Size * Size; x++) {
        glDrawArrays(GL_TRIANGLES, x * 3, 3);
    }
}

public void start() throws Exception {
    NoiseHeightMap nsh = new NoiseHeightMap(500, 24857906);
    nsh.HeightmapPNG(nsh.getHeightmap(), "C:\\Users\\Przemo\\Desktop\\mapka.png");
    map = nsh.getHeightmap();
    initContext();
    renderLoop();
}

public float calculateHeight(float x, float z) {
    float x1, x2, y1, y2, Q11, Q12, Q21, Q22;
    x1 = (int) Math.floor(x);
    x2 = (int) Math.floor(x + 1);
    y1 = (int) Math.floor(z);
    y2 = (int) Math.floor(z + 1);

    Q11 = (float) map[(int) x1][(int) y1];
    Q12 = (float) map[(int) x1][(int) y2];
    Q21 = (float) map[(int) x2][(int) y1];
    Q22 = (float) map[(int) x2][(int) y2];

    return (1f / ((x2 - x1) * (y2 - y1))) * (Q11 * (x2 - x) * (y2 - z) + Q21 * (x - x1) * (y2 - z)
            + Q12 * (x2 - x) * (z - y1) + Q22 * (x - x1) * (z - y1));
}
}

```

# Answer
Let's look at some possible mistakes:

1.)

```
cBuffer = BufferUtils.createFloatBuffer(9 * (Size * Size * 2));
vBuffer = BufferUtils.createFloatBuffer(9 * (Size * Size * 2));
tBuffer = BufferUtils.createFloatBuffer(9 * (Size * Size * 2));

```

Why do the color and texture buffers take up the same amount of space as the vertex buffer? There should be `(size - 1)^2 * 2 * 3 * 3` spaces for the vertices (amount of squares * triangles per square * vertex per triangle * data per vertex), the same amount of color information (if you use RGB) and `(size - 1)^2 * 2 * 2 * 3 * 2` texture coordinates.

2.) You only specify 4 texture coordinates for 6 vertices. Im the nested for loops you define the vertices and colors in 2 batches, one for each triangle, so you put 6 values in the vBuffer and cBuffer, but you only put 4 in the texture buffer. Textures can't render this way.

3.) You mix different versions of OpenGL. You have OpenGL 1.0 in the preRender method and a strange mix of OpenGL 1.0 and 2.0 everywhere else. You should either use OpenGL 2 only or something more modern. Don't mix 1.0 with anything.

4.) You should use shaders. The fixed function pipeline is deprecated and it's even losing support.

5.) You pass a stride of `3 << 2 = 12` for some reason. The values go from the beginning (0), just set these to 0 too.

6.) You render every triangle separately. There's no need for that. Just pass a start position of 0 and a length of `(size - 1)^2 * 2 * 3` to the drawArray function.

7.) You only draw `size^2` triangles, when there's `(size-1)^2*2` of them in total.

8.) You never dispose of the floor texture, you only unbind it
> 1 votes

---
Tags: java, textures, lwjgl, vbo
---


# Question
Title: How to abstract GLFW from my rendering library?
I would like to split my game engine in different libraries, so it is easier to maintain, however i have one problem: for example the window creation is handled by GLFW, so I encapsulated it into a class so it will be able to interact with the rest of my library. The problem is that I don't want to make the applications that use my library also depend on GLFW development headers, because otherwise when I pass user input to the application it must know about GLFW and it's data types and has to do something like this:

```
    //Application.cpp
    #include<mylibrary.h>

    int main()
    {
        myLibrary::window w("Title", 640, 480)
        myLibrary::event e;

        while(w.pollEvents(&e))
        {
            if(e.key == GLFW_KEY_ESCAPE) //Unnecessary GLFW dependancy
                w.close();
        }
    }

```

Because my header is like this:

```
    //mylibrary.h
    #include <glfw/glfw3.h>

    namespace myLibrary
    {
        class window
        {
        public:
            //Blah-blah-blah
        private:
            //Blah-blah-blah
            GLFWwindow* mWindow;
            //Blah-blah-blah
        };
    }

```

How should I go about abstracting GLFW from the application?

And I cannot use GLFW without wrapping it, because making it interact with the rest of my library ecosystem will look very ugly and out of place, and it would mean that the other libraries not only have to know about the rendering library, but also GLFW.

TL;DR: How can I hide GLFW from the user of my library?

# Answer
There are a few options:

1. Opaque data types.

In your `mylibrary.h` file, you would declare a synonym for `void*` that is published publicly, but internally it would be hold the specific type you need. For example, you could have:

```
namespace myLibrary
{
    typedef void* MyLibWindowPtr;

    class window
    {
    public:
        //Blah-blah-blah
    private:
        //Blah-blah-blah
        MyWindowPtr mWindow;
        //Blah-blah-blah
    };
}

```

In your `myLibrary.cpp` file, you would create a pointer of the proper type:

```
window::window()
{
    mWindow = glfwCreateWindow(...);
}

```

This has some downsides, such as removing types from the pointer. That leads to casts and potentially using the value incorrectly.

2. Use an implementation pointer.

This is similar to the above, but works a little differently. In this case, you might expose an actual interface that users of the library can see, but its implementation is behind an opaque pointer. This allows you to have different implementations on different systems. (For example, I've used this to wrap `CGL*` types on macOS, but `EAGL*` types on iOS, so the same code can call them.) It might look something like this:

```
class WindowInterface {
    public:
        WindowInterface();
        ~WindowInterface();

        virtual void ResizeWindow() = 0;
        //... any other methods you want publicly available
};

```

That would be public in a header included by `mylibrary.h`. Then you'd have a private header that defines the concrete implementation:

```
class GLFWImplementation : public WindowInterface
{
    public:
        GLFWImplementation();
        ~GLFWImplementation();

        virtual void ResizeWindow() override;
    // ... etc.
};

```

You would then have a factory method that return the concrete class. Something like this:

```
WindowInterface* createNewWindow()
{
    return new GLFWImplementation();
}

```
> 1 votes

---
Tags: c++, architecture, glfw, window-management
---


# Question
Title: Keypress Left is called twice in Update when key is pressed only once
I have a piece of code that is changing the position of player when left key is pressed. It is inside of `Update()` function. I know, `Update` is called multiple times, but since I have an `if`statement to check if left arrow is pressed, it should update only once. I have tested using print statement that once pressed, it gets called twice.

**Problem:** Position updated twice when key is pressed only once.

Below given is the structure of my code:

```
void Update()
{
    if (Input.GetKeyDown (KeyCode.LeftArrow))
    {
        print ("PRESSEEEEEEEEEEEEEEEEEEDDDDDDDDDDDDDD");
    }
}

```

How can I fix this?

# Answer
> 2 votes
I can think of two ways of solving this

1. **Use LateUpdate function instead of Update**

LateUpdate is said to be called just *once per frame*, so it should fix the problem. However, depending on your project, its side effect could be to change your train of thought when dealing with logic for the same execution order of scripts.
2. **Use a flag**

You could use a flag for a double check.

Example code:

```
using UnityEngine;
using System.Collections;

public class YourClass : MonoBehaviour
{
    private bool isKeyPressed = false;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftArrow) && !isKeyPressed)
        {
            isKeyPressed = true;
            // TODO
            // your logic here when button pressed
        }

        if (Input.GetKeyUp(KeyCode.LeftArrow) && isKeyPressed)
        {
            isKeyPressed = false;
            // TODO
            // your logic here when button released
        }
    }
}

```

# Answer
> 5 votes
Double check that this script isn't in the scene multiple times, either attached to multiple objects or attached multiple times to the same object. That latter mistake trips me up once in a while.

# Answer
> -1 votes
I had the same script on 4 buttons and it was getting called 4 times as expected from reading this thread. Here is how I solved it. Each button has a name. Instead of checking for bool like the answer above, check for the name button. a simple print function reveled the name of the button and I did this.

```
void Update(){
    if(Input.GetKeyDown(KeyCode.UpArrow) && gameObject.name == "down 1 force Button"){
        print("I was touched: " + gameObject.name);
    }
}

```

---
Tags: unity
---