# Question
Title: How to find path in graph without crossing the walls?
I would like to know how to find path in a graph while having the edges "double-sided". Consider this scenario:

I have list of the line segments. These represents "walls" or rather impassable edges (in a game). I then plan in a next step to build a connected graphs (where possible). I'm trying to determine the feasibility at this point. If there's even a solution to this (it should in my opinion).

I don't need to know about A\* or other algorithms per se, but rather how to not walk through the walls as seen in figure B. Any ideas?

I was wondering if I could turn segments to polygons (by adding width). Then make an union of these polygons and then treat them rather as polygons. But I would like to know whether there is a way to do it without this hassle. Also I'm not sure I want to add any width to the lines necessarily.

# Answer
The problem is with how you are formulating your navigation graph. If you'll allow me to butcher your diagram:

Here is what the navigation graph should look like. For each node in the original graph with **n** edges, where **n \> 1**, it should be replaced with **n** nodes. (Notice that each node in the graph is connected by two edges.)

Inserting start and end nodes is a little more tricky. I'd probably start by giving each edge in the updated graph a normal, so you can determine which edges are facing towards the point you wish to insert. The nodes connected to such edges would then be candidates to connect to your inserted nodes.

Once you have the correct graph, you can apply the usual navigation algorithms like A\*.
> 15 votes

# Answer
You're misrepresenting your graph. What you really have is something more like this:

Where the red dots are your nodes, and the blue lines are your edges. This can be produced by creating four nodes for every node in your current graph. (There are actually even more edges that would be valid here as you could move diagonally between a number of these nodes.

The original graph can be used to ensure that the new edges don't cross any of your old edges, but it can't really be used for pathing as it is.
> 5 votes

# Answer
**Update solution**: Even though I was inspired by Andrew Russell's solution. For anyone interested. I've solved it in the end as such.

* **1**) I first detect intersection (point I) with graph (or multiple graphs afterwards).
* **2**) Then I find point in angle higher than angle from an incoming point (Intersection -\> Start). Such point is marked yellow. I'm only concerned with points connected to one currently being processed + start/end point. If left-most angle point is end point, we're done.
* **3-6**) Left-most points are processed and slowly the path around left side of the walls is constructed. This is very fast because no change in structure is needed. Only angle calculation for few points.
* **7a**) Now I gathered the left part. I can now do the same (from point 1) and walk around the right side (right-most angle) this time.
* **7b**) I have now left solution and right solution. The shorter one is my final solution.

If somehow I would end-up at start point as my left-most (right-most respectively), in that case there exists no actual solution.

**Note**: The main advantage is that no graph recreation is needed, and it works on existing structure. Also it doesn't need no other path-finding graph algorithm.

Still again thanks to Andrew Russell for giving me that aha! moment. ;)
> 2 votes

---
Tags: c#, path-finding, graph, lines
---


# Question
Title: Dynamic Flow Control in HLSL with Array References
I'm trying to do lighting calculations for an array of point lights in HLSL. I simply want to pass light direction vectors from the vertex shader to the pixel shader. Here is sample code:

```
static const int MAXLIGHTS = 8;
float4 g_vLightPosition[MAXLIGHTS];
float4x4 mW : WorldTransform; // model to world
float4x4 mV : ViewTransform; // world to view
float4x4 mP : ProjectionTransform; // view to project

void VS_Lighting( in float4 PositionMS : POSITION0,
out float4 PositionCS : POSITION0,
out float4 Texcoord[MAXLIGHTS] : TEXCOORD )
{
    // view-projection
    float4x4 mVP = mul(mV, mP);

    // world position
    float4 vPosWS = mul(PositionMS, mW);

    // clip space pos
    PositionCS = mul(vPosWS, mVP);

    // compute light direction vectors
    for(int i = 0; i < g_nLightCount && i < MAXLIGHTS; ++i)
    {
        Texcoord[i].xyz = g_vLightPosition[i] - vPosWS;
    }
}

```

The above code forces the loop to unroll and gives the following warning:

> warning X3550: array reference cannot be used as an l-value; not natively addressable, forcing loop to unroll

I would like for this code to be dynamic so as to reduce the instruction count. I understand that the problem is accessing the array in the loop. How can I rewrite this code to prevent unrolling during compilation? I am using ps 2.0 or 3.0.

# Answer
You can't rewrite that loop so that it can't be unrolled. GPUs do not in general support a varying number of attributes to be passed between stages.

You can, however, eliminate the loop entirely. Just pass vPosWS to the fragment shader, and do the loop there. Then the unrolling will actually be helpful.

Bonus: You don't waste an **absurd** amount of bandwidth transmitting all those relative light vectors between stages just to save a few subtractions in the pixel shader. You also get per pixel lighting, rather than per vertex.
> 1 votes

# Answer
Unroll. The instruction cost is minimal - just a subtraction! You can try and put "\[unroll\]" (without quotes) just above the "for" line, or just unroll manually, but, really, unroll. You won't even have the comparison instruction for the for loop check.
> 1 votes

---
Tags: c++, shaders, hlsl, directx9
---


title: Class design for a risk-like game

text:
# Question
Title: Class design for a risk-like game
I'm currently coding a AI for a risk-like game, but I'm not sure how I put even the base classes together. I've read a lot about game design patterns, entity component designs and such, but I've trouble translating it to an actual architecture of my own.

My original layout feels weird, I have too many reference cycles and store most objects in multiple places. I know how to remove those, but that would make it (in my mind) a lot more complicated to get simply lists, for example the amount of Units a player possesses, or which units are in Zones next to the current one.

I had a bit more classes and something that kinda worked, but it was a mess and worse than this design. I wanted to start over and design it right. I feel really dumb having problems that should be much more easier to solve. And I wouldn't even know how to begin plugging in the AI.

# Answer
> 1 votes
Right off the bat I think your units don't need neighbours.

Zones should hold neighbouring zones but I would likely add a class called a zoneEdge that contains two pointers one for each zone sharing the edge. Each zone would hold a list of edges. Walking the edges would get the neighbouring zones. When it comes to pathfinding this will really help.

Zones should store references to the units in them somehow be ita list or some other structure. For example if each zone has an id and each player has a dictionary where the key is the zone id and the value is a list of units the player owns in that zone you can reasonably get all the units for a player in a zone and move them to other zones without having to mess with sorting and filtering lists of mixed user units.

A game needs access to all these things. One important thing to remember is that experience makes these things clearer. Don't get paralyzed trying to find the best solution before starting. Get in there and see what works. Only you will know the pitfalls your specific game has.

---
Tags: architecture, design-patterns
---


title: Animation, Interpolation, & Structure

text:
# Question
Title: Animation, Interpolation, & Structure
I have been working on animation in my small game engine recently and I am implementing some interpolation to be used with skeletal animations. I know how to do interpolation but I am not sure where to put the equation that I get out of it.

Do I save an equation for each channel of every bone in the data structure? Maybe something along the lines of:

```
struct Channel
{
    std::string boneName;
    std::vector<KeyFrame> keyframes;

    // These equations will be used to find the position/rotation/scale of
    // the bone at t time.
    std::vector<float> rotEqX, rotEqY, rotEqZ;
    std::vector<float> translateEqX, translateEqY, translateEqZ;
    std::vector<float> scaleEqX, scaleEqY, scaleEqZ;
};

```

Do I just calculate the equation every time I want to update the animation? (Seems a little inefficient?)

# Answer
I'm not sure what you mean 'these equations'. I think you mean the inputs into equations.

I would store rotations as quaternions (x,y,z,w) as mentioned. Interpolating from a key-A to key-B would use a slerp or nlerp function (http://keithmaggio.wordpress.com/2011/02/15/math-magician-lerp-slerp-and-nlerp/).

Translation is stored as x,y,z and uses a simple linear interpolation.

Scale is stored as x,y,z and also use a simple linear interpolation, although in hierarchical animation non-uniform scale is a complicated matter often requiring the squash/stretch rotation to know in what coordinate space the scale is to be applied.

Once you have that working, you can investigate various forms of compression and key frame reduction to reduce the cost. For example, keep track of which bones have identify scale (1,1,1) or no translation (0,0,0) and store flags to avoid performing calculations for those bones. This might be per skeleton, or per animation used on a skeleton. If a bone has a rotation that is consistent for the whole animation, just store it once. You can also store data quantized at a lower precision to get better compression.

Here's an article about different techniques:

http://www.digitalrune.com/Support/Blog/tabid/719/EntryId/131/Character-Animation-Compression.aspx
> 1 votes

---
Tags: c++, directx, animation, directx11, skeletal-animation
---


# Question
Title: How can I fix user input for this pong paddle?
I have been having trouble with my pong paddle - It responds to user input as if it was typing.

> Sometimes, people try to react to KeyPressed events directly to implement smooth movement. Doing so will not produce the expected effect, because when you hold a key you only get a few events (remember, the repeat delay). To achieve smooth movement with events, you must use a boolean that you set on KeyPressed and clear on KeyReleased; you can then move (independently of events) as long as the boolean is set. The other (easier) solution to produce smooth movement is to use real-time keyboard input with sf::Keyboard (see the dedicated tutorial). - http://sfml-dev.org/tutorials/2.1/window-events.php

**I would like to figure out the 2nd option to keep my code neat. What should I be doing differently to achieve this?** I already visited the tutorial, dug around in the docs for a while, and Googled it, but such things seem to be futile (am I missing something obvious?).

My Ball Move code (in the event loop):

```
float deltaTime = deltaTimer.restart().asMilliseconds();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
            {
                playerPaddle.move(0 , -paddleSpeed * deltaTime);
            }

```

My full code:

```
#include <SFML/Graphics.hpp>

int main()
{
 sf::RenderWindow window(sf::VideoMode(600, 400), "Pong");

bool isPlaying = true; //set to true only for debugging
int spacing = 3; // the distance from edge of board to paddle.
int paddleSize = 90;
float paddleSpeed = 0.1;

sf::Clock deltaTimer;
//load the background sprite
sf::Texture backgroundTexture;
backgroundTexture.loadFromFile("assets/images/Background.png");
sf::Sprite background;
background.setTexture(backgroundTexture);

sf::RectangleShape paddle(sf::Vector2f(10,paddleSize)); //10*90 rectangle
paddle.setFillColor(sf::Color(128,128,128));
paddle.setPosition(spacing,0);

sf::RectangleShape playerPaddle(sf::Vector2f(10,paddleSize)); //10*90 rectangle
playerPaddle.setFillColor(sf::Color(128,128,128));
playerPaddle.setPosition(window.getSize().x - playerPaddle.getSize().x - spacing , 0 );

sf::RectangleShape pongBall(sf::Vector2f(10,10));
pongBall.setFillColor(sf::Color(200,200,200));
pongBall.setPosition(20,20);

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
                window.close();
        }

        if (isPlaying)
        {
            float deltaTime = deltaTimer.restart().asMilliseconds();
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) //sf::Keyboard::isKeyPressed(sf::Keyboard::Up)
            {
                playerPaddle.move(0 , -paddleSpeed * deltaTime);
            }
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
            {
                playerPaddle.move(0 , paddleSpeed * deltaTime);
            }

            if (playerPaddle.getPosition().y < 0 )
            {
                playerPaddle.setPosition(playerPaddle.getPosition().x , 0);
            }
            else if (playerPaddle.getPosition().y > window.getSize().y - paddle.getSize().y )
            {
                playerPaddle.setPosition(playerPaddle.getPosition().x , window.getSize().y - paddle.getSize().y );
            }
        }
        else
        {

        }
    }

    window.clear(sf::Color::Black);
    //window.draw();
    window.draw(background);
    window.draw(paddle);
    window.draw(playerPaddle);
    window.draw(pongBall);
    window.display();
}

return 0;

```

}

