# Question
Title: Only 20fps framerate in libgdx Android with ~190 Actors being drawn
I'm getting bad frame rates while developing a game on Android. I have been developing on desktop too and only have the issues on Android. I am testing with a Nexus 6 (can't imagine how badly it will perform on older devices at the moment). Its directly related to the amount of actors I am adding to my scene. I am removing actors that are not on the screen which helps but not enough. Currently I am calling batch.totalRenderCalls around 190 times a frame. Is it excessive?

It is currently hammering me down to around 20fps and I plan to add more to this screen making it difficult to continue development until I have resolved this. Other screens in the game run easily at 60 fps with less actors.

I am extending Actor and storing a texture against it as recommended http://www.gamefromscratch.com/post/2013/11/27/LibGDX-Tutorial-9-Scene2D-Part-1.aspx

Everything on the screen is an actor of some sort, the background (1080p image) and every square or rectangle is crafted from a 1px by 1px image and colour altered in libgdx. The hair, and skin colour and ties of each character are separate textures and create a unique face. This is exactly the same technique as I used in AndEngine in different games I have released with much less framerate trouble, I thought libgdx would have better performance, am I mistaken?

Below I've included some code snippets and a screenshot of my game in development.

Profiling of the game running with a low framerate, I have highlighted a couple of points, are they expected?

My textures:

```
public class ActorTex extends Actor {
Texture texture;

public ActorTex(float width, float height, Texture texture) {
    this(texture);
    setWidth(width);
    setHeight(height);
}

public ActorTex(Texture texture) {
    this.texture = texture;
    setWidth(texture.getWidth());
    setHeight(texture.getHeight());
}

@Override
public void draw(Batch batch, float alpha) {
    Color color = getColor();
    batch.setColor(color.r, color.g, color.b, color.a);
    batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}

@Override
public void act(float delta) {
    super.act(delta);
    setBounds(getX(), getY(), getWidth(), getHeight());
}
}

```

My screen:

```
public abstract class AbstractScreen extends Stage implements Screen {

private FPSLogger log;

public AbstractScreen(Viewport v) {
    super(v);
    log = new FPSLogger();
    GLProfiler.enable();
}

@Override
public void show() {
}

@Override
public void render(float delta) {
    SpriteBatch batch = (SpriteBatch) getBatch();
    batch.totalRenderCalls = 0;
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    // Calling to Stage methods
    super.act(delta);
    super.draw();
    System.out.println(batch.totalRenderCalls);
}

@Override
public void resize(int width, int height) {
    getViewport().update(width, height, true);
}

```

Game class render method:

```
@Override
public void render() {
    super.render();
    fpsLogger.log();
}

```

Managing my textures:

```
public class ResourceManager {

private static AssetManager manager;
private static String filePath;

public static void load() {
    manager = new AssetManager();
    filePath = "img/"; // where we store our images

    for (TextureEnum te : TextureEnum.values()) {
        manager.load(filePath + te.path, Texture.class);
    }
    manager.finishLoading();
}

public static Texture getTexture(TextureEnum te) {
    return manager.get(filePath + te.path, Texture.class);
}

public static Boolean isLoaded() {
    if (manager.getProgress() >= 1) {
        return true;
    }
    return false;
}

public static void dispose() {
    manager.dispose();
    manager = null;
}
}

```

Wondering if anyone can help, would love to get this sorted. Been stuck on this for quite a while now and I'm out of ideas unfortunately.

Does anyone have any good tips or ways to approach this? It does not seem to be a memory management problem as all these textures are in memory in other game screens without issues, also I tried replacing every texture in the game with a 1x1 pixel image and the performance problem did not seem affected, and I am not loading / doing anything funky in my render loop that I am aware of. It is only when they are displayed as actors, when they are removed as actors, the frame rate improves again. Feels like it could be something simple I have done wrong in my rendering.

# Answer
Every actor uses it's own texture so they cannot be batched. I suggest packing the textures into a TextureAtlas, or just make one big texture and change UVs around yourself.

https://github.com/libgdx/libgdx/wiki/Texture-packer#texturepacker
> 1 votes

---
Tags: android, libgdx, sprites, performance
---


title: Getting a game maker android error

text:
# Question
Title: Getting a game maker android error
When I attempt to build my project, I get the following error. Can anyone help?

```
    A problem occurred configuring project ':com.companyname.ReignOfDystopia'.
> failed to find target with hash string 'android-23' in: C:\Users\RyanW\AppData\Local\Android\sdk

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

```

# Answer
> 0 votes
Ok so i figured out the build error. I recompiled the project, and after building the error was no longer being given to me.

---
Tags: android, game-maker
---


title: OpenGL Regarding Frame/Buffer Caching

text:
# Question
Title: OpenGL Regarding Frame/Buffer Caching
I have been trying to get myself refreshed on OpenGL ES. Whilst doing so, I had the following question in mind:

Does OpenGL have any *"caching"* mechanism?

***For example:***

Let's say we draw a stationary triangle with only 3 vertices on the screen; if there will be no transformation applied to the primitive, will OpenGL ES still go through the vertex and fragment shader, drawing the primitive anew every single frame?

Or, does it have any *"caching"* mechanism, which is smart enough to know that since there is no transformation, a "caching" buffer will display the primitive on the screen bypassing calculations within vertex and fragment shaders so that unnecessary calculations could be reduced/avoided in hopes to enhance frame rate and performance?

Thank you.

# Answer
> 2 votes
**OpenGL doesn't specify this; individual implementations are allowed to cache data and/or results so long as the output is conformant with the specification**.

Note that this kind of caching is probably not what you want.

Caching like this implies that you need some kind of storage for the cached output, as well as comparison between the previous frame and the current frame. An OpenGL implementation is not going to be able to make such a comparison until SwapBuffers is called, at which point it will need to do a full comparison between two frames. So it's actually going to be more efficient (not to mention having simpler code paths in the driver - and OpenGL drivers are already quite complex as-is) to just require the program to re-submit everything every frame.

It would also lead to inconsistent framerates with spikes, which are actually worse than consistent but (hypothetically) lower framerates.

**Quake didn't need caching in 1996, it was efficient then, so you shouldn't be thinking that it's inefficient now**.

---
Tags: opengl, opengl-es, frame-buffer
---


# Question
Title: Correct velocity on collision between two rects
I have two moving objects. The objects consist of a velocity `vector2`, a `Rectangle` and a `vector2` as position (origin in the middle of the rect).

Some rough pseudo code for my collision checking function:

```
foreach (object1 in objects)
  foreach (object2 in objects)
    intersectionRect = Rectangle.Intersect(object1.Rectangle, object2.Rectangle)
    if (intersectionRect != Rectangle.Empty) // If colliding
      ResolveCollision(object1, object2, intersectionRect) // does nothing currently
    object1.position += object1.velocity
    object2.position += object2.velocity

```

My problem now is how to do the collision resolution. I need help figuring out a formula to calculate the new velocities of the objects so that they only move as far as they need to not intersect anymore.

I have used google to find a solution, but the most stuff I found was how to do collisions and not how to resolve them.

# Answer
> 1 votes
> I need help figuring out a formula to calculate the new velocities of the objects so that they only move as far as they need to not intersect anymore.

The easiest answer to this is to change strategy from checking if they are colliding right now to check "if I make this move, will it be a collision?" and if so, don't allow the move.

If you don't want to that you will need to calculate penetration depth(this can be somewhat awkward to google..) and then separate the boxes based on this. But essentially calculate how far into box A box B is and adjust position away from the point of intersection.

---

# Answer
> 0 votes
When @boredatwork mentioned penetration depth it reminded me of a method I saw in one of the XNA samples a while back. It might be useful here:

```
    /// <summary>
    /// Calculates the signed depth of intersection between two rectangles.
    /// </summary>
    /// <returns>
    /// The amount of overlap between two intersecting rectangles. These
    /// depth values can be negative depending on which wides the rectangles
    /// intersect. This allows callers to determine the correct direction
    /// to push objects in order to resolve collisions.
    /// If the rectangles are not intersecting, Vector2.Zero is returned.
    /// </returns>
    public Vector2 IntersectionDepth(RectangleF other)
    {
        // Calculate half sizes.
        var thisHalfWidth = Width / 2.0f;
        var thisHalfHeight = Height / 2.0f;
        var otherHalfWidth = other.Width / 2.0f;
        var otherHalfHeight = other.Height / 2.0f;

        // Calculate centers.
        var centerA = new Vector2(Left + thisHalfWidth, Top + thisHalfHeight);
        var centerB = new Vector2(other.Left + otherHalfWidth, other.Top + otherHalfHeight);

        // Calculate current and minimum-non-intersecting distances between centers.
        var distanceX = centerA.X - centerB.X;
        var distanceY = centerA.Y - centerB.Y;
        var minDistanceX = thisHalfWidth + otherHalfWidth;
        var minDistanceY = thisHalfHeight + otherHalfHeight;

        // If we are not intersecting at all, return (0, 0).
        if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
            return Vector2.Zero;

        // Calculate and return intersection depths.
        var depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
        var depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
        return new Vector2(depthX, depthY);
    }

```

Keep in mind this is in the context of my `RectangleF` class but it should give you the right idea.

---
Tags: xna, collision-detection, monogame
---


# Question
Title: How to set building in sequence like COC game using tiles map in cocos2d-x V3.9?
i am developing game in cocos2d-x V3.9. i want to create base like COC game. set all buildings in sequence and it can't be overlap with each others. i want also make boundary for develop city view. user can't develop city out of boundary. please anyone help me or give demo link for same.

# Answer
What you want has more to do with how to implement basic isometric view systems. If I'm understanding correctly that COC stands for Clash of Clans, without having played the game I think it's a somewhat isometric view system.

Isometric could and probably should be thought of more as a 3D projection than a 2D projection, meaning that there is a certain "depth" to the map. This would mean that simple X and Y coordinates won't do for rendering order. It also needs a Z to indicate distance from a certain point. I don't believe Tiled has built-in support to manually indicate a Z coordinate, but with some relatively simple math you should be able to calculate the distance of a building from another point on the map.

The farther away the objects are from the front of the map (front being closest to the camera), the *earlier* they should be drawn. This has a name, it's called the Painter's Algorithm.

Here's a nice tutorial to get you started with depth-sorting.

Every time you add another building, you should put it in its appropriate place in the children list, to make sure it's rendered before the buildings in front of it, and after buildings behind it.

Another very interesting tutorial.
> 0 votes

---
Tags: tilemap, cocos2d
---


title: Issue with detecting collisions in Pong

text:
# Question
Title: Issue with detecting collisions in Pong
I've been working on making Pong in OpenGL and SDL and currently have both paddles and the game ball set up properly. I have an Object (or Entity) class which is used to instantiate each of the entities in the game. The Object class constructor takes a width and a height for the object, the direction in which it moves (x and y), its position, its speed, and rotation.