# Answer
You are blocking on pollEvent. window.PollEvent is for handing events, not your draw loop. Since you are looking at the keypresses every frame, you can't do it in the event handling - it is only trigger on the actual keypress events (which you are now ignoring, which is fine). Move it into the draw loop.

Take a look at this sample:

http://www.sfml-dev.org/tutorials/2.1/graphics-draw.php#the-drawing-window

Good luck!
> 1 votes

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


title: Game Background graphics blurred edges?

text:
# Question
Title: Game Background graphics blurred edges?
Why when using this code for the background for my game do I receive blocks with blurred edges?

```
public final class State_Play extends State_Template {
    private BufferedImage background;
    private int[] pixelelements;
    private int width,height;

    State_Play(){
        init();
    }

    public void init(){
        width=8; //Configuration.appwidth,
        height=6; //Configuration.appheight
        background=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        pixelelements=((DataBufferInt) background.getRaster().getDataBuffer()).getData();
        maketuringarray();
    }

    public void maketuringarray(){
       int singlecolor=new Random().nextInt();
       pixelelements[new Random().nextInt(width*height)]=singlecolor | 0xFF000000;
    }

    @Override
    public void update() {
       maketuringarray();
    }

    @Override
    public void render(Graphics g) {
        g.drawImage(background, 0, 0, Configuration.appwidth, Configuration.appheight, null);
    }

```

Like this

# Answer
> 1 votes
Most likely it is antialiasing the image, in an attempt to avoid looking pixelated. If you have a `Graphics2D` called `g2`, then you can modify the settings:

```
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
      RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

```

The abstract `Graphics` class does not have this method, but the `Graphics` object you have likely is a `Graphics2D` internally.

# Answer
> 1 votes
It looks like you are first rendering the buffered image with bilinear interpolation and the result is later stretched with nearest neighbor filtering. It's hard to say without seeing the rest of the rendering code.

When I copied your code and used it to fill the background of a JFrame, I got either large solid color quads or fully smooth image depending whether I used `VALUE_INTERPOLATION_NEAREST_NEIGHBOR` or `VALUE_INTERPOLATION_BILINEAR` as the interpolation rendering hint.

---
Tags: java, graphics
---


title: Framerate dependent movement

text:
# Question
Title: Framerate dependent movement
I'm moving my character controller using Euler integration like this:

```
Vector3 originalPos = transform.position;
Vector3 acceleration = Physics.gravity;
velocity += acceleration * Time.deltaTime;
characterController.Move(velocity * Time.deltaTime);

```

This works consistently on different framerates. I also implemented simple rope physics by pulling the controller back when its outside the radius. I then (on the same frame) calculate the new velocity from the new and old positions.

```
if (outsideOfRadius)
    Vector3 newPos = anchorPos + (transform.position - anchorPos).normalized * ropeRadius;
    Vector3 oldPosition = transform.position;
    characterController.Move(newPos - oldPosition);
    velocity = (newPos - originalPos) / Time.deltaTime;
}

```

This is the problematic part because it behaves significantly different on different framerates. This causes problems when my character controller lets go of the rope and tries to land on a platform. The distance covered on 30 fps is less than on say 60 fps or higher.

Is there a way I could make this work more consistently across different framerates?

# Answer
Movement should never be dependent on framerate. Bob Nystrom wrote an excellent summary of how to write a game loop that is independent of framerate. Check it out here. He starts with the most basic game loop then makes incremental improvements, discussing the motivation behind each iteration.

I've added his code here but you should really check the article out because you will learn a lot.

```
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag >= MS_PER_UPDATE) {
    update();
    lag -= MS_PER_UPDATE;
  }

  render();
}

```

In order to benefit from higher framerates what you do is pass the lag to the render function which extrapolates the movement that has probably occurred between updates. This makes the motion smoother and allows better machines to benefit from a higher framerate while maintaining a fixed update rate. This is discussed in-depth in the same game loop article I linked to earlier.
> 1 votes

# Answer
You need to separate your games logic from display logic.

Game logic should run at some fixed rate (e.g. 100 ms). Display should query the state of the game and display it at unconnected rate (e.g. 10-20 ms).

That way your display performance never affects the game.
> 1 votes

---
Tags: c#, unity, physics, movement, frame-rate
---


# Question
Title: Is there any harm in having the main game loop run uncontrolled?
I was wondering if there is any possible harm when my game loop runs as fast as the system allows?

I currently have a loop, that, by measuring passed time in nanoseconds, runs the game logic and rendering logic at predefined speeds without a problem. In fact any logic I do in the loop is clocked to a certain amount of calls each second.

The loop itself though just runs about as fast as it likes to which comes up to around 11.7 million loops a second on my machine.

Loop (simple pseudocode):

```
while(!isGameOver){

 if(canPollInputs){
    pollInputs()
 }

 while(canStepLogic){
    stepLogic()
 }

 if(canRender){
    render()
 }
}

```

My question is basically if that simple loop, if its not running at a controlled speed, can do any harm to a system?

Edit: That means my logic is running 30 times a second (30 tps), my renderer is running at 60 fps, I'm polling inputs a 100 times a second and there's also some logic to cope with logic or rendering taking longer than expected. But the loop itself is not throttled.