In order to detect whether the ball has collided with either a paddle or the top or bottom of the screen, I do the following checks:

```
// Collision with the top
            if ((ballTop >= topWallBottom) || (ballBottom <= bottomWallTop)) {
                ball.yDir = -ball.yDir;
            }

            // Collisions Left Paddle - Ball
            if ((
                (leftPaddleBottom > ballTop) ||
                (leftPaddleTop < ballBottom) ||
                (leftPaddleLeft > ballRight) ||
                (leftPaddleRight < ballLeft))) {

            }
            else{
                ball.xDir = -ball.xDir;
                ball.yDir = -ball.yDir;
            }
            if ((
                (rightPaddleBottom < ballTop) ||
                (rightPaddleTop > ballBottom) ||
                (rightPaddleLeft > ballRight) ||
                (rightPaddleRight < ballLeft))) {

            }
            else{
                ball.xDir = -ball.xDir;
                ball.yDir = -ball.yDir;
            }

```

The dimensions of each object are defined by essentially using the width and height of each object, dividing either value by two (for either the x or the y direction) and checking if the ball's (collision box) position has intersected with that of a paddle or a border:

```
// Ball dimensions
            float ballTop, ballBottom, ballLeft, ballRight;
            ballTop = ball.posY + (ball.height / 2.0f);
            ballBottom = ball.posY - (ball.height / 2.0f);
            ballLeft = ball.posX - (ball.width / 2.0f);
            ballRight = ball.posX + (ball.width / 2.0f);

            // Wall Dimension
            float topWallBottom = topWall.posY - (topWall.height / 2.0);
            float topWallTop = topWall.posY + (topWall.height / 2.0);
            float bottomWallBottom = bottomWall.posY - (bottomWall.height / 2.0);
            float bottomWallTop = bottomWall.posY + (bottomWall.height / 2.0);

            // Left Paddle Dimensions
            float leftPaddleTop = leftPaddle.posY + (leftPaddle.height / 2.0f);
            float leftPaddleBottom = leftPaddle.posY - (leftPaddle.height / 2.0f);
            float leftPaddleRight = leftPaddle.posX + (leftPaddle.width / 2.0f);
            float leftPaddleLeft = leftPaddle.posX - (leftPaddle.width / 2.0f);
            // Right Paddle Dimensions
            float rightPaddleTop = rightPaddle.posY + (rightPaddle.height / 2.0f);
            float rightPaddleBottom = rightPaddle.posY - (rightPaddle.height / 2.0f);
            float rightPaddleRight = rightPaddle.posX + (rightPaddle.width / 2.0f);
            float rightPaddleLeft = rightPaddle.posX - (rightPaddle.width / 2.0f);

```

For some reason, the ball seems to be passing right through the paddle and not redirecting at all. I'm pretty sure that I have everything set up correctly but I can't really determine what is preventing the ball's collisions from being detected.

Is there something that I'm doing wrong conceptually, or is there just a small mechanical issue? I feel like its the latter, but I can't be sure.

Here is the full code for reference.

Of course, any other specific suggestions about how to implement collision detection here would be welcomed, thanks!

# Answer
> 1 votes
Objects passing through each other, in simulation, is called tunnelling and is a very common problem. There are numerous ways round it, some of which have been highlighted already.

A common way to solve fast moving, small objects from tunelling is to fire a ray between their previous position, and current position, and checking for intersection. If you detect one then you move your object to the intersection point then run your intersection test.

So your code would now do something like

```
if(IntersectRay(PreviousPos, CurrentPos, &IntersectionPos))
{
 BallPos = IntersectionPos;
}

```

Your InterectRay would looke something like

```
if(PreviousPos.x >  LeftBat.x && CurrentPos.x < LeftBat.x)
{
    // We have crossed the bat's plane check to see where y was
    float percentAlong = (LeftBat.x - PreviousPos.x) / (CurrentPos.x - PreviousPos.x);
    float yIntersection = percentAlong * (CurrentPos.y - PreviousPos.y) + PreviousPos.y;

    // Is Y within bat's bounds?
}

```

I've not run this code but you can see what I'm doing. Checking to see if the ray crosses a bat's vertical plane then, if it does, checking to see where the y interesction was and seeing if that is within the bat's height. If it is, then you return that intersection as found and true.

That way you should mostly pick up intersections.

More advanced versions of this can be a case of extrapolating sphere collisions, instead of rays which can pass through narrow gaps, or even scaling the collision geometry along velocity.

Basically real time physics simulation is difficult for exactly the problems that you are coming across.

# Answer
> 0 votes
I am just replying from the top of my head. But I think that your if should be something like this:

```
if (((leftPaddleBottom <= ballBottom) &&
            (leftPaddleTop <= ballTop) &&
            (leftPaddleLeft < ballLeft) &&
            (leftPaddleRight > ballLeft)))

```

For the left paddle: The ball should be within the limits of the paddle (top and bottom),

```
GOOD
___
| |
| |O
|_|

BAD
___
| |
| |
|_|
   O

```

The left side of the ball should be smaller than the right side of the paddle but greater than the left side of the paddle

```
GOOD
___
| |
| O
|_|

BAD
  ___
  | |
O | |
  |_|

```

Hope it helps.

---
Tags: opengl, collision-detection, physics, sdl
---


# Question
Title: showing Load 'name' (-1) couldn't be loaded because it has not been added to the built settings even after adding it
I have created 3 scenes `(StartMenu, Game, Win)` and added all of them to built setting with proper arrangement. `StartMenu` Scene has a button `start` which should take game to second `Game` Scene when onClick event is called on it.

The onClick event of `start` button is mapped to `LevelManager` Empty Object. That object has a script `LevelManager` whose code I have posted.

I have added all those scenes to built settings.

but still I am getting this error:

```
Level 'name'(-1) couldn't be loaded because it has been added to the built settings.
To add a level to the built settings use menu File->Built settings.
UnityEngine.Application:LoadLevel(String)
LevelManager:LoadLevel(String) (at Assets/Scripts/LevelManager.cs:8) // 8 line is Application.LoadLevel line)
UnityEngine.EventSystems.EventSystem:Update()

```

**LevelManager.cs**

```
using UnityEngine;
using System.Collections;

public class LevelManager : MonoBehaviour {

    public void LoadLevel(string name){
            Application.LoadLevel(name);
    }

    public void QuitRequest(){
            Debug.Log("Quit Requested");
    }

}

```