Edit: Using `Thread.sleep()` to e.g. Throttle the main loop down to 250 loops per second leads to a reduction but the loops runs at around 570 loops per second instead of the desired 250 (will add code when I'm at my desktop machine..)

Edit: Here we go, a working java gameloop in order to clarify things. Also feel free to use it but don't claim it yours ;)

```
private void gameLoop() {

    // Time that must elapse before a new run
    double timePerPoll = 1000000000l / targetPPS;
    double timePerTick = 1000000000l / targetTPS;
    double timePerFrame = 1000000000l / targetFPS;
    int maxFrameSkip = (int) ( (1000000000l / MINIMUM_FPS) / timePerTick);

    int achievedPPS = 0;
    int achievedFPS = 0;
    int achievedTPS = 0;

    long timer = TimeUtils.getMillis();

    int loops = 0;

    int achievedLoops = 0;

    long currTime = 0l;
    long loopTime = 0l;

    long accumulatorPPS = 0l;
    long accumulatorTPS = 0l;
    long accumulatorFPS = 0l;

    long lastTime = TimeUtils.getNano();

    while(!isRequestedToStop) {
        currTime = TimeUtils.getNano();
        loopTime = currTime - lastTime;
        lastTime = currTime;

        loops = 0;

        accumulatorPPS += loopTime;
        accumulatorTPS += loopTime;
        accumulatorFPS += loopTime;

        if(accumulatorPPS >= timePerPoll) {
            pollInputs();
            playerLogic();
            achievedPPS++;
            accumulatorPPS -= timePerPoll;
        }

        while(accumulatorTPS >= timePerTick && loops < maxFrameSkip) {
            tick();
            achievedTPS++;
            accumulatorTPS -= timePerTick;
            loops++;
        }

        // Max 1 render per loop so player movement stays fluent
        if(accumulatorFPS >= timePerFrame) {
            render();
            achievedFPS++;
            accumulatorFPS -= timePerFrame;
        }

        if(TimeUtils.getDeltaMillis(timer) > 1000) {
            timer += 1000;
            logger.debug(achievedTPS + " TPS, " + achievedFPS + " FPS, "
                    + achievedPPS + " Polls, " + achievedLoops + " Loops");
            achievedTPS = 0;
            achievedFPS = 0;
            achievedLoops = 0;
        }

        achievedLoops++;
    }
}

```

As you can see there is almost no code run on each loop but always a certain selection based on how much real time has passed. The question is referring to that 'worker loop' and how it does influence the system.

# Answer
It will cause one CPU core to always run on 100%. This usually doesn't cause any *harm* to the system. CPUs are designed to run on 100% for hours. But on a mobile device it will drain the battery quickly and heat up the device, which will likely cost you about a stars in your store ratings. On a desktop computer this is less of a problem, but it will consume more of the users electricity, causes the CPU fan to spin faster which might cause some noise and waste CPU cycles which could otherwise be used by other processes. While these are not critical defects, they are still bad style, so you should avoid them when possible.

You didn't say anything about how your game logic loop works internally, but when you are using the delta-time approach (each calculation you are doing takes the time since the last call into account), you are dealing with very small delta-time values. This means you can run into problems with floating-point inaccuracy which can cause all kinds of strange behaviors. Also, the resolution of the system timer is often limited, so when your logic loop is too fast, you can get a delta-t value of zero, which then might cause a division by zero resulting in a crash.

To mitigate this problem, you should limit your framerate (graphic and logic) to the maximum of what the human eye can perceive. How much that is is disputed and depends on the kind of animation and on what kind of display it is shown, but estimations range from 40 FPS to 120 FPS. That means you need to set a minimum time of execution of each loop between 20ms and 8ms. Should a loop iteration finish faster, let the cpu thread `sleep` for the remaining timespan.
> 34 votes

# Answer
You're wasting CPU cycles. That means lower battery time on notebooks, tablets and phones, higher electricity bills, more heat generated by the machine, noisier fans. Also, you may be eating cycles from other important system processes (e.g. the window server could become jerky), which could then affect gameplay. Some system schedulers on today's pre-emptive multitasking systems also penalize applications that use too many cycles, so you may be fast first, then suddenly see strange jerkiness when you're throttled by the system.

Many hardcore gamers also build custom PCs from scratch that are at the edge of their fan's specs, in which case a hot day and the heat your game generates may cause the safeties to trigger in the machine (at best) or even make parts overheat and die (at worst). So if that's your target audience, you may want to ensure you're always leaving a bit of space "at the top".

Finally, there are gameplay issues where you might be advantaging players with faster machines over those with slower ones. Having the game loop capped at a certain frequency and using additional cycles solely for non-gameplay-relevant aspects (like rendering higher fidelity graphics, surround sound effects or whatever) will make your game more fair.
> 2 votes

# Answer
## You shouldn't have jittery movement / gameplay

There are two ways that you can implement game logic - tied to a real time, or tied to the number of "turns"/processing steps. If some thingy in your game is moving leftwards, will it's motion be different if your stepLogic() was called 100 instead of 50 times?

If your code treats the elapsed time explicitly everywhere and does it correctly, then it might be okay; but if there's anything in your code that depends on the number of 'steps' then you'll get unwanted side-effects.

First, the speed of things that should be moving constantly will vary unpredictably (depending on processor usage), and this makes for very annoying controls - you can't make a precise punch or a jump if suddenly the game speeds up or slows down. Even for games with no 'twitch' at all, it looks annoying and jittery if things aren't moving smoothly.

Second, you might get problems with character abilities depending on the computer speed - a classic example is the old Quake issue where the maximum jumping range was unintentionally dependent on your fps.

These issues may appear even if you try to have the code to be fps-independent, accumulation of rounding errors can often cause such bugs.
> 1 votes

# Answer
The only potential harm is to your power consumption, so don't do this on mobile devices. Conversely, quite a few embedded systems spend their entire lives in a loop waiting for things to happen.

It used to be entirely normal to simply render game frames as fast as possible, sometimes without even a timer to compensate gameplay for different CPU speeds. Bullfrog's racing game Hi-Octane was a particularly bad victim of this, and I suspect this is what the poster mentioning Civ2 is referring to.

I'd advise you to at least poll inputs on every pass if you're on a Windows system or similar, to ensure snappy input response.
> 1 votes

---
Tags: java, game-design, performance, game-loop
---


title: How to draw a curved line in Box2d?

text:
# Question
Title: How to draw a curved line in Box2d?
I need to draw a curved line, I have searched the Internet but found nothing that would suit my needs.

I used `b2ChainShape` but it's not completely what I need.

How can I draw a curved line with Box2d?

# Answer
> 1 votes
You should use b2EdgeShape.

I used this tutorial to achieve a curved collisioning line in Box2D Cocos2dX (the tutorial is in ObjectiveC - C++, but it will give you the idea).

But at the end, it's making little rects making a bigger line that simulates a curved line:

```
b2BodyDef bd;
bd.position.Set(0, 0);

m_body = m_world->CreateBody(&bd);

b2EdgeShape shape;

b2Vec2 p1, p2;
for (int i=0; i<m_nBorderVertices-1; i++) {
    p1 = b2Vec2(((m_borderVertices[i].x  - winSize.width/2)/PTM_RATIO), ((m_borderVertices[i].y - winSize.height/2)/PTM_RATIO));
    p2 = b2Vec2(((m_borderVertices[i+1].x - winSize.width/2)/PTM_RATIO) ,((m_borderVertices[i+1].y - winSize.height/2)/PTM_RATIO));
    shape.Set(p1, p2);
    m_body->CreateFixture(&shape, 0);
}

```

---
Tags: java, box2d
---


title: Getting a color value from a coord

text:
# Question
Title: Getting a color value from a coord
My goal is to get a RGB value of a pixel based of off a X,Y coordinate.

I have been working on AIs for a small project attempting to make a bot that can pass through a maze. I want to get the pixel color in front of the bot to test if it is a wall or not. I have no example code because i don't know exactly where to start.

# Answer
Use:

```
pygame.Surface.get_at(x,y)

```

to get a pixel RGBA value.

http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get\_at
> 1 votes

# Answer
```
mouse_x,mouse_y = pygame.mouse.get_pos()
color = some_surface_object.get_at((mouse_x,mouse_y))

```

will return array \[0=\>R, 1=\>G, 2=\>B\] in demical values \[122,25,224\]
> 0 votes

---
Tags: python, pygame, color, pixel
---


# Question
Title: Must all AI states be able to react to any event?
FSMs implemented with the State design pattern are a common way to design AI agents. I am familiar with the State design pattern and know how to implement it.

How is this used in games to design AI agents?

Consider a simplified class `Monster`, representing an AI agent:

```
class Monster {
    State state;
    // other fields omitted

    public void update(){ // called every game-loop cycle
        state.execute(this);
    }

    public void setState(State state){
        this.state = state;
    }

    // irrelevant stuff omitted
}

```

There are several `State` subclasses implementing `execute()` differently. So far, classic State pattern.

AI agents are subject to environmental effects and other objects communicating with them. For example, an AI agent might tell another AI agent to attack (i.e. `agent.attack()`). Or a fireball might tell an AI agent to fall down. This means that the agent must have methods such as `attack()` and `fallDown()`, or commonly some message receiving mechanism to understand such messages.

1. With an FSM, the current State of the agent should be the one taking care of such method calls - i.e. the agent delegates to the current state upon every event. Is this correct?
2. If correct, how is this done? Are all states obligated by their superclass to implement methods such as `attack()`, `fallDown()` etc., so the agent can always delegate to them on almost every event? Or is it done in some other way?

# Answer
I would probably try and keep everything that changes the agent's attributes *with* the agent (`decreaseHealth`) and split the involved behaviour into several FSMs (`animation`, `combat`, etc).

IE: the agent has a method `getHit` that is somehow called when the agent gets hit (by the physics system, other agents, fireballs, etc).

Other FSMs can register to be informed when `getHit` is called. For example the combat system, which would then change state: if the agent has a shield or protection spell, reduce it's value and change to 'defensive' state, if not call `decreaseHealth` directly on the agent and go to 'suppressed' state.

Other FSMs would register to be informed when `decreaseHealth` is called: The sound-system would change from 'talking' to 'screaming' state, the animation-system would change from 'play running animation' to 'play falling down animation' state, etc.
> 1 votes

# Answer
I think this situation would benefit from a **Hierarchical State Machine** which is the type I use in my games to solve this problem.

Some links:

A hierarchical state machine (HSM) is a state machine where states are grouped together and have parent states. Therefore grouped states can all react to events collectively to produce behavior that is general for a specific set of states. For example I'm currently working on a generic ground based movement script for my game, the 'Legs' component supplies the states:

* grounded
    + standing
    + walking
    + running
* airborne
    + jumping
    + falling

etc...

You can see that some states are substates of others, in this way if the actor entity receives an event such as 'jump' and it is in the ground state (which is to say that it is in any of the states: standing, walking or running) it will transition to the jumping state. A similar event could occur for something only applicable to the airborne state.
> 0 votes

---
Tags: ai, design-patterns, fsm
---


# Question
Title: Executing Components in an Entity Component System
Ok so I am just starting to grasp the whole ECS paradigm right now and I need clarification on a few things. For the record, I am trying to develop a game using C++ and OpenGL and I'm relatively new to game programming. First of all, lets say I have an Entity class which may have several components such as a MeshRenderer,Collider etc. From what I have read, I understand that each "system" carries out a specific task such as calculating physics and rendering and may use more that one component if needed. So for example, I would have a MeshRendererSystem act on all entities with a MeshRenderer component. Looking at Unity, I see that each Gameobject has, by default, got components such as a renderer, camera, collider and rigidbody etc. From what I understand, an entity should start out as an empty "container" and should be filled with components to create a certain type of game object. So what I dont understand is how the "system" works in an entity component system.

http://docs.unity3d.com/ScriptReference/GameObject.html

So I have a GameObject(The Entity) class like

```
class GameObject
{
public:
    GameObject(std::string objectName);
    ~GameObject(void);
    Component AddComponent(std::string name);
    Component AddComponent(Component componentType);
};

```

So if I had a GameObject to model a warship and I wanted to add a MeshRenderer component, I would do the following:

```
warship->AddComponent(new MeshRenderer());

```

In the MeshRenderers constructor, should I call on the MeshRendererSystem and "subscribe" the warship object to this system? In that case, the MeshRendererSystem should probably be a Singleton("shudder"). From looking at unity's GameObject, if each object potentially has a renderer or any of the components in the default GameObject class, then Unity would iterate over all objects available. To me, this seems kind of unnecessary since some objects might not need to be rendered for example. How, in practice, should these systems be implemented?

# Answer
> 1 votes
Another approach is to register your subsystems with the game object system. During registration, they provide component configuration parameters that identify what components must exist to consider an entity of interest during it's update pass.

Now you simply create your entities and associate components to them. These entities by default are inactive and not in the world simulation. Once they've been created with all their settings, you ask the game object system to *activate* the entity. During activation, the system registration configuration is compared to that of the entity and if a system's component needs are met, the entity is added to that system's view. You can send out events during this phase to inform systems of new entities so they can create internal resources for their update tick when it gets called.

Now during the update pass for each system, the system is presented with a list of entities to operate upon. The beauty of this is that components do not know of systems and the systems simply don't care how the components came into existence, just that they exist.

One of the main things I have come to like is keeping components and systems separate, particularly around lifetime management. Naturally systems need to know when they come and go for various reasons, but because components are often of interest to more than one system, it makes sense that their construction/destruction and storage be handled independently from systems.

# Answer
> 1 votes
Unity's Entity-Component-System implementation isn't an ideal model on which to base a custom ECS. Unity favors ease of use over strict adherence to the ECS paradigm and made lots of trade-offs to serve that end.

Where Unity falls short of a pure ECS is the lack of separation between data and logic. In a pure ECS components contain only data and the logic that operates on them live in separate systems. However, to facilitate GUI based data-binding, Unity's components have update methods with logic that operates on that component's data. One might think, "Well isn't that the point?, its OOP after-all" but that's the thing with ECS, the whole drive behind it is to keep data and logic separate.

If you want a better understanding of how "systems" come into play in ECS architecture I strongly recommend reading the following two articles. They do a great job of breaking it down:

What is an entity system framework for game development?

Why use an entity system framework for game development?

# Answer
> 0 votes
One of the main goals of ECS is to have classes as decoupled as possible, mainly components and systems. In this sense, I wouldn't make a component subscribe itself to the systems it needs to, because then suddendly you will find that you have components hooked up to Systems, and if you remove a system, you have to alter the respective components.

Take as an example a Position component, and think of the many ways it can be used in many different Systems. If you have the Position constructor subscribe to the different Systems, say, MovementSystem, CollisionSystem, etc, then suddendly, it's not so decoupled anymore, and intrinsecaly you will be binding Components just by creating then, which you might not always want.

In my ECS implementation, I have a factory class that is capable of creating components, and thus registers each component with the respective System. This means that all the coupling will happen here, and it can be easily configurable, allowing me to have multiple ways to instantiate the components without directly changing the components themselves. If you use factories, you will find that you can then take a step further and create files from where you can read entities and their associated components, pushing your game towards a data-driven design.

I hope this helps. As a disclaimer, take all this advice with a grain of salt, since I am not an expert.

# Answer
> 0 votes
To expand on crancran's answer, I will share our experiences with the ECS we use at work.

Each component has the ability to be registered with a list of that component type. For example, our ModelComponent is registered with a ComponentList in it's create function, and removed in it's destroy function. Each frame, in the update loop, different systems are handed the component list(s) they need to operate upon. The ModelRenderer is handed the ComponentList as well as the ComponentList, for example. This keeps the data and the systems decoupled.

I some cases these lists are actually use to update the entities themselves - we iterate over all of the particle systems at a specific point in the frame to update them by calling ComponentList::Update() which invokes an Update method for each item (not using virtuals, but using template programming). The lists can also be split into active/inactive cases, and in some projects the lists are sophisticated and understand our portal system and staged updates.

One of the key aspects of ECS is that it takes awhile to get it right. I would encourage you to start working on components in a game and see what feels right. I do not believe there is yet a canonical, **correct** implementation out there.

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


# Question
Title: How to apply two pixel shaders in one go
Is there any possible way to apply two pixel shader simultaneously in directx-9. For example I am having two pixel shaders one to apply ripple effect and another to modify the color of the texture rendered on the screen. Is there any way that I can render the effect of the two pixel shaders simultaneously without combining them in the same shader file. Any kind of help is appreciated.

# Answer
> 2 votes
You would have to render the results of the first to a texture, then read the texture in the second shader and output the results to the screen.

---
Tags: directx9, slimdx
---


# Question
Title: What method is best to display respawn times?
I'm currently working on multiplayer game and am trying to work out how to display respawn times. I had a few ideas in mind, taking inspiration from other games I've played before.

* Text Based
*
* Progress Bar
*
* Visual Timer
*

Is there another way to display respawning for players that improves visual feedback? Meaning, is clear and effective at conveying exactly how long a player has to wait to respawn?

# Answer
The "correct" answer depends on what determines the time. Is it a fixed time that's always the same (or \<= 3 different times)? And how long is it? Why do you want the user to know how long it will take? Is it enough time to grab a bite to eat? Or is it a short time the user will be waiting in front of the screen for?

Because if it's short, why show the user exact information? The equivalent of "one moment please" to keep them in front of the screen and make them aware that the game hasn't locked up in some weird way is enough. It would be different if it's a long time, because then the user may want to get up and start the coffee maker or whatever.

Also, if it is always the same delay, the user will likely get used to the delay, so the only one who really wants to know how long it takes in seconds is someone who dies for the first time. Later, people will know what to expect, so don't need that information displayed.

I personally find long artificial waits annoying, and rather enjoy how World of Warcraft handles it, where you immediately respawn as a ghost at a graveyard nearby and then have to walk back to your corpse to actually be reunited with your body. That way you have a penalty (you have to walk back to where you died), but you get a kind of gameplay and stay "inside the world" and do not really drop out of immersion. Of course, if you were in the middle of a mob when you died you may die again immediately, but hey, that can be solved by massaging the mob AI to avoid corpses, I guess.

I also like the approach Call of Duty has, where you simply respawn immediately in some random location and can immediately get back into the game. As you obviously died and didn't complete whatever objective you had, you've had a short delay already, and you might have to go back to your team, causing a second delay that encourages you not to die in the future.
> 2 votes

---
Tags: gui
---


# Question
Title: Should I design UI in raster or in vector editing software?
I am working on a IOS city builder game (more like planet builder) but that's not the case, I was making the buttons in photoshop when something hit me: "if I make raster icons in photoshop, they will look pixelated on ipads!"

And so I proceded to illustrator to create the same things, but illustrator has nowhere near the amount of cool tools, that made my buttons look so cool in photoshop.

The question: Should I stick with vector graphics and make them work? so then I have resizable buttons. or Should I just create several sets of buttons, which are different sizes? a set for ipads,a set for iPhone 5's a set for iPhone 6's..

# Answer
As Krom Stern pointed out, there is no "correct" way of doing UI for a game. To be honest the whole rasterVSvector thing is misleading, as you should always chose the one that works best in the particular case (look at this --\> article for more info on raster/vector, and when to prefer one over the other).

Now when it comes to games two things are always in conflict, that is *memory* and *computation*. As the article above points out, **vectors might be cheaper to store but more expensive to compute**.

On the other hand, you could create a raster image of your button for the best quality (say iPad), and then generate a mipmap of the button (normally used for texture LoD), but this way you would have all possible button sizes, which you could swap over devices.

If you are interested in more advanced techniques for achieving resolution independent vectors, by taking advantage of the Signed Distance Field of a full scale raster image, and then re-generating it on the GPU using shaders, take a look at this paper by Valve.

That aside, I think you'll be alright if you just use bitmaps (rasters), especially if you can make them look better. **Think of optimising only if you actually need to**!
> 1 votes

---
Tags: ios, gui
---


title: .fnt font file offset issues in Unity

text:
# Question
Title: .fnt font file offset issues in Unity
I want to display 2D text in Unity using bitmap fonts (.fnt files). There are some solutions out there, but I'm writing my own. Each character is a game object with a `SpriteRenderer`.

It works. However, there is a small offset problem.

The `o`, `g` and `3` characters are badly positioned. This is the code that makes this:

```
    Vector3 cursor =    new Vector3 (0, 0, 0);  // Cursor for positioning the characters

    for (int i = 0; i < text.Length; ++i) {
        char    c       = text[i];
        Sprite  sprite  = spriteForCharacter(c);
        GameObject obj  = new GameObject();
        obj.AddComponent<SpriteRenderer>().sprite = sprite;
        obj.transform.localPosition     = new Vector3(cursor.x + xOffset(c), cursor.y, 0);
        cursor += new Vector3(xAdvance(c),0,0);
    }

```

---

`spriteForCharacter(char)` returns a Sprite object that is created by making a `Texture2D` with the dimensions of the character (according to the information in .fnt file), then copying the pixels of the .PNG bitmap file to it, and finally creating the sprite with `Sprite.Create()`. Here's the relevant part:

```
Texture2D tex = new Texture2D(characterWidth, characterHeight);
Color[] pixels = bitmap.texture.GetPixels(character.x, bitmap.texture.height - characterY - characterHeight,characterWidth,characterHeight);
tex.SetPixels(pixels);
tex.Apply();

```

---

`xOffset(char)` and `yOffset(char)` simply return the `xOffset` and `yOffset` values for this character as read in the .fnt file.

---

If you look at the code, you will notice that I never used `yOffset(char)`. I obviously should use it, but look what happens:

If I **add** the offset:

```
obj.transform.localPosition = new Vector3(cursor.x + xOffset(c), cursor.y + yOffset(c), 0);

```

If I **subtract** the offset:

```
obj.transform.localPosition = new Vector3(cursor.x + xOffset(c), cursor.y - yOffset(c), 0);

```

I'm at a loss: I'm not sure what to do wit hthe `yOffset` property.

---

Yes, I've confirmed that the `yOffset` property is read from the .fnt file correctly. If anything, all the lines in the .fnt file were parsed appropriately.

---

Here I submit the .fnt file and its bitmap - both created with Hiero

```
info face="Arial-Black" size=18 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=1,1,1,1 spacing=0,0
common lineHeight=28 base=20 scaleW=256 scaleH=128 pages=1 packed=0
page id=0 file="SimpleFont.png"
chars count=94
char id=32   x=0     y=0     width=0     height=0     xoffset=0     yoffset=20    xadvance=8     page=0  chnl=0
char id=125   x=0     y=0     width=10     height=21     xoffset=-1     yoffset=5    xadvance=9     page=0  chnl=0
char id=123   x=10     y=0     width=10     height=21     xoffset=-1     yoffset=5    xadvance=9     page=0  chnl=0
char id=41   x=20     y=0     width=10     height=21     xoffset=0     yoffset=5    xadvance=9     page=0  chnl=0
char id=40   x=30     y=0     width=10     height=21     xoffset=0     yoffset=5    xadvance=9     page=0  chnl=0
char id=64   x=40     y=0     width=18     height=20     xoffset=-1     yoffset=5    xadvance=15     page=0  chnl=0
char id=124   x=58     y=0     width=6     height=20     xoffset=0     yoffset=6    xadvance=7     page=0  chnl=0
char id=93   x=64     y=0     width=9     height=20     xoffset=-1     yoffset=6    xadvance=9     page=0  chnl=0
char id=91   x=73     y=0     width=9     height=20     xoffset=0     yoffset=6    xadvance=9     page=0  chnl=0
char id=106   x=82     y=0     width=9     height=20     xoffset=-2     yoffset=6    xadvance=8     page=0  chnl=0
char id=36   x=91     y=0     width=15     height=19     xoffset=-1     yoffset=5    xadvance=14     page=0  chnl=0
char id=81   x=106     y=0     width=18     height=19     xoffset=0     yoffset=5    xadvance=17     page=0  chnl=0
char id=38   x=124     y=0     width=18     height=18     xoffset=0     yoffset=5    xadvance=18     page=0  chnl=0
char id=35   x=142     y=0     width=15     height=18     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=37   x=157     y=0     width=21     height=18     xoffset=0     yoffset=5    xadvance=20     page=0  chnl=0
char id=92   x=178     y=0     width=9     height=18     xoffset=-1     yoffset=5    xadvance=7     page=0  chnl=0
char id=47   x=187     y=0     width=9     height=18     xoffset=-1     yoffset=5    xadvance=7     page=0  chnl=0
char id=48   x=196     y=0     width=15     height=18     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=57   x=211     y=0     width=15     height=18     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=56   x=226     y=0     width=15     height=18     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=54   x=0     y=21     width=15     height=18     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=51   x=15     y=21     width=15     height=18     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=83   x=30     y=21     width=16     height=18     xoffset=0     yoffset=5    xadvance=15     page=0  chnl=0
char id=79   x=46     y=21     width=18     height=18     xoffset=0     yoffset=5    xadvance=17     page=0  chnl=0
char id=71   x=64     y=21     width=17     height=18     xoffset=0     yoffset=5    xadvance=17     page=0  chnl=0
char id=67   x=81     y=21     width=17     height=18     xoffset=0     yoffset=5    xadvance=16     page=0  chnl=0
char id=59   x=98     y=21     width=7     height=17     xoffset=0     yoffset=9    xadvance=8     page=0  chnl=0
char id=63   x=105     y=21     width=14     height=17     xoffset=0     yoffset=5    xadvance=13     page=0  chnl=0
char id=53   x=119     y=21     width=15     height=17     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=52   x=134     y=21     width=15     height=17     xoffset=-1     yoffset=5    xadvance=14     page=0  chnl=0
char id=50   x=149     y=21     width=15     height=17     xoffset=-1     yoffset=5    xadvance=14     page=0  chnl=0
char id=49   x=164     y=21     width=11     height=17     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=121   x=175     y=21     width=15     height=17     xoffset=-1     yoffset=9    xadvance=13     page=0  chnl=0
char id=116   x=190     y=21     width=11     height=17     xoffset=-1     yoffset=6    xadvance=10     page=0  chnl=0
char id=113   x=201     y=21     width=14     height=17     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=112   x=215     y=21     width=14     height=17     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=103   x=229     y=21     width=14     height=17     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=102   x=243     y=21     width=11     height=17     xoffset=-1     yoffset=5    xadvance=9     page=0  chnl=0
char id=100   x=0     y=39     width=14     height=17     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=98   x=14     y=39     width=14     height=17     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=85   x=28     y=39     width=16     height=17     xoffset=0     yoffset=6    xadvance=17     page=0  chnl=0
char id=74   x=44     y=39     width=14     height=17     xoffset=-1     yoffset=6    xadvance=14     page=0  chnl=0
char id=33   x=58     y=39     width=7     height=16     xoffset=0     yoffset=6    xadvance=8     page=0  chnl=0
char id=55   x=65     y=39     width=15     height=16     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=108   x=80     y=39     width=7     height=16     xoffset=0     yoffset=6    xadvance=8     page=0  chnl=0
char id=107   x=87     y=39     width=15     height=16     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=105   x=102     y=39     width=7     height=16     xoffset=0     yoffset=6    xadvance=8     page=0  chnl=0
char id=104   x=109     y=39     width=13     height=16     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=90   x=122     y=39     width=16     height=16     xoffset=-1     yoffset=6    xadvance=15     page=0  chnl=0
char id=89   x=138     y=39     width=18     height=16     xoffset=-1     yoffset=6    xadvance=16     page=0  chnl=0
char id=88   x=156     y=39     width=18     height=16     xoffset=-1     yoffset=6    xadvance=16     page=0  chnl=0
char id=87   x=174     y=39     width=23     height=16     xoffset=-1     yoffset=6    xadvance=20     page=0  chnl=0
char id=86   x=197     y=39     width=18     height=16     xoffset=-1     yoffset=6    xadvance=16     page=0  chnl=0
char id=84   x=215     y=39     width=16     height=16     xoffset=-1     yoffset=6    xadvance=15     page=0  chnl=0
char id=82   x=231     y=39     width=17     height=16     xoffset=0     yoffset=6    xadvance=16     page=0  chnl=0
char id=80   x=0     y=56     width=15     height=16     xoffset=0     yoffset=6    xadvance=15     page=0  chnl=0
char id=78   x=15     y=56     width=16     height=16     xoffset=0     yoffset=6    xadvance=17     page=0  chnl=0
char id=77   x=31     y=56     width=18     height=16     xoffset=0     yoffset=6    xadvance=19     page=0  chnl=0
char id=76   x=49     y=56     width=14     height=16     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=75   x=63     y=56     width=17     height=16     xoffset=0     yoffset=6    xadvance=17     page=0  chnl=0
char id=73   x=80     y=56     width=8     height=16     xoffset=0     yoffset=6    xadvance=9     page=0  chnl=0
char id=72   x=88     y=56     width=16     height=16     xoffset=0     yoffset=6    xadvance=17     page=0  chnl=0
char id=70   x=104     y=56     width=14     height=16     xoffset=0     yoffset=6    xadvance=14     page=0  chnl=0
char id=69   x=118     y=56     width=15     height=16     xoffset=0     yoffset=6    xadvance=15     page=0  chnl=0
char id=68   x=133     y=56     width=16     height=16     xoffset=0     yoffset=6    xadvance=16     page=0  chnl=0
char id=66   x=149     y=56     width=16     height=16     xoffset=0     yoffset=6    xadvance=16     page=0  chnl=0
char id=65   x=165     y=56     width=18     height=16     xoffset=-1     yoffset=6    xadvance=16     page=0  chnl=0
char id=62   x=183     y=56     width=14     height=15     xoffset=0     yoffset=7    xadvance=14     page=0  chnl=0
char id=60   x=197     y=56     width=14     height=15     xoffset=0     yoffset=7    xadvance=14     page=0  chnl=0
char id=43   x=211     y=56     width=13     height=14     xoffset=0     yoffset=7    xadvance=14     page=0  chnl=0
char id=117   x=224     y=56     width=13     height=14     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=115   x=237     y=56     width=14     height=14     xoffset=-1     yoffset=9    xadvance=13     page=0  chnl=0
char id=111   x=0     y=72     width=15     height=14     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=101   x=15     y=72     width=15     height=14     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=99   x=30     y=72     width=15     height=14     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=97   x=45     y=72     width=15     height=14     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=58   x=60     y=72     width=7     height=13     xoffset=0     yoffset=9    xadvance=8     page=0  chnl=0
char id=122   x=67     y=72     width=13     height=13     xoffset=-1     yoffset=9    xadvance=12     page=0  chnl=0
char id=120   x=80     y=72     width=15     height=13     xoffset=-1     yoffset=9    xadvance=14     page=0  chnl=0
char id=119   x=95     y=72     width=21     height=13     xoffset=-1     yoffset=9    xadvance=19     page=0  chnl=0
char id=118   x=116     y=72     width=15     height=13     xoffset=-1     yoffset=9    xadvance=13     page=0  chnl=0
char id=114   x=131     y=72     width=11     height=13     xoffset=0     yoffset=9    xadvance=10     page=0  chnl=0
char id=110   x=142     y=72     width=13     height=13     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0
char id=109   x=155     y=72     width=19     height=13     xoffset=0     yoffset=9    xadvance=20     page=0  chnl=0
char id=61   x=174     y=72     width=13     height=12     xoffset=0     yoffset=8    xadvance=14     page=0  chnl=0
char id=94   x=187     y=72     width=13     height=12     xoffset=0     yoffset=5    xadvance=14     page=0  chnl=0
char id=42   x=200     y=72     width=11     height=11     xoffset=1     yoffset=5    xadvance=12     page=0  chnl=0
char id=44   x=211     y=72     width=7     height=11     xoffset=0     yoffset=15    xadvance=8     page=0  chnl=0
char id=126   x=218     y=72     width=14     height=8     xoffset=0     yoffset=10    xadvance=14     page=0  chnl=0
char id=39   x=232     y=72     width=8     height=8     xoffset=0     yoffset=6    xadvance=7     page=0  chnl=0
char id=34   x=240     y=72     width=12     height=8     xoffset=-1     yoffset=6    xadvance=11     page=0  chnl=0
char id=45   x=0     y=86     width=9     height=7     xoffset=-1     yoffset=12    xadvance=8     page=0  chnl=0
char id=46   x=9     y=86     width=7     height=7     xoffset=0     yoffset=15    xadvance=8     page=0  chnl=0
char id=96   x=16     y=86     width=8     height=7     xoffset=-1     yoffset=5    xadvance=8     page=0  chnl=0
char id=95   x=24     y=86     width=14     height=5     xoffset=-1     yoffset=20    xadvance=11     page=0  chnl=0

```

---

~~I couldn't help but notice that of the three `o`'s, only one is off. Now I am even more puzzled.~~ Thanks to Steven it seems like the three `o`'s are actually aligned.

# Answer
The reason you are getting this behaviour is because of coordinate system. The base coordinate for your sprites is "left,bottom" (classic Cartesian) however all offsets in `fnt` files are assuming inverted `Y` axis (drawing from "left,top" of the sprite).

So instead of (you may notice this gives correct align, but on the top, i.e. `g` goes up instead of down):

```
obj.transform.localPosition = new Vector3(cursor.x + xOffset(c), cursor.y + yOffset(c), 0);

```

you should do:

```
var baseLine = 20; // you should get baseline from fnt file
var y = cursor.y;
// first put it into assumed by fnt position
y += baseLine - charHeight(c); // charHeight must return character height
// now apply offset, using '-' instead of '+' because of our coordinates
y -= yOffset(c);

obj.transform.localPosition = new Vector3(cursor.x + xOffset(c), y, 0);

```

I'm not 100% sure that I'm correct since I can't test it, but I think solution lies somethere close to this. Hope that helps!
> 4 votes

# Answer
I can't add a comment because my reputation isn't high enough, so this isn't really an answer.

I thought the o's were offset differently as well, but when I used a ruler it turns out all three o's are on the same baseline. It is just an optical illusion from the dropped 'm'.

In you code sample for extracting the glyphs from the font texture you use the variable character.x, but then you use a variable characterY - what's the value of that, and why not just use character.y directly?

Let's look at the font data.

Here is the entry for 3: char id=53 x=119 y=21 width=15 height=17 xoffset=0 yoffset=6 xadvance=14 page=0 chnl=0

And here is the entry for 1: char id=49 x=164 y=21 width=11 height=17 xoffset=0 yoffset=5 xadvance=14 page=0 chnl=0

The two glyphs are in the same row, and vertically aligned with each other, but the offset is off by one. This seems to match your rendering.

Are you using the baseline and line height properties as well? I don't know about .fnt but you might want your Y offset to be equal to lineheight - baseline + yoffset. Maybe that's a better calculation?

What anchor points are you using for positioning the glyphs? Top right, bottom left? If all the glyph textures are different heights, you might need to subtract the height of the glyph first before applying the yoffset.

Just my observations.
> 3 votes

# Answer
It seems that something is going wrong when you create the textures for the individual characters. First, if we look closely, we see that it's not just the `o`, `g` and `3` characters are badly positioned:

As Petr Abdulin points out:

> The base coordinate for your sprites is "left,bottom" (classic Cartesian)

which is correct. Your renderer assumes `left,top` coordinate system which is part of the problem here. However, something else must be wrong in your code in addition to that because otherwise you should actually get something like this with the code you pasted:

Here, all letters are top-aligned. However, since yours doesn't look like that, I suspect that something is not quite right with your sprite/texture computation.

For instance, I don't quite understand what exactly you're doing here:

```
Color[] pixels = bitmap.texture.GetPixels(character.x, bitmap.texture.height - characterY - characterHeight,characterWidth,characterHeight);

```

If we look at the font spec file, we see that every character gives the coordinates of its sub-bitmap directly, e.g., for the lower-case g we have:

```
char id=103   x=229     y=21     width=14     height=17     xoffset=0     yoffset=9    xadvance=14     page=0  chnl=0

```

The coordinates `x, y, width, height` refer directly to the sub-region of the bitmap, so I would have expected your code to look something like this:

```
int x = x(c)
int y = y(c)
int width = width(c)
int height = height(c)

Color[] pixels = bitmap.texture.GetPixels(x, y, width, height);

```

Note that there is no subtraction from `bitmap.texture.height`.

My suggestion is that you try to find out why your first image looks different. Once you fixed that, it's easy to achieve the actually correct rendering by *adding* `yoffset` to the y-coordinate, like you tried before.
> 3 votes

# Answer
I think it would be useful for you to try this program "bmglyph" http://www.bmglyph.com/ You can generate a character set with the font you like and export the font atlas in unity native format and in Cocos2D format (the format used by NGUI). Then you can look at how the program generate the .fnt and match it against what you already have and see if you are missing something. I used it in several project and it was plug and play. Hope it helps.
> 0 votes

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


# Question
Title: How to hit an enemy, or "how do entities interact with each other?"
The title might be a tad simple for the purpose, but bear with me.

I'm a tad lost about how to do the interaction between game objects. I use an entity-component-system framework and I've got the basics up and running: the player can run around, collisions get reported correctly, graphics are updating nicely and so on. I even have an AI enemy wandering around.

However, what if I want to hit the enemy with a sword? How do I know what the player hit? The naive solutions (for e.g. Box2D) do something like this:

```
void BeginContact(b2Contact* contact)
{
    // Get the colliding bodies
    b2Body* body1 = contact->GetFixtureA()->GetBody();
    b2Body* body2 = contact->GetFixtureB()->GetBody();

    // Get the user data
    int body1UserData = body1->GetUserData();
    int body2UserData = body2->GetUserData();

    // Check if the enemy hit the player
    if((body1UserData == PLAYER && body2UserData == ENEMY) ||
       (body2UserData == PLAYER && body1UserData == ENEMY))
    {
        // Enemy collided with player, damage the player
        causeDamageToPlayer();
    }
}

```

This solution "works", but to my understanding has very little use in real-life scenario. Again: what if I want to hit an enemy with a sword? Which enemy did I hit? Should I really keep adding and removing the sword collider from the game world? I can't really find any good reads on this topic. There's lots of articles and books about game engines, but the actual game architecture is commonly left out.

I'm purposefully leaving this a bit vague since there is probably multiple ways to do that. I'm after some real-life usage examples and how to do things in a bigger scale, where there's tens of different enemies / entities, various weapons and so on.

# Answer
> 0 votes
You need to send events around. When the you have a contact, emit an event of type "contact" with data "entity1" and "entity2".

Now your system that resolves the attacks listens to events of type "contact". Therefore, it can check if one of the entities was attacking, and if yes, using what weapon.

Well, you can go on from there, depending on your entities/components/systems and supported interactions.

# Answer
> 0 votes
What I have done in previous projects is send all Entity class members to a central event hub and send a boolean variable telling whether contact has been made or not. the Entity itself then determines what to do by the provided information

---
Tags: architecture
---


# Question
Title: What is the correct way to authenticate a player with password from Unity to a php api server?
So, I have a game in Unity for mobiles that gives you the possibility to sign-up with username, email and password to unlock extra features. The datas are sent, through a POST request, to a PHP+MYSQL server that expose an API. I'm developing both so I have complete freedom on how to implement it.

My question is what is the correct way to:

* save auth data on player mobile device so it can automatically login on subsequent runs of the game
* how to safely send username and password to my server for the authentication

I want to protect data from man in the middle attacks and I don't want to send clear password because users tends to always use the same email/password combination.

Thank you

# Answer
You want your webserver access to go through HTTPS; that will encrypt the traffic so people in the middle can't read it.
> 3 votes

---
Tags: unity, php, mysql, authentication
---


# Question
Title: How to access bottom canvas layer in HTML?
I have such html:

```
<div id="main_window">
 <canvas id="canvas_hex_logic" width="200" height="100"></canvas>
 <canvas id="canvas_ground" width="200" height="100"></canvas>
</div>

```

and css:

```
#canvas_hex_logic{
 position: absolute;
 top:31px;
 left:201px;
 z-index: 0;
}
 #canvas_ground{
 position: absolute;
 top:31px;
 left:201px;
 z-index: 1;
}

```

in #canvas\_hex\_logic I'm rendering mask for my hexagons:

over it I'm placing ground layer:

part of JS code, for picking color under mouse:

```
  ..... mouse event handler above .....
  var c_hex = document.getElementById("canvas_hex_logic");
  var ctx_hex = c_hex.getContext("2d");
  ..... ..... ..... ..... ..... .....
  var color = ctx_hex.getImageData(mouseX, mouseY, 1, 1).data;

```

This code working, if #canvas\_hex\_logic is on tom of other layers.

So, question is - how to pick color under mouse from #canvas\_hex\_logic layer when it is overlayed with another layer?

Thanks!

# Answer
> 1 votes
found answer:

```
#canvas_ground {
  left: 201px;
  pointer-events: none;  <<--------- this helps
  position: absolute;
  top: 31px;
  z-index: 1;
}

```

# Answer
> 1 votes
Your issue comes from the fact that your 'hex' canvas is hidden by your 'ground' canvas, and do not receive the mouse events.

But in fact you don't care from which canvas the click event was raised : just have your mouse handling code hook the events of the top-most canvas, and use those coordinates.

(I assume here that all canvases have the same size and do completely overlap. By the way you might want to put all the canvas within a single div with absolute positioning of the canvas (left,top)=(0px,0px). It'll be easier to later add canvases.)

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


# Question
Title: How do I cut off the edge of an image in a 2D JavaScript Array?
OK, I am trying to make a game that is a little bit like SimTower but utilizing HTML5 (particularly the canvas element) and JavaScript with a little CSS.

I have ran into a couple of little problems that have caused me to pause coding since summer and read and reread JavaScript books. My main problem right now is that I don't know how to get the lobbies to work properly. Currently, I have divided the lobby images into the left-most portion (which does not repeat) and the right portion which does (but this portion needs to be able to be cut off at arbitrary grid locations. I loaded them into my webpage but the bottom floors (in this case 5 since it is a 3-story grand lobby and a 2-story mezzanine) need to be completely filled in with lobby and mezzanine from the left-most side to the right-most side of the tower (because one cannot build wider than the lobby). The 32 right-most tiles are supposed to repeat (the 7-leftmost tiles are supposed to stay on the leftmost side of the tower) but the repeating portion of the lobby can only repeat whole copies of the image when I need it to be able to be cut off at arbitrary grid tiles (multiples of 16 pixel widths). I was also wondering if it was good form to have 0's in the array where the images/tiles extend (so no images overlap) but I presume it is.

In short, I would like to know how to make the lobby images render correctly (with part of each staying on the left-most side and the rest repeating all the way to the right-most side). My skylobbies look OK because I just have rooms without transparency overlap and cover portions of the skylobby but this is not ideal and it might make programming path-finding harder once it is implemented (and I need the ground lobby to work correctly). I previously posted a similar question that really asked two questions (one on optimizing performance) but I was able to figure that out and fix it thanks to my friends and pen pals.

By the way, my web page has 21 lines of code, and supporting JavaScript pages for the functions and a 110 line array (that is 320 columns wide). I could post a portion of my code if requested though I don't know how helpful it would be to post the entirety. Also, if it matters, each tile in my game is 16 pixels wide and 72 pixels tall (48 pixels for the rooms, 24 pixels for the space between stories).

I am going to assume that a link to the project would probably be best so here it is: https://github.com/AzemOcram/OcramTower/tree/gh-pages

Here is the portion of the code for loading the array and displaying it in the web page:

```
// Depends on global mapArray, defined in map.js
function drawRooms(ctx, rect) {
var FLOOR_HEIGHT = 72;
var SECTION_WIDTH = 16;
var MAX_ROOM_HEIGHT = FLOOR_HEIGHT * 5;
for (var floor = 0; floor < mapArray.length; floor++) {
    var y = 108 + FLOOR_HEIGHT * floor;

// Bail out early to avoid drawing the whole tower every time
if (y > rect.h + rect.y) continue;
if (y + MAX_ROOM_HEIGHT < rect.y) continue;

var floorSections = mapArray[floor];
for (var section = 0; section < floorSections.length; section++) {
var x = 1000 + SECTION_WIDTH * section;
if (x > rect.w + rect.x) continue;

var roomIndex = mapArray[floor][section];
var img = roomImages[roomIndex];
var w = img.naturalWidth;
var h = img.naturalHeight;
if (x + w < rect.x) continue;
if (y + h < rect.y) continue;

ctx.drawImage(img, x, y, w, h);
    }
}
}
function draw(ctx, rect) {
drawBackground(ctx, rect);
drawRooms(ctx, rect);
}

var ctx;
function drawFrame() {
var x = -drawOffset.x;
var y = -drawOffset.y;
var w = ctx.canvas.width;
var h = ctx.canvas.height;
ctx.save();
ctx.fillStyle = 'black';
ctx.translate(-x, -y);
ctx.fillRect(x, y, w, h);
draw(ctx, {x: x, y: y, w: w, h: h});
ctx.restore();

console.log("drawing...");

requestAnimationFrame(drawFrame);
}

window.onload = function() {
var canvas = document.getElementById("gameCanvas");

var dragStart = {x: 0, y: 0, started: false};

window.onmousedown = function (e) {
    dragStart.x = e.clientX;
    dragStart.y = e.clientY;
    window.onmousemove = drag;
    return false;
};

window.onmouseup = function (e) {
    window.onmousemove = null;
    return false;
};

function drag(e) {
    drawOffset.x += e.clientX - dragStart.x;
    drawOffset.y += e.clientY - dragStart.y;
    dragStart.x = e.clientX;
    dragStart.y = e.clientY;

    return false;
};

window.onresize = fillWindow;
function fillWindow() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}

fillWindow();

skyLine.src = 'UI/OT_skyline.png';
waitFor(skyLine);

for (var i = 0; i < ROOM_IMAGE_MAP.length; i++) {
    var roomImage = new Image();
    roomImage.src = ROOM_IMAGE_MAP[i];
    waitFor(roomImage);
    roomImages.push(roomImage);
}

ctx = canvas.getContext('2d');
waitForAll();
}

waitFor.queue = [];
waitFor.loaded = 0;
function waitFor(img) {
waitFor.queue.push(img);
}
function waitForAll() {
for (var i = 0; i < waitFor.queue.length; i++) {
    waitFor.queue[i].onload = function () {
        waitFor.loaded++;
        if (waitFor.loaded == waitFor.queue.length - 1) {
            requestAnimationFrame(drawFrame);
        }

```

EDIT: Here are some pictures demonstrating the problem:

The left side (which doesn't have the problem visible)

I hope these pictures demonstrate the problem (I need the lobby to extend all the way to the right) and I hope I can get help on this. If I add another copy of the lobby image, it extends beyond the confines of the building area. Ideally, I want to be able to build lobbies that can be extended 1 tile (16 pixels) at a time.

# Answer
Use the overload of the `drawImage` method of `2DContext` that allows you to draw part of an image. MDN calls it slicing:

> **drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)**
> Given an image, this function takes the area of the source image specified by the rectangle whose top-left corner is (sx, sy) and whose width and height are sWidth and sHeight and draws it into the canvas, placing it on the canvas at (dx, dy) and scaling it to the size specified by dWidth and dHeight.

In your case, you will have to check each tile of the image that you draw, and when you get to the rightmost (or whatever) tile that needs to be cut off, figure out how much width you really need. For the other tiles, you can either draw the full width with this method, or use one of the other overloads that draws the full image.
> 1 votes

---
Tags: javascript, html5
---


# Question
Title: StartCoroutine function inside TriggerOnEnter2D not working - unity + kinect
So i'm using Kinect with unity to track user's hand movements, and let the user's hand act as a mouse, I have written the code to detect a collision between a button (sprite object) and the hand cursor using **OnTriggerEnter2D**, but I want the hand cursor to remain on the button (sprite object) for atleast 3 seconds for it to be considered as a button click action. The WaitForSeconds coroutine doesn't seem to be working. What am i doing wrong?

```
public class MenuSelect : MonoBehaviour{

private string btnName;
private string themeName;

// Use this for initialization
void Start ()
{
    //gestureListener = Camera.main.GetComponent<GestureListener>();
}

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

}

void OnTriggerEnter2D(Collider2D col)
{
    //print("Collision Detected");
    StartCoroutine(WaitTime(3));
    if(col.gameObject.tag == "Button")
    {
        btnName = col.gameObject.name;
        switch(btnName)
        {
            case "musicBtn":
                Application.LoadLevel("Menu_Music");
                break;

            case "startBtn":
                Application.LoadLevel("Menu_Select");
                break;

            case "instructBtn":
                print("Instruction Clicked");
                break;

            case "exitBtn":
                Application.Quit();
                break;

            case "themeBtn":
                Application.LoadLevel("Menu_Theme");
                break;

            case "backBtn":
                Application.LoadLevel("Menu_LoadScreen");
                break;
        }
    }

}

IEnumerator WaitTime(float waitTime)
{
    yield return new WaitForSeconds(waitTime);
    print("seconds up already");
}   }

```

# Answer
The coroutine itself will pause, but the code that called StartCoroutine() will keep going. So in this case, WaitTime() will pause but OnTriggerEnter2D() will keep going.

What you probably want instead is for the entire button logic to go in the coroutine. Then it won't matter that OnTriggerEnter2D() keeps going, since starting the coroutine is all it does. At that point you should call the coroutine function something other than WaitTime() since it's doing a lot more than just waiting eg. WaitThenRespondToButton()
> 1 votes

# Answer
Your `WaitTime` Coroutine will not pause the evaluation of the following code. The Coroutine will be kicked off and logic will immediately continue. Your Coroutine is waiting 3 seconds and will call that `print` function wherever it resides but that's all it will do.

You should probably go with something like:

```
private float triggerEnterTime = 0;

void OnTriggerEnter2D(Collider2D col)
{
    triggerEnterTime = Time.time;
}

void OnTriggerStay2D(Collider2D col)
{
    // Too soon?
    if(Time.time - triggerEnterTime < 3)
    {
        // Might want to do something to indicate graphically that you're holding
        //     like a progress bar. For now, simply abort for this frame.
        return;
    }

    // Has been held for 3 seconds, evaluate it
    if(col.gameObject.tag == "Button")
    {
        btnName = col.gameObject.name;
        switch(btnName)
        {
            case "musicBtn":
                Application.LoadLevel("Menu_Music");
                break;

            case "startBtn":
                Application.LoadLevel("Menu_Select");
                break;

            case "instructBtn":
                print("Instruction Clicked");
                break;

            case "exitBtn":
                Application.Quit();
                break;

            case "themeBtn":
                Application.LoadLevel("Menu_Theme");
                break;

            case "backBtn":
                Application.LoadLevel("Menu_LoadScreen");
                break;
        }
    }
}

```

That should do the trick but something that might be cleaner is to define a "MenuItemBehavior" that will handle itself rather than some master `switch` statement.

Something like the following. I'd attach it individually to each button and then set "TargetScene" for each as well. This should work for most of them though you'd have to do something slightly different for "Instruction" and "Exit"

```
public class SceneMenuItemController : MonoBehaviour
{
    public string TargetScene;

    private float triggerEnterTime = 0;

    void OnMouseUpAsButton()
    {
        if (!string.IsNullOrEmpty(TargetScene))
        {
            Application.LoadLevel(TargetScene);
        }
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        triggerEnterTime = Time.time;
    }

    void OnTriggerStay2D(Collider2D col)
    {
        // Too soon?
        if(Time.time - triggerEnterTime < 3)
        {
            // Might want to do something to indicate graphically that you're holding
            //     like a progress bar. For now, simply abort for this frame.
            return;
        }

        if (!string.IsNullOrEmpty(TargetScene))
        {
            Application.LoadLevel(TargetScene);
        }
    }
}

```
> 1 votes

---
Tags: unity, unityscript, kinect
---


# Question
Title: Efficient fog-of-war visibility searching
Every game I look into that uses fog of war tends to have the AI ignore fog of war completely. I'm starting to see why.

I have a RTS game I'm working on, with lots of units moving around. All units are on a grid, and I use a predefined search pattern to scan the grid points around the unit to find the nearest target. So far so good.

However, I have another unit type who's job it is to run around the map and collect scrap from destroyed units. As with combat units, I want it to look around and select the closest scrap it can find. However, unlike combat units, this search isn't limited to it's own vision radius. It should be able to take advantage of the player's entire fog of war. If another unit or building has revealed some scrap, it should be available for the unit to go pick up.

While scanning the vision radius of a unit is simple, I'm having trouble thinking of an efficient way to determine which grid points to scan in this much larger case. Any grid points within view of a building will be fairly static, but things other units see will change every frame, as they are constantly moving.

The two options I see are to record per-player visibility flags within the grid points themselves, and then (somehow) update those flags each frame, or to just loop through all units and buildings and perform individual searches to build a list of visible scrap. The first would be difficult to keep updated without re-scanning the entire map, and the second would be very redundant if there were many units or buildings in a small area.

Is there another method I could use to build a list of visible scrap within a player's entire fog of war view, given that that view is constantly changing?

# Answer
> 1 votes
I think, that's work for influence maps. It's almost your first option but in more common interpretation for AI in games. Influence maps presents all your map with grid in some specific structure. For each cell you save some value and periodically update it. In your case, you can save last\_seen\_time as value. So, when you'll iterate scrap to find new target, you easily can check that someone from units saw it (last\_seen\_time \> scrap\_spawn\_time). In updating phase you should iterate units and set current time as last\_seen\_time at each visible cell from this unit.

How to implement good influence map structure depends in your purposes. Easiest way: divide the map to small cells. You don't need to update it each frame, few times per second should be enough in your purposes. And you don't need to clear it each frame, only update new visible cells.

# Answer
> 1 votes
> The two options I see are to record per-player visibility flags within the grid points themselves, and then (somehow) update those flags each frame...

This seems like the right answer to me. Store whether or not each player can see each grid point. Updating the map can actually be very simple and efficient. You presumably already update each unit. When you do this, check the grid cells within the view radius (this is easy to do using rasterization). Mark them as "seen" if a unit has seen them. Just clear the visibility map every frame.

If that's too slow, you can store the visibility map the other way around: a spatial hash map of all the nodes currently seen. Create a hash map where the value is the node, and the key is

hash(x, y) = x * p1 ^ y * p2

Where p1, p2 are large primes and ^ is the xor operator. You can iterate over the hash map to see which nodes to check (don't need to iterate over nodes that aren't seen). You can also add to the hash map easily using the hash function.

---
Tags: rts, search, fog-of-war
---


# Question
Title: I want to render some surfaces in GLSL with normal maps, and some without
I have normal mapping working in my game, but I want to only use normal mapping for some surfaces, and not others.

Right now, as far as I can tell, my shader is applying an incorrect normal of (0, 0, 0) in tangent space to my non normal mapped surfaces, since no textures are bound to the sampler.

Is there a suitable way of detecting that nothing is bound to a sampler in GLSL and then using a flat normal instead? I've also found old posts around the web recommending the following:

1. Using a dummy 1x1 texture with the color (128, 128, 255) - this will lose Phong interpolation.
2. Switching shader programs for normal mapped and non-normal mapped surfaces - I get the feeling that I'd end up duplicating a lot of code this way, especially when I start implementing specular maps, parallax displacement maps, etc.

Are either of these still recommended or is there a new feature to query the sampler that I could make use of? Should I be doing it one way over another for performance reasons?

Here is my fragment shader:

```
#version 330 core

in vec2 UV;
in vec3 tangentSpaceLightDir;
out vec4 outColor;
uniform sampler2D diffuseMap, normalMap;

void main (void)
{
    vec4 texel = texture(diffuseMap, UV);
    vec4 ntexel = texture(normalMap, UV);

    // I want to use vertex normal here, if nothing is bound.
    vec3 N = normalize(ntexel.xyz * 2.0 - 1.0);

    vec3 L = normalize(tangentSpaceLightDir);

    float lambertTerm = dot(N, -L);

    vec4 finalColor = vec4(0.0);
    if (lambertTerm > 0.0)
    {
         finalColor += vec4(lambertTerm, 1.0);
    }

    outColor = finalColor * texel;
}

```

# Answer
You already know what you have to do, I'll just summarize it. There are three ways to solve your problem:

* Go ahead and make a conditional like you're saying, either by sampling the texture or by creating a separate `uniform` for this purpose. As you probably know, adding branching on a shader is almost never a good idea, and much less so in the fragment shader: **You usually don't want to do this**
* Add a `uniform float` that determines whether or not you use normals. Set it to 0 to disable and to 1 to enable. After calculating the normals, multiply the result by this value. If you set it to 0, the result will be 0. However, the program won't be faster when you want to disable normals. **You would usually prefer this approach**
* But, if you can afford to switch shaders, I really recommend you do so. The shader will be a bit faster when normals are disabled. If you're worried about duplicating code, you can make your shader be procedurally generated, by assembling different parts, and creating different sets of shaders for each different necessity you have. Having lots of shaders, even hundreds of different shaders is not uncommon in modern games. **If possible, you may want to do this**
> 9 votes

---
Tags: opengl, shaders, glsl, graphics-programming, normal-mapping
---


# Question
Title: How should a Unity object control it's state?
I've been using Unity's component based design, and the biggest problem I've faced is how to control an object's( not component's ) state.

The problem is, some components must act differently based on the object's state. However, checking an object's state within a non-specific component( imagine we have a "DamageEnemyComponent" ) won't work at all because it makes assumptions about the object it's attached to.

The alternative is to make each component perform one, and only one function. The components are then disabled/enabled or added/removed depending on the object's state( probably managed by a more specific component. )

Imagine we have a "Boomerang" object. Assume it has only two states; idle( being held by the player ) and firing. In the idle state, the boomerang would have very few components, because we don't want it to interact with the world while it's simply being held. It may have components to listen for a "throw", though. Once it is thrown, some state manager on the object needs to update the object to have components for moving, damaging enemies, maybe picking up items etc. When the boomerang is back in the hands of the player, it's component list would need to be restored. This would work, but it would basically be building a new game object for each state, which is incredibly tedious and messy without Unity's editor. Not to mention the inheritance and interfaces can't be used well here( since the state specific components will be built into the state manager script. )

I can't see a way to control state using Unity's components. How is this usually done? It feels as if Unity should provide a way to build different states in the editor, much like building an object.

# Answer
For states, I usually use Enums, and then do a switch statement within the Update method. Enabling/disabling components is probably easier than adding/removing them.

If you need to listen for or be ready to execute a method that should only happen within a specific state, check the state at the start of the method.

If the file gets too long and confusing, you can certainly break certain parts down into their own components and link/reference the various classes between each component as required, then enable/disable each component as required when changing states.

Here's a rough version of how I might code the start of a Boomerang:

```
// Various states the boomerang can be in
enum BoomerangState {
    Idle = 1,
    Firing = 2
}

BoomerangState state;

// Decide if we should launch the boomerang
bool WeShouldLaunch() {
    return state == BoomerangState.Idle ? true : false;
}

// Launch the boomerang and enable its collider
void Launch() {
    GetComponent<BoxCollider>().enabled = true;
    state = BoomerangState.Firing;
}

// Return boomerang to idle state and disable its collider
void MakeIdle () {
    state = BoomerangState.Idle;
    GetComponent<BoxCollider>().enabled = false;
}

void Update () {
    // Do things based on current state
    switch (state) {
        case BoomerangState.Idle:
            // Hold boomerang and be ready to launch it
            if (WeShouldLaunch()) {
                Launch();
            }
            break;
        case BoomerangState.Firing:
            // Make boomerang fly where needed
            // ...
            // Then when done:
            MakeIdle();
            break;
    }
}

// Only deal damage if boomerang is out and about (eg not idle)
void OnCollisionEnter(Collider col) {
    if (state == BoomerangState.Firing) {
        // Damage the collider we hit
    }
}

```
> 3 votes

---
Tags: unity, state, entity-component
---


title: 2D Hitboxing on an HTML image

text:
# Question
Title: 2D Hitboxing on an HTML image
I want to make a turn-based game where the player is given "opportunities for attack." An image of the in-game sprite character appears when it's the player's turn to attack. The player can mouseover the various parts of the image, which will highlight that specific body part, like so:

The player can then choose to attack that given body part.

To do this, I was thinking of adopting the "grid" method, and put my image within a 2D array... with each region of the body mapped to a certain square, like so:

Or, I could generate a pixelated version of the in-game sprite within a grid to begin with, so I would already have the mappings, like so:

Minecraft Pixel Art

I'm not sure:

* how to partition the image up so that each section is represented meaningfully in the matrix
* if this is the right way of doing this

Any guidance would be helpful

# Answer
You could just store a second image (or use the alpha channel of your image) to store a heat map (this also depends a bit on how you're drawing this, e.g. through a canvas).

You just create some mapping and tint areas in their specific color (example):

* Left arm becomes red.
* Right arm becomes orange.
* Left leg becomes cyan.
* Right leg becomes blue.

As an alternative, you could use the alpha channel of your image. For drawing, you round your alpha value (e.g. if it's above 250, consider it to be 255):

* Left arm is `alpha = 254`.
* Right arm is `alpha = 253`.
* Left leg is `alpha = 252`.
* Right leg is `alpha = 251`.

When you've got a touch event, you're just looking up the pixel at that position and determine the color. Based on the color you know the actual assignment.

This even works with animated sprites and avoids having the player pick some body part despite touching some area outside the actual image.

---

Also have a look at HTML's `<map>` tag, which would allow you to define freeform outlines that become clickable.
> 2 votes

---
Tags: 2d, javascript, sprites, rpg, grid
---


# Question
Title: When are Unity scripts actually disabled?
When I disable an active script in unity, will it be disabled then and there, or will it only be disabled at the end of the frame?

For example, if I disable a certain script from within a "OnCollisionEnter" event method, will the "disabled" script still perform it's Update method for this frame?

# Answer
I just tested this using the following code:

```
void OnCollisionEnter( Collision collision )
{
    this.enabled = false;
    Debug.Log( "Collided with " + collision.gameObject.tag );
}

void Update()
{
    if( this.enabled )
    {
        Debug.Log( "Enabled" );
        return;
    }
    Debug.Log( "Disabled" );
}

```

"Enabled" was displayed until the object came in contact with something, it outputted "Collided with *tag*". "Disabled" was never shown, proving that disabling/enabling an object takes immediate effect. It's probably just a flag that is checked when calling event methods.

This is assuming that Update methods are called after OnCollisionEnter, which they, according to the Unity documentation, are.
> 3 votes

# Answer
I think this document from the Unity help should be useful. Look to the diagram at the bottom of the page.

Physics and collisions are processed before the game logic so if you disable an object during **collision** it will become disabled after its next update.
> 0 votes

---
Tags: unity
---


# Question
Title: Why does my libgdx app just display the badlogic.jpg instead of my start screen?
I have been looking at example libgdx games. It looks like https://github.com/libgdx/libgdx-demo-cuboc is the closest thing to a game I would like to make. I am able to download, compile and execute the Cuboc game no problem. So I follow the instructions for creating a libgdx project (https://github.com/libgdx/libgdx/wiki/Project-Setup-Gradle) and I am able to compile and execute the resulting project which just displays the badlogic.jpg file.

So I start aping the code from Cuboc into my game, which I am calling Malfunction. All I want to do is display my "MainMenu" screen which simply display a png file which I copied from the Cuboc game.

Here's what I have in my Malfunction project:

```
// Malfunction.java
package com.redcricket.malfunction;

import com.redcricket.malfunction.screens.MainMenu;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;

public class Malfunction extends Game {
    private String TAG = "MAL";

    @Override
    public void create () {
        Gdx.app.log(TAG, "MainMenu (Game)");
        setScreen(new MainMenu(this));
    }
}

```

... and this java file ...

```
// MainMenu.java
package com.redcricket.malfunction.screens;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class MainMenu extends MalfunctionScreen {
    TextureRegion title;
    SpriteBatch batch;
    float time = 0;
    private String TAG = "MAL";

    public MainMenu(Game game) {
        super(game);
        // TODO Auto-generated constructor stub
        Gdx.app.log(TAG, "MainMenu (Game)");

    }

    @Override
    public void show () {
        Gdx.app.log(TAG, "show()");

        title = new TextureRegion(new Texture(Gdx.files.internal("data/title.png")), 0, 0, 480, 320);
        batch = new SpriteBatch();
        batch.getProjectionMatrix().setToOrtho2D(0, 0, 480, 320);
    }

    @Override
    public void render (float delta) {
        Gdx.app.log(TAG, "render (float)");

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        batch.draw(title, 0, 0);
        batch.end();

        time += delta;
        if (time > 1) {
            if (Gdx.input.isKeyPressed(Keys.ANY_KEY) || Gdx.input.justTouched()) {
//              game.setScreen(new IntroScreen(game));
                Gdx.app.log(TAG, "all done ...");
            }
        }
    }

}

```

... and this java file ...

```
// MalfunctionScreen
package com.redcricket.malfunction.screens;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Screen;

public abstract class MalfunctionScreen implements Screen {
    Game game;

    public MalfunctionScreen (Game game) {
        this.game = game;
    }

    @Override
    public void resize (int width, int height) {
    }

    @Override
    public void show () {
    }

    @Override
    public void hide () {
    }

    @Override
    public void pause () {
    }

    @Override
    public void resume () {
    }

    @Override
    public void dispose () {
    }
}

```

Update: I also have this java code ...

```
package com.redcricket.malfunction.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.redcricket.malfunction.Malfunction;

public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        new LwjglApplication(new Malfunction(), config);
    }
}

```

So why does this screen appear when I run my modified version of Malfunction?

Also none of my calls to `Gdx.app.log` ever show up in logcat.

Thanks!

# Answer
> 1 votes
Oops! *redfaced* I made a typo in the name of the file I trying to open. In my assets/data folder the file was named `tile.png` not `title.png`. Thanks to Justin-C on #libgdx irc

---
Tags: libgdx
---