Error Code snapshot(couldn't copy):

# Answer
Error message tells you exactly what is wrong. You are trying to load scene with name `name`. You have to change the string in the editor in OnClick handler to `Game` in your case.
> 4 votes

# Answer
I was having the same issue. It worked one day, and not the next. I found that for some reason, it lost the link in the picture I provided. It worked fine after I updated all of the buttons on all of the scenes.
> 0 votes

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


# Question
Title: Component based Entity System using polymorphism: OpenGL does not render
I want to be able to create Entities from different Component sets. I want to call `Entity entity(new StaticObject(modelpath, position));` I have an EntityTypes Header:

```
struct EntityType
{
public:
    std::vector<Component*> components;

};

struct StaticObject :public EntityType {
    StaticObject(std::string meshPath, glm::vec3 Position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 Orientation = glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3 scale = glm::vec3(1.0f, 1.0f, 1.0f));
    Mesh mesh;
    Space space;
};

```

In its constructor I initialize the members `Mesh` and `Space` and push their address to the back of `std::vector<Component*> components;`

My Entity then takes the pointer to the StaticObject type (with the member vector components) and inserts the pointers to the components into a multimap, together with its unique entity ID (`std::multimap<unsigned int, Component*> entityComponents` contains all component instances in my game and I can access them with the entity IDs).

In my loadMesh() function I find the mesh of entityID I want to load, create a vaoID and give it to the component (together with the number of vertices and indices). But when I try to render the mesh using that data from my entityComponents multimap, my mesh won't render. I checked with debugging breakpoints and the vao id and number of indices are being initialized correctly.

```
void Graphic::loadMesh()
{
    for (unsigned int c = 0; c < Component::entityComponents.size(); ++c) {
        std::multimap<unsigned int, Component*>::iterator cItr = Component::entityComponents.find(c);
        std::multimap<unsigned int, Component*>::iterator lastC = Component::entityComponents.upper_bound(c);
        if(cItr != Component::entityComponents.end())
        for (; cItr != lastC; ++cItr) {
            Component& curCom = *cItr->second;

            if (curCom.getComType() == ComType::Mesh) {
                GLuint vaoID;
                GLuint vboID;
                GLuint iboID;
                Vertex* vertexArray = nullptr;
                unsigned int* indexArray = nullptr;
                unsigned int vertexNum = 0;
                unsigned int indexNum = 0;

                if (curCom.getPath() == "cube" || curCom.getPath() == "Cube") {
                    vertexNum = 8;
                    indexNum = 36;
                    vertexArray = new Vertex[vertexNum];
                    indexArray = new unsigned int[indexNum];

                    vertexArray[0].position.x = -1.0f;
                    ....
                    vertexArray[7].position.z = +1.0f;

                    for (int i = 0; i < 8; i++) {
                        vertexArray[i].color.r = 1.0f
                        ...
                        vertexArray[i].color.a = 1.0f;
                        vertexArray[i].position.w = 1.0f;
                    }

                    indexArray[0] = 2;
                    ...
                    indexArray[35] = 2;
                }
            }

                glCreateVertexArrays(1, &vaoID);
                glGenBuffers(1, &vboID);
                glGenBuffers(1, &iboID);

                //associate vertexArray with vboID and indexArray with iboID
                glNamedBufferStorage(vboID, sizeof(Vertex)*vertexNum, &vertexArray[0], 0);
                glNamedBufferStorage(iboID, sizeof(unsigned int)*indexNum, &indexArray[0], 0);
                glVertexArrayElementBuffer(vaoID, iboID);
                //vaoID vertex attrib array binding location 0 -> vboID
                glVertexArrayVertexBuffer(vaoID, 0, vboID, 0, sizeof(Vertex));

                //vao binding location 0 -> attribute 0
                glVertexArrayAttribBinding(vaoID, 0, 0);
                glVertexArrayAttribFormat(vaoID, 0, 4, GL_FLOAT, GL_FALSE, offsetof(Vertex, position));

                glVertexArrayAttribBinding(vaoID, 1, 0);
                glVertexArrayAttribFormat(vaoID, 1, 4, GL_FLOAT, GL_FALSE, offsetof(Vertex, color));

                cItr->second->setVAO(vaoID);
                cItr->second->setVertexNum(vertexNum);
                cItr->second->setIndexNum(indexNum);
            }
        }
    }
}

void Graphic::render()
{
    for (unsigned int c = 0; c < Component::entityComponents.size(); ++c) {
        std::multimap<unsigned int, Component*>::iterator cItr = Component::entityComponents.find(c);
        std::multimap<unsigned int, Component*>::iterator lastC = Component::entityComponents.upper_bound(c);

        if(cItr != Component::entityComponents.end()){

            for (; cItr != lastC; ++cItr) {
                if (cItr->second->getComType() == ComType::Space) {
                    glm::vec3 position = cItr->second->getPos();
                    glm::mat4 translate = glm::translate(Camera::camMatrix(), position);
                    glm::mat4 rotate = glm::rotate(translate, 2.0f, glm::vec3(1.0f, 0.0f, 0.0f));
                    glm::mat4 fullMatrix = glm::scale(rotate, glm::vec3(1.0f, 1.0f, 1.0f));
                    currentShader.addUniform("transformationMatrix", fullMatrix);
                }
                if (cItr->second->getComType() == ComType::Mesh) {
                    GLuint vaoID = cItr->second->getVAO();
                    unsigned int indexNum = cItr->second->getIndexNum();
                    glBindVertexArray(vaoID);
                    glEnableVertexArrayAttrib(vaoID, 0);
                    glEnableVertexArrayAttrib(vaoID, 1);
                    glDrawElements(GL_TRIANGLES, indexNum, GL_UNSIGNED_INT, nullptr);
                    glBindVertexArray(0);
                }
            }
        }
    }
}

```

**one thing that might be causing it is my Component implementation.** Though this would be weird because when I check the values of the vaos and index numbers, everything is correct. But as you can see my component implementation is kind of whacky, because I need to be able to access the member functions of the sub-structs through a Component\*:

```
    enum class ComType {
    Space,
    Movement,
    Mesh
};

///OPTIMIZE POLYMORPHISM
struct Component
{

    static std::multimap<unsigned int, Component*> entityComponents;
    virtual ComType getComType() = 0;
    //SPACE
    virtual glm::vec3 getPos() = 0;
    virtual glm::vec3 getFront() = 0;
    virtual glm::vec3 getScale() = 0;
    //MOVEMENT
    virtual glm::vec3 getDir() = 0;
    virtual float getSpeed() = 0;
    //MESH
    virtual std::string getPath() = 0;
    virtual GLuint getVAO() = 0;
    virtual unsigned int getVertexNum() = 0;
    virtual unsigned int getIndexNum() = 0;

    //SETTERS
    virtual void setVAO(GLuint& VAO) {};
    virtual void setVertexNum(unsigned int VertexNum) {}
    virtual void setIndexNum(unsigned int IndexNum) {}
};

struct Space :public Component{
    const ComType type = ComType::Space;
    glm::vec3 position;
    glm::vec3 orientation;
    glm::vec3 scale;

    //GETTERS
    ComType getComType() { return type; }
    glm::vec3 getPos() { return position; }
    glm::vec3 getFront() { return orientation; }
    glm::vec3 getScale() { return scale; }

    glm::vec3 getDir() { return glm::vec3(); }
    float getSpeed() { return 0.0f; }
    std::string getPath() { return ""; }
    GLuint getVAO() { return 0; }
    unsigned int getVertexNum() { return 0; }
    unsigned int getIndexNum() { return 0; }
};

struct Movement :public Component {
    const ComType type = ComType::Movement;
    glm::vec3 direction;
    float speed;

    //GETTERS
    ComType getComType() { return type; }
    glm::vec3 getDir() { return direction; }
    float getSpeed() { return speed; }

    glm::vec3 getPos() { return glm::vec3(); }
    glm::vec3 getFront() { return glm::vec3(); }
    glm::vec3 getScale() { return glm::vec3(); }
    std::string getPath() { return ""; }
    GLuint getVAO() { return 0; }
    unsigned int getVertexNum() { return 0; }
    unsigned int getIndexNum() { return 0; }

};

struct Mesh :public Component {
    const ComType type = ComType::Mesh;
    std::string filePath = "";
    GLuint vaoID = 0;
    GLuint textureID = 0;
    Vertex* vertexArray = nullptr;
    unsigned int* indexArray = nullptr;
    unsigned int vertexNum = 0;
    unsigned int indexNum = 0;

    //GETTERS
    ComType getComType() { return type; }
    std::string getPath() { return filePath; }
    GLuint getVAO() { return vaoID; }
    unsigned int getVertexNum() { return vertexNum; }
    unsigned int getIndexNum() { return indexNum; }

    glm::vec3 getDir() { return glm::vec3(); }
    float getSpeed() { return 0.0f; }
    glm::vec3 getPos() { return glm::vec3(); }
    glm::vec3 getFront() { return glm::vec3(); }
    glm::vec3 getScale() { return glm::vec3(); }

    //SETTERS
    void setVAO(GLuint& VAO) { vaoID = VAO; }
    virtual void setVertexNum(unsigned int VertexNum) { vertexNum = VertexNum; }
    virtual void setIndexNum(unsigned int IndexNum) { indexNum = IndexNum; }
};

```

I hope these snippets are enough.

# Answer
Okay its fixed now, but i dont know why. I played around and started copying the rendering in the loading function and then i called the loading function every frame (together with my other rendering function). i got 2 cubes, which had me wondering because i expected one (from the loadMesh function). when i erased the rendering part from the loadMesh function the one cube from the render() function stayed there! i dont know what happened, but it just works now. it might be because i called

```
    glEnableVertexArrayAttrib(vaoID, 0);
    glEnableVertexArrayAttrib(vaoID, 1);

```

when i copied the rendering part but i am not calling it anymore now and it still works! really weird.

EDIT: it looks like i HAVE to use glCreateBuffers instead of glGenBuffers. that was literally it.
> 0 votes

---
Tags: opengl, c++, entity-system, component-based, polymorphism
---


title: Control stick map analysis

text:
# Question
Title: Control stick map analysis
I'm implementing this map of inputs (from the gamecube title Super Smash Bros. Melee) and translating it into code for my game:

The map is depicted using hardware coordinates (the square shape of the map) while the game itself limits the range of inputs to a circle (depicted by the gray circular outline). If a hardware input is outside the range of the circular game input, then it is rounded down. This is what causes the radial patterns. Each colored section is a different output based on the input. The gray square in the center is the deadzone of the stick.

The zones "fsmash", "usmash", and "dsmash" were easy to code in. It was as simple as

```
if (pos.x > 0.80 || pos.x < -0.80) fsmash
if (pos.y > 0.66) usmash
if (pos.y < -0.66) dsmash

```

My question is how to incorporate the other 4 zones. It's simple for "jab" as it is in the deadzone so it will be the else condition (when pos.x && pos.y == 0) The inputs go out radially which seems to suggest it follows the same patterns as the larger zones. When inputs are outside of the black circle I have drawn, they could be rounded down then I could simply do..

```
if (pos.x > 0) ftilt
if (pos.x < 0) jab
if (pos.y > 0) utilt
if (pos.y < 0) dtilt
else jab

```

However I'm not sure of how I could implement it since the cutoff point for the outer zones was the actual implemented radius of the stick in game. Any help would be appreciated or ask if I need to clarify anything. Thanks!

# Answer
> 1 votes
Note that your four other regions are divided along the diagonal lines where `y = ±x`, so you can test for these using absolute values:

```
Assume the following constants:
   horizontalCoefficient = 1.0
   verticalCoefficient   = 1.0

ftilt:  pos.x > abs(pos.y) * horizontalCoefficient
jab:   -pos.x > abs(pos.y) * horizontalCoefficient
utilt:  pos.y > abs(pos.x) * verticalCoefficient
dtilt: -pos.y > abs(pos.x) * verticalCoefficient

```

It's up to you how you want to handle values exactly on the cusp where `y = ±x`. For instance, you could decide that horizontal moves ftilt & jab take precedence over vertical moves by changing their signs to `>=`

---

If you want the angle thresholds to be at some angle different than 45-degrees, you can change the constant coefficients used. This doesn't require any trigonometry or angular calculations at runtime - we use trig to figure out the value we want at design time/compile time, and at runtime we just compare ratios.

Let `theta` be the angle between the horizontal axis and the `utilt/ftilt` boundary. Then we can calculate our coefficients using the tangent and cotangent trigonometric functions:

```
verticalCoefficient = tan(theta)
horizontalCoefficient = 1.0/verticalCoefficient

```

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


title: Box2D body rotation problem

text:
# Question
Title: Box2D body rotation problem
When my player jumps, I start a rotation and I want to finish it when he gets back on the ground.

My Player is jumping off the ground and landing back on in **1 second**.

My physics are updating at 10 FPS (**10 times per second**).

So I want to complete a 180 degree rotation for exactly 1 second. I add 18 degree to my player at every world update. I convert the degrees to radians, but the result is this:

I want him to jump with a 0 degree angle, rotate and land with 0 degree angle. Here is my code:

```
world.step(step, 8, 3);

if(isJumping) {
    angle -= (18*Math.PI)/180; // conver degrees to radians
    player.body.setTransform(player.body.getPosition(), angle);
}

```

# Answer
By your logic you're applying your math correctly. However, I doubt that it's really taking the rectangle 1 second to jump and also that your engine is giving a constant 10 fps.

Your physics framerate timed with your jump event will fluctuate based on a ton of different things (when the thread is scheduled, how the engine prioritizes it, PC load, etc) and I don't think you should rely on a specific amount of physics frames to rotate your character.

* If you want, you can cheat the effect without using physics. Make the rotation an animation such that it will always complete its rotation regardless of the physics frames. I think that Impossible Game uses this effect

* You can set the rotational angle to the desired amount once you hit the ground and tweak the amount your rotating by to make it look smooth. This is less desirable if your physics fps ever becomes really unstable but if you need the physics engine to know about your rotation that can't be done from the animation, I'd do this.
> 1 votes

---
Tags: libgdx, box2d, rotation, angles
---


# Question
Title: Complex system-component dependencies in entity-component-system?
I am trying to design a data-oriented ECS engine. The issue I am struggling with is that my rendering system have to rely on *two different* sets of entities to actually do rendering.

My current idea is to have (usually one, but possibly more) entities representing cameras (e.g. sets of components describing views and viewports). Then, I can have `RenderingSystem` that iterates through all `CameraComponents` and renders everything they 'see' to appropriate viewports.

However, this requires `RenderingSystem` to query for two non-intersecting sets of components: `cameras` and `renderables`. My current approach allows systems to select a set of nodes that have one or several required components. It does not allow for more complex queries, like *either* `CameraComponent` or `RenderableComponent`. This is not the first time when more complex system-component dependencies (using unions of component sets insetead of their intersections) seem useful to me.

Plain old data components have crucial advantages:

* They are trivially serializable
* Can be changed by game designers without recompilation or coding knowledge
* Describe behaviors in purely declarative way

That is why I would like to put cameras among other things in the ECS.

Use case: if we are implementing mirrors, we may put `Renderable`, `Position` and `Camera` components on them, then `Renderable's` texture will also be a render target for `Camera`. `RenderingSystem` then will render them in some efficient way.

So, is defining more complex relations with components (like "*this system should receive all nodes that have `Camera` and `Position` as 'cameras' collection and all nodes with `Renderable` and `Position` as 'renderables'*) the most flexible solution in this case, or is there a better way?

**UPDATE(1):** I ended up allowing systems to define their dependencies like this (the word "aspect" is borrowed from Artemis ECS framework):

```
aspects: {
    renderables: Aspect.all(['Transform', 'Sprite']),
    cameras: Aspect.all(['Transform', 'Camera']),
    emitters: Aspect.all(['Transform', 'ParticleEmitter']),
    ...
}

```

These lists are gathered, passed to a system, cached and rendered in an efficient way. This actually works quite nicely (in other systems too), as well as cameras being entities. Is this a common way to do it?

**UPDATE(2):** I have spent some time working with ECS-like architectures and added a conclusion as an answer. I hope it makes clear that the approach I have suggested in the first update is just one of available options.

# Answer
> 2 votes
I have spent some time working with ECS-like approaches and can now write the conclusion.

Making complex queries for your entities is alright (and necessary) as long as they are not a bottleneck (which they won't be if you know in advance what you will be querying for).

Let's use name `Aspect` for a selection filter you use to query for entities. Aspects are created with constructors like `Aspect.all([TransformComponent, RenderableComponent, ...])`, `Aspect.any([...])` and so on, whatever you actually need. `Aspect.all` instance can be efficiently represented by a bitfield, and we can have a lookup table:

```
HashTable<Aspect, Set<EntityId>>

```

It gives us O(1) querying for a set of entities having all the specified components. This table is updated on inserting/removing entities and their components. Aspects we query for should also be known beforehand to be efficiently tracked (I make calls like `entityManager.registerAspect(Aspect.all([...]))` during initialization stage, before creating any entities). `EntityId` sets for `Aspect.any` and other kinds of `Aspect` can also be cached or constructed on the fly depending on memory and performance requirements.

As for systems and defining their dependencies, this is a matter of preference and convenience. It is mostly unrelated to the rest of your infrastructure, but you can make some handy helpers. Systems are basically anything that fetches your entities and operates on them. If you like the declarative approach and defining dependencies in your class, you can implement a base class for some (not necessarily all) systems and use it like this:

```
class Renderer extends AutoQueryingSystem {
    aspects: {
        renderables: Aspect.all([
            TransformComponent,
            Aspect.any([SpriteComponent, SimpleShapeComponent])
        ]),
        cameras: Aspect.all([TransformComponent, CameraComponent])
    },

    // AutoQueryingSystem automatically quieries for its aspects
    // and passes the results into its update function
    update: function(dt, entities) {
        for (camera of entities.cameras) {
            for (renderable of entities.renderables) {
                // Do rendering...
            }
        }
    }
}

```

But you can do the same thing manually just as well:

```
var renderableAspect = Aspect.all([
    TransformComponent,
    Aspect.any([SpriteComponent, SimpleShapeComponent])
]);
var cameraAspect = Aspect.all([TransformComponent, CameraComponent]);
...
update: function(dt) {
    var cameras = entityManager.getEntities(renderableAspect);
    var renderables = entityManager.getEntities(cameraAspect);
    // Do rendering...
}

```

As Sean Middleditch notes, you may not even have separate `System` classes for third-party libraries, in which case the abovementioned declarative approach would be harder to implement. Simply calling `entityManager.getEntities` can be done anywhere, though.

# Answer
> 10 votes
First, you should not have a strict 1-1 mapping of Components to Systems. It's unclear to me from your question if that's the case already. You may very well have singular systems that use or interact with numerous components. Rendering, physics, AI, etc. are all Systems (they perform a cohesive set of updates and logic) but interact with many Components.

A System needs to be able to store a list of entities that match some particular **Signature**. e.g., if physics requires `BodyComponent` and `TransformComponent`, then the `PhysicsSystem` needs a list of all entities that have both of those two components.

**Solution 1**

A System also likely needs multiple such lists, as you're finding. `RenderSystem` needs to know about all Renderable+Transform pairs, as well as all Camera+Transform pairs, and that's only for a very simple rendering engine (once you get particles, post-processing, terrain, foliage, skinned meshes, etc. it gets more complex).

**Solution 2**

The other alternative that I'm rather fond of is to stop trying to use the ECS pattern. If you split all your engines (physics, graphics, AI, audio, etc.) up into separate libraries (which is probably already the case for physics since most people use off-the-shelf libraries there) then you'll note that you need each to exist independently of your ECS framework.

For instance, when you load an entity up and see that it has a `PhysicsComponent` you call into your physics library's `CreateBody()` function with all the data from the entity; that will usually return some kind of pointer or id. Store that into the `PhysicsComponent`. Most of the rest of the data you loaded off disk can possibly even just be thrown away since it'll all be copied into the physics library's internal data structures. Really all you're left with is some glue so when game logic needs to add a force to a game object it can find the appropriate pointer to the physics library's body object.

Your Components end up mostly just being glue that holds your convenient data-driven game objects together with the external handles/objects managed by your engine libraries. You're more likely to find that you don't need Systems at all anymore and possibly (for simpler games) don't even need Components, either.

Depending on your choice of libraries or how you decide to implement Components, this may still even end up looking a lot like an ECS. For instance, instead of storing a `PhysicsComponent` that holds a pointer to a rigid body object, your library may allow you to attach a unique ID to a body when it's created and then query for bodies by ID; that would allow you to attach the `EntityId` to the corresponding physics body and then write a `ComponentMapper` facade that queries your third-party physics library instead of a custom component data structure. I question the utility of such a design myself, but it's certainly something you could do.

# Answer
> 2 votes
I think you are over-using the component model. While what you are saying could be accomplished and would work, the general way of doing this is making the camera a global thing.

Sometimes it is just much easier to make an exception than to try force everything into a rigid view of "everything must be a component". So I recommend making the camera not a component but rather a property of the RenderSystem. There you could even have a list of cameras, and the RenderSystem would have much more control to optimize the way things get rendered.

---

In response to your edit:

If you want to keep your original model, and you are willing to sacrifice performance(though that will depend on the implementation), you could do it in 2 passes. The first pass will only enumerate cameras into the system, and the second pass renders all objects from all viewports.

---
Tags: architecture, entity-system, component-based
---


title: Unity AudioClip Null Error C#

text:
# Question
Title: Unity AudioClip Null Error C#
I'm trying to play a sound on death, but keep getting a null error. I know it is something in my code, and I have already tried looking at an alternate question.

This is my code:

```
public class BallHealth : MonoBehaviour
{
    public float maxPositionY = -10.0f;

    void Update ()
    {
        float positionBallY = transform.position.y;

        if (positionBallY <= maxPositionY)
        {
            StartCoroutine (RestartLevel ());
        }
    }

    IEnumerator RestartLevel()
    {
        AudioSource audio = new AudioSource ();

        audio.clip = (AudioClip)Resources.Load("GameOver") as AudioClip;
        audio.Play();
        yield return new WaitForSeconds(audio.clip.length);
        Debug.Log("You Died....");
        SceneManager.LoadScene("LevelOne");
    }
}

```

I already locate my file, in the resource folder.

How do I fix the null error?

# Answer
> 2 votes
You can't allocate components without attaching them to a GameObject (with `gameObject.AddComponent`). Unity will return a "null" object if you try to call a component constructor directly.

You should replace this line:

```
AudioSource audio = new AudioSource ();

```

With something like this:

```
AudioSource audio = GetComponent<AudioSource>();
if (audio == null) audio = gameObject.AddComponent<AudioSource>();

```

Which will use the existing AudioSource component on the object if you already made one, and will create and attach a new one if not.

Unrelatedly, you are unnecessarily casting the same object twice here (with `(AudioClip)` and `as AudioClip`):

```
audio.clip = (AudioClip)Resources.Load("GameOver") as AudioClip;

```

You only need one or the other, or even better:

```
audio.clip = Resources.Load<AudioClip>("GameOver");

```

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


# Question
Title: How do I clear streaming textures in SDL?
I need to clear a streaming texture before I draw into it on the next frame, because only a part is updated, and it's random enough that I can't predict which part will be clear.

I don't want to reinitialize it every time, or rewrite the whole texture each time.

Here is the code I tried, but this fails every time, since the texture is in streaming mode.

```
SDL_Texture* StreamingTexture = SDL_CreateTexture(render, SDL_PIXELFORMAT_RGBA8888,
        SDL_TEXTUREACCESS_STREAMING, screen_width, screen_height);

SDL_SetRenderTarget(render, StreamingTexture);
SDL_SetRenderDrawColor(render, 0, 0, 0, 0);
SDL_RenderClear(render);

```

# Answer
You just need to use SDL\_FillRect:

```
SDLX_TextureLockSurface(Texture, Surface);
SDL_FillRect(Surface,NULL,SDLX_RGBAtoPixel(0,0,0,0)); // <<-- this is what clears entire texture
SDLX_TextureUnlock(Texture); //LOOOOOCK !!!!!

```
> 1 votes

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


title: orbit object around another object

text:
# Question
Title: orbit object around another object
I am building `3D solar system` containing (sun \> earth \> moon).
I have difficult to add the part which the moon rotate around earth.
I separated between "moon" and other stars.
The problem is that the center of earth is not const like the sun.
I know that earth is in `starsList[1]` so I thought to translate the moon to this place but got weird result..
Someone have an idea how to do this?

```
mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [0, 0, z]);

for (i = 0; i < starsList.length; i++) {
    mvPushMatrix();

    if (starsList[i].name == "moon"){
        /////////
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        mat4.translate(mvMatrix, starsList[1].initPlace);
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        ////////
   }
    else{
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        mat4.translate(mvMatrix, starsList[i].initPlace);
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
    }
    mvPopMatrix();
}

```

# Answer
I assume, that you are using 3D/2D models for the sun and the planets and the moon. In this case, you can pass `uniforms` for each planet to the `vertexShader` which contain data about the position of an object.

For example the sun will always have a steady position in the middle of the screen. And the earth will move relative to the sun and the moon relative to the earth.

First you create uniforms for your shaders:

```
uniform vec4 sunPos;
uniform vec4 earthPos;
uniform vec4 moonPos;

```

Then you get their location so you can change them:

```
GLint sunPos = glGetUniformLocation(shaderPrg, "sunPos");
GLint earthPos = glGetUniformLocation(shaderPrg, "earthPos");
GLint moonPos = glGetUniformLocation(shaderPrg, "moonPos");

```

Then you set the `sunPos` to `vec4(0, 0, 0, 1)`

```
glUniform4i(sunPos, 0, 0, 0, 1);

```

Then you calculate the Earth's position according to the sun for each frame in your gameloop:

```
glUniform4f(earthPos, calcEarthX(), calcEarthY(), calcEarthZ(), 1.0f);

```

Note that the calc function need to return a float or a GLfloat

Then you just do the same for the Moon's postion for each frame.

```
glUniform4f(moonPos, calcMoonX(), calcMoonY(), calcMoonZ(), 1.0f);

```

Now you can use these uniforms in your shaders render each model correctly.

There is surely an easier solution, but I am new to openGL, too. ;D
> 0 votes

---
Tags: opengl, 3d, javascript, webgl
---


# Question
Title: Achieve same effect as a FixedJoint2D but also match RigidBody2D forces
Trying to make an object that is affected by rigidbody physics in exactly the same way as the object it's linked to. So torque, velocity, and any resultant torque or velocity from a collision.

This image demonstrates what I mean:

I've tried using FixedJoint2D, my objects share velocity but do not share torque, applying torque doesn't do anything to either object, it seems locked. I tried using other joints, such as DistantJoint2D(doesn't match y value, only separation value), TargetJoint2D(immediately negates velocity), RelativeJoint2D(The closest to actually working, but glitches out when torque is applied, it acts on a centre of mass between the two connected objects and the objects sort of spin around each other, sometimes getting closer together or farther apart)

I also can't just apply the transform position and rotation to the second object, since these objects will be colliding with moving objects. The objects that they collide with slide into the squares and are pinched away when using this method.

So I need to know if there is a way to use the FixedJoint2D or RelativeJoint2D or another method or joint that I do not know of to achieve this same effect. Perhaps applying the collision forces happening to one object to the other but it needs to be immediate and I don't know how to apply the collision from one object to another.

# Answer
> 1 votes
This is a really interesting question and had me thinking about it. I don't think it's a physics question because you want a non physical response. In A you want the left hand block to hover in the air where as, physically, I would expect A to fall and constrain to block B too. So I am not sure that this is a physics problem.

Your diagram shows that B is always responding to the other objects and A merely following? if that is the case then I'd simply have A as a trigger, mimicking what B does, with a linear translate, and having no effect on the simulation. That would certainly produce the effects you've designed.

If you want B to respond to A's physical interactions, and vice versa then I would have an overlap sphere on both of the bodies. When the bodies come close to something that will effect them the rigidbody for that body is switched on, and the other body's is switched off and it's welded in it's relative position. In effect the other body becomes a ghost.

Where this breaks down is when you have both bodies trying to react to different impulses. There again I think that is impossible because you could well get opposing inputs. One body could be hit left, the other could be hit right, and you can't resolve those conflicting inputs so you would need to only ever nominate one dominate.

---
Tags: unity, physics, collision-resolution, joints
---


# Question
Title: Character movement resetting x & y position in HTML5 game
I have an HTML5 game I'm working on and I'm at the point where I'm trying to make the character move. For the most part, the character(A rectangular square) is moving, but it's not moving from its starting position. Instead, when I hit the move key the character's x position and y position are reset to 0, 0. My question is, why is the character's position being set to 0, 0 before it starts moving?

I've included a link to the dropbox with the project so it's easier to see what's going on, but here's the movement script for reference.

**initMap.js Script, lines 81 - 92**

```
case "Player":
    gameObjectsLayerCtx.fillStyle = "rgb(0, 0, 0)";
    gameObjectsLayerCtx.fillRect(xPos, yPos, destWidth / 3, destHeight / 3);
    window.onkeydown = function(ev){
        var key = ev.key;
        if(key == "w"){
            yPos += 5;
            gameObjectsLayerCtx.clearRect(0, 0, gameObjectsLayer.width, gameObjectsLayer.height);
            gameObjectsLayerCtx.fillRect(xPos, yPos, destWidth / 3, destHeight / 3);
        }
    };
    break;

```

Project

The script is the initMap.js script and the movement functionality is from lines 81 - 92

**The character's starting position**  **Where the character moves to when pressing the move key**

# Answer
Fair warning, you're going to run into quite a few issues with some of your code, but I was able to resolve this particular problem.

You have to save the players X,Y positions if you plan on changing them. By the time the window.onkeydown fires the xPos and yPos are reset to 0 and 0. Lets look at this function and look at the last 6 lines.

```
gameObjectsSpriteSheet.onload = function(){
  var tileWidth = 0;
  var tileHeight = 0;
  var destWidth = 0;
  var destHeight = 0;
  var xPos = 150;
  var yPos = 150;
  for(var rows = 0; rows < GameObjects.length; rows++){
    tileHeight = 247;
    destHeight = tileHeight / 2;
    for(var cols = 0; cols < GameObjects[rows].length; cols++){
      tileWidth = 255;
      destWidth = tileWidth / 2;
      switch(GameObjects[rows][cols].object){
        case "T":
          gameObjectsLayerCtx.drawImage(gameObjectsSpriteSheet, 0, 0, tileWidth, tileHeight, xPos, yPos, destWidth, destHeight);
          break;
        case "Player":
          gameObjectsLayerCtx.fillStyle = "rgb(0, 0, 0)";
          gameObjectsLayerCtx.fillRect(xPos, yPos, destWidth / 3, destHeight / 3);
          window.onkeydown = function(ev){
            var key = ev.key;
          if(key == "w"){
            yPos += 5;
            gameObjectsLayerCtx.clearRect(0, 0, gameObjectsLayer.width, gameObjectsLayer.height);
            gameObjectsLayerCtx.fillRect(xPos, yPos, destWidth / 3, destHeight / 3);
          }
          };
          break;
      }
      xPos += destWidth / 2;
    }
    xPos = 0; // After drawing the scene you reset the xPos to 0
    yPos += destHeight / 2;
  }
  yPos = 0; // After drawing the scene you reset the yPos to 0
}
```

You're reseting the X and Y so you can draw the next line, but the player has no idea where it was drawn when the keypress event happens.

You can fix this by adding 2 variables to store the players X and Y positions:

```
var playerX = 0;
var playerY = 0;
```

Put this outside of the gameObjectsSpriteSheet.onload function. I put it directly after the close of that function when I did my testing.

This next bit of code is my solution with a couple comments that will hopefully explain what is going on.

```
gameObjectsSpriteSheet.onload = function() {
  var tileWidth = 0;
  var tileHeight = 0;
  var destWidth = 0;
  var destHeight = 0;
  var xPos = 150;
  var yPos = 150;
  for (var rows = 0; rows < GameObjects.length; rows++) {
    tileHeight = 247;
    destHeight = tileHeight / 2;
    for (var cols = 0; cols < GameObjects[rows].length; cols++) {
      tileWidth = 255;
      destWidth = tileWidth / 2;
      switch (GameObjects[rows][cols].object) {
        case "T":
          gameObjectsLayerCtx.drawImage(gameObjectsSpriteSheet, 0, 0, tileWidth, tileHeight, xPos, yPos, destWidth, destHeight);
          break;
        case "Player":
          playerX = xPos; // Ok we need to draw the player at this location, lets save it for later use.
          playerY = yPos; // lets save this for later use as well
          gameObjectsLayerCtx.fillStyle = "rgb(0, 0, 0)";
          gameObjectsLayerCtx.fillRect(playerX, playerY, destWidth / 3, destHeight / 3); // Draw the player using the variables we just saved.
          window.onkeydown = function(ev) {
            var key = ev.key;
            if (key == "w") {
              playerY += 5; // Lets modify the playerX and Y instead of yPos since that variable is no longer useful.
              gameObjectsLayerCtx.clearRect(0, 0, gameObjectsLayer.width, gameObjectsLayer.height);
              gameObjectsLayerCtx.fillRect(playerX, playerY, destWidth / 3, destHeight / 3); // Draw the player using our new variables.
            }
          };
          break;
      }
      xPos += destWidth / 2;
    }
    xPos = 0;
    yPos += destHeight / 2;
  }
  yPos = 0;
}
  }
// this is where I put the new variables.
var playerX = 0;
var playerY = 0;
```
> 1 votes

---
Tags: javascript, html5, html-canvas
---


title: Specular Lighting Error

text:
# Question
Title: Specular Lighting Error
At the moment I am implementing Specular Lighting for my engine in DirectX on top of Diffuse Lighting. I am using a physically based technique and as you can see from the image below something is clearly wrong. Can somebody please help me?

One thing I think that may be causing the issue is a buffer packing error (I only started learning to do this yesterday) so some values may not be sent across to HLSL properly. Here's my cbuffer struct + the light struct.

```
struct cbPerFrame
{
    Light  light;
    XMVECTOR cameraPosition;
    float pad;
    float pad2;
    float pad3;
    float Roughness;
    float Metalness;
};

struct Light
{
    Light()
    {
        ZeroMemory(this, sizeof(Light));
    }
    XMFLOAT3 dir;
    float pad;
    XMFLOAT4 ambient;
    XMFLOAT4 diffuse;
};

```

Or is it how I'm sending my Camera Position over to HLSL?

```
constbuffPerFrame.light = light;
constbuffPerFrame.Roughness = 10.0f;
constbuffPerFrame.Metalness = 10.0f;
constbuffPerFrame.cameraPosition = camPosition; //camPosition is a XMVector

```

If that's fine then there must be something dead stupid & simple I've done in my shader:

**Effects.fx**

```
#include "common.hlsli"

struct Light
{
    float3 dir;
    float4 ambient;
    float4 diffuse;
};

cbuffer cbPerFrame
{
    Light light;
    float3 cameraPosition;
    float Roughness;
    float Metalness;
};

cbuffer cbPerObject
{
    float4x4 WVP;
    float4x4 World;
};

Texture2D ObjTexture;
SamplerState ObjSamplerState
{
    Filter = ANISOTROPIC;
    MaxAnisotropy = 16;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float2 TexCoord : TEXCOORD;
    float3 normal : NORMAL;
};

VS_OUTPUT VS(float4 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL)
{
    VS_OUTPUT output;

    output.Pos = mul(inPos, WVP);

    output.normal = mul(normal, World);

    output.TexCoord = inTexCoord;

    return output;
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 textureColor = ObjTexture.Sample(ObjSamplerState, input.TexCoord);
    float3 specularAlbedo = float3(Metalness, Metalness, Metalness);

    float3 lighting = 0.0f;

    float3 lightPos = float3(100.0f, 100.0f, 0.0f);
    float3 pixelToLight = lightPos - input.Pos;
    float  lightDist = length(pixelToLight);
    float3 lightDir = pixelToLight / lightDist;
    float nDotL = saturate(dot(input.normal, light.dir));

    float3 diffuseLighting = textureColor * light.ambient * light.diffuse;
    diffuseLighting += saturate(DirectDiffuseBRDF(textureColor, nDotL));

    float3 specularLighting = textureColor * light.ambient * light.diffuse;
    specularLighting += DirectSpecularBRDF(specularAlbedo, input.Pos, input.normal, lightDir, cameraPosition, Roughness);

    lighting = diffuseLighting + specularLighting;

    return float4(lighting, textureColor.a);
}

```

**common.hlsli**

```
//=================================================================================================
// Constant Variables
//=================================================================================================
static const float Pi = 3.141592654f;
static const float Pi2 = 6.283185307f;
static const float Pi_2 = 1.570796327f;
static const float Pi_4 = 0.7853981635f;
static const float InvPi = 0.318309886f;
static const float InvPi2 = 0.159154943f;

//=================================================================================================
// Sampler States
//=================================================================================================
SamplerState SamplerLinear
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

SamplerState SamplerAnisotropic
{
    Filter = ANISOTROPIC;
    MaxAnisotropy = 16;
    AddressU = Wrap;
    AddressV = Wrap;
};

// ===============================================================================================
// http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html
// ===============================================================================================
float2 Hammersley(uint i, uint N)
{
    float ri = reversebits(i) * 2.3283064365386963e-10f;
    return float2(float(i) / float(N), ri);
}

// ===============================================================================================
// http://graphicrants.blogspot.com.au/2013/08/specular-brdf-reference.html
// ===============================================================================================
float GGX(float NdotV, float a)
{
    float k = a / 2;
    return NdotV / (NdotV * (1.0f - k) + k);
}

// ===============================================================================================
// Geometry Term
// -----------------------------------------------------------------------------------------------
// Defines the shadowing from the microfacets.
//
// Smith approximation:
// http://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf
// http://graphicrants.blogspot.fr/2013/08/specular-brdf-reference.html
//
// ===============================================================================================
float G_Smith(float a, float nDotV, float nDotL)
{
    return GGX(nDotL, a * a) * GGX(nDotV, a * a);
}

// ================================================================================================
// Fresnel
// ------------------------------------------------------------------------------------------------
// The Fresnel function describes the amount of light that reflects from a mirror surface
// given its index of refraction.
//
// Schlick's approximation:
// http://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf
// http://graphicrants.blogspot.fr/2013/08/specular-brdf-reference.html
//
// ================================================================================================
float3 Schlick_Fresnel(float3 f0, float3 h, float3 l)
{
    return f0 + (1.0f - f0) * pow((1.0f - dot(l, h)), 5.0f);
}

// ===============================================================================================
// http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
// ===============================================================================================
float3 ImportanceSampleGGX(float2 Xi, float Roughness, float3 N)
{
    float a = Roughness * Roughness; // DISNEY'S ROUGHNESS [see Burley'12 siggraph]

    float Phi = 2 * Pi * Xi.x;
    float CosTheta = sqrt((1 - Xi.y) / (1 + (a * a - 1) * Xi.y));
    float SinTheta = sqrt(1 - CosTheta * CosTheta);

    float3 H;
    H.x = SinTheta * cos(Phi);
    H.y = SinTheta * sin(Phi);
    H.z = CosTheta;

    float3 UpVector = abs(N.z) < 0.999 ? float3(0, 0, 1) : float3(1, 0, 0);
    float3 TangentX = normalize(cross(UpVector, N));
    float3 TangentY = cross(N, TangentX);

    // Tangent to world space
    return TangentX * H.x + TangentY * H.y + N * H.z;
}

//The Direct Diffuse BRDF
float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
    return (diffuseAlbedo * nDotL);
}

//The Direct Specular BRDF
float3 DirectSpecularBRDF(float3 specularAlbedo, float3 positionWS, float3 normalWS, float3 lightDir, float3 CameraPos, float Roughness)
{
    float3 viewDir = normalize(CameraPos - positionWS);
    float3 halfVec = normalize(viewDir + lightDir);

    float nDotH = saturate(dot(normalWS, halfVec));
    float nDotL = saturate(dot(normalWS, lightDir));
    float nDotV = max(dot(normalWS, viewDir), 0.0001f);

    float alpha2 = Roughness * Roughness;

    // Computes the distribution of the microfacets for the shaded surface.
    // Trowbridge-Reitz/GGX normal distribution function.
    float  D = alpha2 / (Pi * pow(nDotH * nDotH * (alpha2 - 1) + 1, 2.0f));

    // Computes the amount of light that reflects from a mirror surface given its index of refraction.
    // Schlick's approximation.
    float3 F = Schlick_Fresnel(specularAlbedo, halfVec, lightDir);

    // Computes the shadowing from the microfacets.
    // Smith's approximation.
    float  G = G_Smith(Roughness, nDotV, nDotL);

    return D * F * G;
}

```

**EDIT** :

```
cbuffer cbPerFrame
{
    Light light;
    float pad0;
    float pad1;
    float pad2;
    float Roughness;
    float Metalness;
    float4 cameraPosition;
};

```

Have I packed my cbuffer structure correctly now? If not can you guys tell me what to do to fix it (I'm clueless). If it is packed correctly what is the problem then?!

# Answer
```
struct Light
{
    XMFLOAT3 dir;
    float pad;
    XMFLOAT4 ambient;
    XMFLOAT4 diffuse;
};

struct cbPerFrame
{
    Light  light;
    XMVECTOR cameraPosition;
    float Roughness;
    float Metalness;
};

```

Should be a match for HLSL:

```
struct Light
{
    float3 dir;
    float4 ambient;
    float4 diffuse;
};

cbuffer cbPerFrame
{
    Light light;
    float4 cameraPosition;
    float Roughness;
    float Metalness;
};

```
> 1 votes

---
Tags: c++, directx, hlsl, lighting
---


# Question
Title: Does anisotropic filtering need a previously generated mipmap?
I have a GPU which supports anisotropic filtering and a 1024x1024 soil texture. I would like to know, if I even need to create a mipmap when I am using anisotropic filtering or if I can just leave it out and only use anisotropic filtering.

I looked it up in some tuts and posts and each one had mipmapping enabled too, but they did not mention why.

I am not sure, but I think that I need a mipmap because I don't think that anisotropic filtering scales a texture from 1024x1024 to something like 512x512 or 256x256. Am I right?

# Answer
You don't need to enable mipmap for anisotropic filtering to work, but you should. Anisotropic filtering is an experimental feature on some GPUs, so the support rate is very low. To make sure the user gets close to the same experience as on other devices, you need both.
> 0 votes

---
Tags: opengl, textures, mipmaps
---


# Question
Title: Animating a texture growing & fading with a Unity 2D particle system
I've created texture which could represent a lightning orb. Is it possible to animate scaling of the texture to simulate this lighting burst? Like the orb is growing and than fades away.

Or do I need to make sequence of similar images and then animate it as particle system in Unity?

# Answer
As Dan said, your looking for the size over lifetime, and the color over lifetime can control opacity. Just keep tweeking the particle system, even if its just one particle
> 1 votes

---
Tags: unity, 2d, particles
---


# Question
Title: Capture High Resolution Screen Shot for Unity Game
I'm working on a mobile game. We need some HD screen shot to use in our **press kit**. I'd like to know, how do we capture HD screen shot of games inside **unity's editor**. Resolution **must support printing quality of banners** that we would use to showcase our game in local game expo.

# Answer
> 1 votes
According to this post on Unity Answers there are/were some issues with huge screenshots.

But they suggest using this (FREE) asset (Instant Screenshot) from the asset store. Give it a try and let us know if that works for you (and which resolution you created with).

---
Tags: unity, marketing, screenshot
---


# Question
Title: Calculate 8 different directional input based on arrow keys combinations
Considering I have `four variables` event binded to each `arrow key`, that can be `0` or `1`

My current approach to this issue is simply 8 nested ifs checking each combination or keys

Is there a more *math-y* clever way to solve this issue?

# Answer
> 6 votes
Given 4 variables `up` `left` `down` `right` with values zero or one, the simplest method is to define a 2-component direction vector `(dx, dy)` like so:

```
dx = right - left
dy = up - down

```

(No conditionals required!)

If you need more specialized logic/behaviour for each direction, I'd be inclined to do something like...

```
directionIndex = 3 * (up - down) + right - left;

```

Then the directions shake out like so:

```
-4 down-left
-3 down
-2 down-right
-1 left
 0 center / canceling
 1 right
 2 up-left
 3 up
 4 up-right

```

If you store an array of 9 direction vectors, you can add 4 to the index above to look up into your (zero-based) array, getting your direction in a single table lookup, again branch-free.

Or you could use this index as the control for a single switch-case statement, to do unique actions for each direction without more than one level of nesting. (Since I see you're asking about LÖVE, you can use a Lua analog of a switch like this)

# Answer
> 5 votes
A common method is to combine the opposite direction keys into a single axis, giving you X and Y movements, then you combine the X and Y into a single 2D movement vector.

Here's what that code might look like:

```
local dx,dy = 0,0
if (keyPressed.up) then dy = dy - 1 end
if (keyPressed.down) then dy = dy + 1 end
if (keyPressed.left) then dx = dx - 1 end
if (keyPressed.right) then dx = dx + 1 end

```

You need to decide a few things from here:

* What to do if the player presses opposite directions (e.g. left and right) together. The example given cancels them both out, but perhaps you want to have one override the other.
* If diagonals should be faster than single axis directions. If not, find a decent 2D vector library and use normalise.

This method has the advantage of being adaptable across different input devices. Gamepads for example will give you analog stick input as X and Y values between -1 and 1.

The code here is not too bad but still seems repetitive - there are four virtually identical `if` conditions. But you'll see a lot of code like this when dealing with 2D (or 3D) problems. It's possible to refactor this code to have less repetition but there's a tradeoff between math-heavy code that's non-obvious. You need to decide whether having less repetitive code that's harder to understand is worth it.

---
Tags: algorithm, input, love2d
---


# Question
Title: Unity C# - Rotate smoothly an object towards the direction given by input
I am trying to rotate an object towards the direction given by de direction of the input. For example, if I am pressing 'up' of the directional pad, the player should rotate pointing that direction.

I've tried using Euler angles, and when I press the direction, I call a coroutine that sums the `eulerAngle.y` of the object till it gets the angle of the direction, but it doesn't work. I don't know if there is another approach to use.

Here is the code for the coroutine. It starts if a certain key is pressed and if a flag is not activated:

```
 IEnumerator rotateTowards(float angle)
 {
    rotating = true;
    Debug.Log("Rotating the mono...");
    Debug.Log("Your angle: " +transform.eulerAngles.y);
    float turningTime = 0.8f;
    //float thisAngle = this.transform.eulerAngles.y;
    Vector3 thisAngle = this.transform.eulerAngles;

    if(thisAngle.y < angle)
    {
        while(thisAngle.y < angle)
        {
            thisAngle.y += turningTime * Time.deltaTime;
            this.transform.eulerAngles = thisAngle;
        }
    }

    if(thisAngle.y > angle)
    {
        while(thisAngle.y > angle)
        {
            thisAngle.y -= turningTime * Time.deltaTime;
            this.transform.eulerAngles = thisAngle;
        }
    }

    this.transform.eulerAngles = thisAngle;
    rotating = false;
    yield return null;
 }

```

Thanks in advance.

# Answer
> 2 votes
I don't see why you need a coroutine; I think you need `Quaternion.Slerp()`.

Unity give an example of what you want to do in its documentation.

# Answer
> 0 votes
Have you tried using Debug.Log statements in your code to make sure that your code is even running? Try putting a while(true) statement and then stopping the coroutine when it's done?

# Answer
> 0 votes
First, euler angles aren't precise, everything gets internal converted to quaternions, second Unity has some smoothing on the default input controls, third, u may know but i dont see it in your example, you need to sue StartCouroutine("Name"); to use an IEnumerator.

Ill give you an example of the simplest solution i found

```
Update(){
    float h=Input.GetAxis("Horizontal");//thies work with WASD or arrow keys + other things unity can use, gamepad etc..
    float v=Input.GetAxis("Vertical");
    if(v!=0||h!=0){// if we are getting inputs, form -1 to 1, 0=no input
        Vector3 direction=(Vector3.forward*h)+(Vector3.right*v);// as the key is held down the h or v values will move toward full -1 or 1, thus handling the smooth rotation
        transform.rotation=Quaternion.LookRotation(direction);
    }
}

```

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


title: Hold and swipe can't work together

text:
# Question
Title: Hold and swipe can't work together
I Have a character in my game that must go when player hold finger at the screen, but when I swipe character first go, and then do swipe. (for example jumping - character first go, and only then jump). This my code for touch:

```
 if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began)
        {
            startTime = Time.time;
            startPos = touch.position;
        }
        else if (touch.phase == TouchPhase.Ended)
        {
            endTime = Time.time;
            endPos = touch.position;
            swipeDist = (endPos - startPos).magnitude;
            swipeTime = endTime - startTime;

            if (swipeTime < maxTime && swipeDist > minSwipeDist)
            {
                swipe();
            }
        }
        else if (touch.phase == TouchPhase.Stationary && isTap == 0)
        {
           hold();
        }
    }

```

This my code for a hold:

```
  void hold()
{

        moveVelocity = 3f;

}

```

And for swipe:

```
void swipe()
{
    Vector2 distance = endPos - startPos;
        if (Mathf.Abs(distance.x) > Mathf.Abs(distance.y))
    {
           if (distance.x > 0)
        {
            Debug.Log("Right swipe");
        }
        if (distance.x < 0)
        {
           Debug.Log("Left swipe");
        }
    }
    if (Mathf.Abs(distance.x) < Mathf.Abs(distance.y))
    {
        if (distance.y > 0)
        {
            Debug.Log("Up swipe");
        }
        if (distance.y < 0)
        {
            Debug.Log("Down swipe");
        }
    }
}

```

**My question is**: When player swipe left character first go, and only then do swipe left. I want player swipe, without going forward. How can I do this?

# Answer
> 1 votes
it looks like you need to wait just a bit, and collect some position data where you call Hold, to make sure the player didn't intend to swipe.

Something like this:

```
endPos=touch.position;
swipeDist=(endPos-startPos).magnitude;
holdTime=endTime-startTime;
if(holdTime>minHoldTime&&swipeDist<holdThreshold)hold();

```

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


# Question
Title: How to move a object to a target point like sine wave in 2D world
I want to move my gameobject to move point A to target point B like sine wave, I have used Vector2.Lerp but its just straight line. so far I tried many ways and I managed this

```
//sine wave
vLastPos = new Vector2(transform.position.x , Mathf.Sin(Time.time)*2f+2f);
transform.position = vLastPos+Vector2.right*Time.deltaTime;

```

but the problem is its moving the gameobject left to right not to target position. the gameobject shold reach the target position and stop. please help me.

# Answer
I'm going to explain as much as I can to avoid more questions.

Let's begin from the simple linear motion. It's something like:

```
X = X + cos(angle)* distance * deltaTime;
Y = Y + sin(angle)* distance * deltaTime;

```

First of all, we're using trigonometry to find out how much we should move an object at the specific coordinate using Sin and Cos functions to convert it from the angle. Think of it as converting angle to a unit vector by finding projections to each coordinate axis.

Then we're multiplying the result to the distance to move from the origin (speed of the movement, actually) and multiplying to the time that got past from the previous frame to make movement independent from the framerate. Note that this action makes everything being measured in **units-per-second**. Last thing to explain is the angle, but I think Unity has methods to calculate angle between two points so it shouldn't be a problem.

Well, we got it moving to the desired point, what's next?

Let's modify the angle, here's how to do it:

```
X = X + cos(angle + sin(Time*speed)*amplitude)* distance * deltaTime;
Y = Y + sin(angle + sin(Time*speed)*amplitude)* distance * deltaTime;

```

This will make your object move to the desired point with a wavy behaviour, but note that speed will decrease amplitude because we're just rotating the angle and too big amplitude will make the object stay spinning at the same position being unable to move. This is what the resulting pattern looks like:

It is also able to home to your target:
> 5 votes

# Answer
You can use a parametric sine wave, combined with a rotation matrix equation:

```
var theta = some angle
var x = t
var y = amp * sin(t)
var xp = (x * cos(theta)) - (y * sin(theta));
var yp = (x * sin(theta)) + (y * cos(theta));
draw(xp, yp);

```

```
var cvs = document.getElementById('c');
var cxt = cvs.getContext('2d');

var cw = cvs.width / 2;
var ch = cvs.height / 2;

var theta = 0;
var amp = 10;

function Draw()
{
  cxt.beginPath();
  cxt.moveTo(cw, ch);
  for (var t = 0; t < 300; ++t)
  {
    var x = t;
    var y = amp * Math.sin(t / 5);

    cxt.lineTo(
      cw + (x * Math.cos(theta) - y * Math.sin(theta)),
      ch + (x * Math.sin(theta) + y * Math.cos(theta))
    );
  }
  cxt.stroke();
}

(function loop()
{
 cxt.clearRect(0, 0, cvs.width, cvs.height);
 Draw();
  theta += 0.01;

 requestAnimationFrame(loop);
})();
```

```
html {
  font-family: sans-serif;
}
canvas {
  cursor: default;
  -webkit-user-select: none;
  user-select: none;
}
```

```
<canvas id='c' width='300' height='300'></canvas>
```
> 1 votes

# Answer
To add variety to the answers, you could use an AnimationCurve to manually offset a position along a linear path, so you can get any shape wanted.
> -1 votes

---
Tags: unity, unityscript
---


# Question
Title: Making Bigger Touch Space in Node Using SpriteKit And Objective-C
I am trying to make simple game, but I have a problem. The node is too small. On iPhones with smaller screen size, the finger can't move it. On iPad and on simulator, however, the node can be moved due to larger sizes of the screens. Due to that, I know it's not the code that causes the issue.

Due to the fact that I am using this paddle image on many levels, I create it as separate file so I can implement it anywhere I want within the app.

Here is what I got:

**PaddleNode.m**

```
- (id)init
{
    return [self initWithName:@"paddle"];
}

- (id)initWithName:(NSString *)name
{
    self = [super init];
    if (self) {

        self = [PaddleNode spriteNodeWithImageNamed: @"board.png"];
        self.userInteractionEnabled = YES;
        self.name = name;
        self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.frame.size];
        self.physicsBody.dynamic = NO;
        self.physicsBody.usesPreciseCollisionDetection = YES;
        self.physicsBody.categoryBitMask = paddleCategory;
        self.physicsBody.collisionBitMask = emptyCategory;
        self.currentTouchValue = nil;
    }

    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.previousTouchesTimestamp = event.timestamp;
    for (UITouch *touch in touches) {
        self.currentTouchValue = [NSValue valueWithNonretainedObject:touch];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.currentTouchValue = nil;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches) {
        NSValue *key = [NSValue valueWithNonretainedObject:touch];
        if ([key isEqualToValue:self.currentTouchValue]) {
           CGPoint touchPoint = [touch locationInNode:self.scene];
           CGPoint movePoint = CGPointMake(self.position.x, touchPoint.y);

           if ([self withinParentFrame:movePoint])
               self.position = movePoint;
       }
    }
 }

 - (BOOL)withinParentFrame:(CGPoint)point
 {
    CGFloat offset = self.size.height / 2;
    if (point.y >= offset && point.y <= self.scene.frame.size.height - offset)
        return YES;
    else
        return NO;
 }

```

P.S. I am learning Objective-C by myself and English is not my first language. So, if it's OK, explain me like you would to little child.

# Answer
> 1 votes
Given that `PaddleNode` is a subclass of `SpriteKit Node`, what would be an important thing to do is to first set the `size` property when using `spriteNodeWithImageNamed:`:

```
self.size = self.view.scene.frame.size;

//Or, you could set it to somewhere else.
//Example:
//self.size = (CGSize){100.0f, 100.0f};

self = [PaddleNode spriteNodeWithImageNamed: @"board.png"];

```

Another part we'd need to do is to set its position, after having set up the size. The following is an example for positioning the node relative to its parent:

```
self.position = (CGPoint){CGRectGetMidX(self.scene.view.frame), CGRectGetMidY(self.scene.view.frame)};

```

---
Tags: sprites, ios, objective-c, spritekit
---


# Question
Title: Is it possible to use C++ in SDL for Android?
I have successfully compiled SDL for Android using the example, which uses C. Is it possible to use C++ too?

I am trying to port a C++ game which uses SDL 2 to Android.

If it is possible, how can I do this?

# Answer
> 1 votes
The principles are exactly the same:

1. you write your game in c++
2. create the cmake files to compile your project
3. hit ndk\_build

In general ndk\_build can compile both c and c++, so it doesn't really matter which one you choose. I've actually only used SDL2 bundled with c++ code and it compiles perfectly.

---
Tags: c++, android, sdl, c, porting
---


title: 2D pathfinding - finding smooth paths

text:
# Question
Title: 2D pathfinding - finding smooth paths
I was trying to implement a simple pathfinding, but the outcome is less satisfactory than what I intended to achieve. The thing is units in games like Starcraft 2 move in all directions whereas units in my case only move in at most 8 directions (Warcraft 1 style) as these 8 directions direct to next available nodes (they move from a tile to next neighboring tile). What should I do in order to achieve the result as in Starcraft 2? Shrink the tile size?

On the picture you can see a horizontal line of rock tiles being obstacles, and the found path marked as green tiles. The red line is the path I want to achieve.

# Answer
> 8 votes
For a good pathfinding algorithm, using A\* would probably be a good idea, however, for a simple game that doesn't require sophisticated, efficient, nor effective path searching, simply having the characters move toward a target by finding out the direction of the target should be sufficient.

You can do is generate a 'visibility graph'(what other points are visible from each point) from the vertices and then perform A\* on the graph. This works because the shortest path will always lie on the visibility graph.

Shrink the tile size may help you.

**Resources**

**Further Reading**

**EDIT :** I like @MarkusvonBroady's comment.

> "it is actually about path smoothing, not finding. The path found on the picture looks OK."

**Resources**

From @MarkusvonBroady

I have made a search, find the followings (those may help you)

# Answer
> 0 votes
Starting from one end of the raw path, say `path[0]`, you can remove `path[1]` if the segment formed by joining the points of `path[0]` and `path[2]` does NOT intersect any wall. Going further until the last segment will provide a simpler path.

This will not only smooth the path but also remove some useless points, like fire example, 3 consecutive segments of a straight line.

---
Tags: game-design, game-mechanics, path-finding
---


# Question
Title: How do I add cinematics to a Unity game with C#?
I'm trying to develop a 3D game, and want to know the best way to go about adding cinematic or cut scenes that are triggered by a players proximity to certain objects.

# Answer
It depends very much on the sort of cutscene you want to play.

If it's a pre-rendered video you're after, then you can create a Movie Texture and show that once a player has entered the specified trigger area. With this method it would just be enablinga plane once the player reaches a certain point, and then disable it again once the cut scene is finished.

If, on the other hand, you want to display a cutscene using your existing assets and cameras, then I'd recommend looking into the Cinema Director asset. It's a little pricey at $60, but I've been using it a while now and it's well documented and works nicely. With this method you'd need to direct the cutscene yourself, moving assets to the right point for the time frame you enter, and then play the cut scene once a player reaches a specified trigger.
> 2 votes

# Answer
Your actually asking two questions:

1. How do I show cinematics, and
2. How do I trigger things by proximity.

The easiest way to show a cinematic is to show a pre-rendered video on a plane. The harder way involves controlling the camera and characters through animation, but what is shown can be dynamic, and interactive rather than premade.

For proximity, you can use colliders as triggers, or do continues distance checks.

You should explore one aspect of your problem at a time, and see which solution best fits your situation.
> -2 votes

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


title: Texture not appears?

text:
# Question
Title: Texture not appears?
I make fat cube "fbx" with blender and export it to unity. this fat cube not allowed texture to appears ! i make a small cube by unity and texture pop-up ! What is wrong ?

# Answer
Your model is missing a UV-map and therefore materials cannot be assigned to it.

Unity provides decent documentation on what you need to do when importing models from modelling packages.
> 1 votes

---
Tags: unity, textures
---


# Question
Title: Implementing Valve's checkerboard rendering technique
I've been trying to implement Valve's VR checkerboard rendering technique (original document) and was wondering which way would be the best to proceed.

The thing is that I need to "abort" the execution of 2x2 blocks of fragments in a checkerboard pattern considering how GPUs work in blocks of pixels.

I've thought of several approaches which are the following :

* Discard fragments in the fragment shader using a condition like this one :

```
float mod2 = gl_FragCoord.x + gl_FragCoord.y;
float res = mod(mod2, 2.0f);
if (res == 0.0f)
   discard;

```
* Use the stencil buffer and write a checkerboard pattern on it using an image or such.
* Use some kind of clipping method where I have several quads in front of the camera forming a checkerboard pattern.

The first approach seems to be the worse because I have to branch and after, discard fragments. And considering the fact that GPUs work in blocks of 2x2 pixels, I need to find a way to abort block by block so that I don't get the fragment shader processed anyway (even with a discard). And I'm not even sure this would force a block to abort and skip the fragment shader.

The second method seems OK, but I'm not sure if there's a better way to do it. Would the fragment shader be processed anyway ?

The third seems to need to process more polygons which is not really a good idea I guess even though it does not require a lot of processing considering they would be simple quads.

What would be the most efficient method (listed here or not) for skipping these blocks ?

# Answer
> 1 votes
The answer is in the source you linked:

> Clip() 2x2 pixel quads as you render, or fill stencil or depth with a 2x2 checker pattern and render

and also

> Skip rending a checker pattern of 2x2 pixel quads to **match current GPU architectures**

In other words, it should work, theoretically, but you better test there is an actual increase of performance. I'd also expect `if` \+ `discard` to work, but just like the other methods, I'd want to test and verify first if it actually results in a performance increase.

---
Tags: opengl, rendering, glsl
---


# Question
Title: Stop animation from playing while waiting to destroy object
I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object?

**C#**

```
void Die(){
    GetComponent<Animation>().CrossFade(die.name);
    //If the current animation time is greater than 90% of the entire animation length, destroy the object.
    if(GetComponent<Animation>()[die.name].time > GetComponent<Animation>()[die.name].length * 0.9){
        StartCoroutine(RemoveBody());
    }
}

IEnumerator RemoveBody(){
    yield return new WaitForSeconds(5);
    Destroy(gameObject);
}

```

# Answer
> 1 votes
```
using UnityEngine;
using System.Collections;

public class Die : MonoBehaviour {
    public Animator anim;// Animator component
    public bool check;// Check animation is done
    public float DonePercent = 1;// 100% of the entire animation length.you can change it by 0.5f then %50 of the entire animation length.
    void Start() {
        anim = GetComponent<Animator>(); // access to animator component
        StartCoroutine (CheckIsDoneAnimation ()); // start coroutine
    }
    void Update(){
        check = anim.GetCurrentAnimatorStateInfo (0).normalizedTime > DonePercent && !anim.IsInTransition (0); // if animation is done by DonePercent
    }
    IEnumerator CheckIsDoneAnimation(){
            yield return new WaitUntil (() => check == true);
            print ("Works!");
        Destroy (gameObject);
    }
}

```

it didn't need coroutine I just show you how you can wait until work finish in coroutine.so you can check when animation finished then destroy object.

```
using UnityEngine;
using System.Collections;

public class Die : MonoBehaviour {
    public Animator anim;
    public float DonePercent = 1;
    void Start() {
        anim = GetComponent<Animator>();
    }
    void Update(){
        if(anim.GetCurrentAnimatorStateInfo (0).normalizedTime > DonePercent && !anim.IsInTransition (0)){
            print("works! without coroutine");
            Destroy (gameObject);
        }
    }
}

```

perhaps you ask me what is usage this "()=\>" you can know it on this link.

this is helpful about waituntil-waitwhile-in-unity

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


title: Roll a 6DOF camera to a plane direction

text:
# Question
Title: Roll a 6DOF camera to a plane direction
I've been working on a 6DOF camera that I want to be able to "align" to any walls orientation to make it feel like I'm standing on that wall.

I'm thinking it's a simple matter of finding the right amount needed between the current cameras rotation and the ground orientation and apply the difference in roll, but I'm terrible at vector math. Any help?

I use C# XNA Quaternion/Matrix/Vector3, but any pesudo math can do as thats what I'm struggling with.

Edit: I would also like this to work on spheres & cylinders, so I'd also need a way calculate the difference in pitch from changing from one vector to avoid making the camera feel like it looking upward if walking a step forward on top of a sphere for example.

# Answer
Turns out this was both easier and hard than I first realized. The simple answer to my question, of "rolling" a 6DOF cameras feet onto any normal, was quite simple. It can be aligned to any planar/spherical/cylindrical vector as follorws:

```
Roll(Vector3.Dot(currentDirection, alignmentVector));

```

But to achieve a camera that can truly latch on to any of these types of surfaces, we'd also need to make sure movement went along these planes as well as move the Yaw and Pitch to compensate for the movement, and this is something that requires quite a bit more calculations, which I found an answer to here. I've yet to implement this solution in my C# XNA environment tho, so if anyone has any help om this that would be greatly appreciated.

This does in a way answer my own question, however it doesn't solve my greater problem, so if anyone has a better solution or an implementation of DMGregory's suggestion for C#, I will mark that as the answer instead of this.
> 0 votes

---
Tags: c#, xna, rotation, vector, quaternion
---


# Question
Title: For best practice, which "glTexParameters" should I set when creating a texture?
For best practice, which `glTexParameters` should I set when creating a texture?

I am already using a mipmap and anisotropic filtering, but I am not sure if this is enough for each texture or if I should also define some parameters for magnifying and minimizing (i.e. `GL_TEXTURE_MIN_FILTER`, `GL_TEXTURE_MAG_FILTER`, etc).

I am creating a texture for a simple game engine I am writing.

# Answer
> 3 votes
There's no best practice for this; instead you set the parameters according to the needs of your program.

There are certain technical requirements which will depend on the capabilitis of your OpenGL implementation, so I would suggest reviewing the glTexParameter documentation where the requirements for each parameter are discussed.

One I will highlight is that if you are using a GL\_TEXTURE\_MIN\_FILTER with one of the MIPMAP options in it, you must have also specified a full mipmap chain when specifying the texture.

A common mistake is that the initial value of GL\_TEXTURE\_MIN\_FILTER is GL\_NEAREST\_MIPMAP\_LINEAR, so if you (1) don't specify a full mipmap chain, but also (2) don't specify a GL\_TEXTURE\_MIN\_FILTER without mipmaps, you'll have an invalid combination of state.

Personally I would recommend using glTexStorage and sampler objects instead of glTexImage and texture parameters. glTexStorage will help you avoid accidentally creating incomplete textures, and sampler objects are more flexible in that they decouple these states from the texture object.

---
Tags: opengl, textures
---


title: Loading Song in MonoGame Windows

text:
# Question
Title: Loading Song in MonoGame Windows
I cannot load the song into my game. I got error in both templates WindowsDX and WindowsGL. Monogame Develop Build 1252

Both files .wma and .xnb are exist in Content folder and Build Actions are sets to Content, and Copy Always to output dir. Checked with mp3/ogg too but with no result.

The Song works perfect with XNA, and with MonoGame I cannot load any song.

Edit SOLVED: The newest build 1478 solved the problem

DX

GL

# Answer
> 1 votes
As the error states, You may be pointing to the wrong directory, file, or type of file.

Make sure to Add the song to game content by Right-Clicking on your designated Content Folder \>\> Existing File \>\> Select the File.

Make sure that your audio is supported by the Content Pipeline : http://rbwhitaker.wikidot.com/managing-content.

Verify that the File Name is the same.

# Answer
> 0 votes
This is a problem(or feature?) of Monogame where you have to specify the file type for audio because both files are generated in the Content Builder. I believe it is .ogg for music and .wav for SFX. You can check the file types in the built content folder(default: Content).

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