# Question
Title: Handling AI with ECS in a turn based roguelike
I am trying to implement the Entity Component System pattern to use in a roguelike game. Right now, I have 3 systems. Input, AI, and Action. The input system basically is just a system used by the player to get input from the keyboard. The AI system is for the NPCs. The action system processes anything with an Action component, which is used to describe either a move, an attack, an item usage, basically anything that advances the game time.

However, I am having trouble with implementing the correct behaviors. It is clear that the player should have a turn, getting his input. If the input is invalid, he repeats his turn, again and again until he makes a turn that passes time. Then the enemies should get their move from the AI system, and initiate it. So what the behavior should be like is this:

```
while(!input.passesTime())
    input.getInput()
    draw()
action.do(Player)
for all Entities with AI
    AI.think(Entity)
    action.do(Entity)
draw()

```

Notice how everything is intertwined and doesn't really make sense as a single (or multiple) system. How can I design this better? Note especially that I need to update the screen everytime, even with invalid inputs since they may write something out (e.g. "Nothing interesting happens").

After some thinking it seems clear that the renderer should also be a system, but this doesn't really clear up the requirements.

# Answer
Note: I'm playing fast and loose with the pseudocode here, so let me know if anything is unclear.

Ideally, the player shouldn't be special - just another set of components. The main function of entities is to group components. You might think of it this way: components get updates, not entities.

From the good old Evolve Your Hierarchy article:

Updates flow *down* from the Component Manager, and entity association flows *across*.

So, you'd start from something like this:

```
while(running)
    turn = timer.Now     // or something, time management is another problem altogether
    foreach ComponentType in ComponentManager ordered by ComponentType.UpdatePriority
        foreach Component in ComponentType
            Component.Update(time)
    foreach Component in ComponentManager.AllComponents ordered by Component.DrawPriority
        if Component is Drawable
            Component.Draw(time)

```

Note the complete lack of references to entities in this loop! The update and draw methods are really the only two special cases you need, and we only tolerate draw being separate as an optimization in the face of system limitations (it's generally better to try and group draw calls, and draw doesn't need to be called every pass) - it's not architecturally ideal. If each component has a reference to its parent entity, it can talk to the other components on its parent entity and there's no need to pass the entity as an argument to its update method. There's no need to have special methods for each component either, since that could just be wrapped into a uniform set of method declarations:

```
Input.Update(time)
    getInput()

AI.Update(time)
    think()

```

Rule of thumb: if you can wrap it, you can combine it into a generic method shared by similar classes.

So, your class hierarchy should look something like

```
class Component { Update(), parentEntity }
class Drawable : Component { Draw() }
class Entity { Components }
class AI : Component { Update() { /* think stuff */ } }
class Action : Component { Update() { /* do stuff */ } }
class Input : Component { Update() { /* get input and pass it on to other components */ } }
// etc.

```

Since this is a turn based game, you'll probably want a game keeper component like

```
class GameKeeper : Component
{
    Update(time)
    {
        if isOdd(time) currentTurn = Player
        else currentTurn = Cpu
    }
    // or use events
    TurnFinished(entity)
    {
        if entity == PlayerEntity
            currentTurn = Cpu
        else currentTurn = Player
    }
}

```

Then

```
class AI
{
    Update(time)
    {
        gamekeeper = FindComponent(GameKeeper)
        if gamekeeper.currentTurn != Cpu
            return
        // otherwise think stuff
        action = parentEntity.GetComponent(Action)
        action.Do("Some action")
    }
}
class Action
{
    Do(message)
    {
        // Get ready to do whatever is in the message
    }
    Update(time)
    {
        gamekeeper = FindComponent(GameKeeper)
        if gamekeeper.currentTurn != Cpu
            return
        // actually do all the things
    }
}

```
> 4 votes

---
Tags: architecture, entity-system, design-patterns, turn-based, roguelikes
---


# Question
Title: How to use traditional pixel coordinates system in OpenGL? (with C++/SDL2)
I find the normalized, centralized coordinate system used in OpenGL weird and annoying, is there anything I can do at all to make it work like normal pixel coordinates on everything ever except OpenGL? And yes, of course I Googled it.

EDIT: I'm using OpenGL 2.1

# Answer
`glOrtho( 0.f, viewWidth, viewHeight, 0.f, 0.f, 1.f );`

Assuming that you're starting from an identity matrix, this glOrtho() call will give you a traditional window coordinate system with 0,0 at the top left corner, such that one unit in OpenGL space corresponds exactly to one pixel in the view which contains the OpenGL-rendered image.

Man page for glOrtho.
> 3 votes

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


title: Efficient parsing of text file to map

text:
# Question
Title: Efficient parsing of text file to map
I am creating a roguelike which will use an ASCII based tile set. There is a text file that represents the map (ie. walls, floor, items). I believe the next steps are to read this file in and use a 2D array to hold objects that represent each of the characters.

My question is, is there a more efficient way to parse through that file and create the object map without using one huge switch statement to create the proper object? If not, is there a better approach I can take overall?

# Answer
> 1 votes
Any modern compiler will almost always convert a large Switch statement into a jump table; not into a succession of nested IF's. This may be ugly code, violating your sense of aesthetics, but is the most efficient means to parse such a structure. If you were to use a Lexer- or Parser-Generator tool such as LEX or YACC or any of their modern descendants, that is exactly what they generate.

Note that if you have different classes to represent the different terrain types, then you have replaced a multitude of repetitive switch statements during game operation with a single switch statement at class generation time. That in and f itself is a ***very*** significant performance improvement.

# Answer
> 1 votes
Can you set them up as a generic `Dictionary<String, Object>`?

```
private readonly Dictionary<String, Object> _tileDefinitions =
    new Dictionary<String, Object>
    {
       {"_", nothing},
       {"#", wallobj},
       {"$", treasureobj}
    };

public Map Parse(string fileContents)
{
    var x = 0;
    var y = 0;
    var map = new Map();
    for(var i = 0; i < fileContents.Length; i++)
    {
        x++;
        if(fileContents[i] == Environment.NewLine)
        {
            x = 0;
            y++;
            continue;
        }
        Tile tile;
        if(_tileDefinitions.TryGetValue(fileContents[i], out tile))
            map[x, y] = tile;
        else
            throw new Exception("Invalid tile " + fileContents[i]);
    }
    return map;
}

```

---
Tags: c#, roguelikes
---


# Question
Title: How to get rid of jerky movement in scrolling? C# / XNA
I'm having a bit of trouble with my code meant to create a scrolling background of random-ish ones and zeros. When moving to the right (or left), it scrolls smoothly for a few seconds, stops/jerks, then starts scrolling smoothly again. I've spent an entire day now trying to iron out this issue and nothing that I've done makes it any better.

Here is my isolated code:

```
    namespace TestScrollyNumbers
    {
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        graphics.PreferredBackBufferHeight = 768;
        graphics.PreferredBackBufferWidth = 1366;
        graphics.IsFullScreen = false;
        graphics.ApplyChanges();
    }

    KeyboardState CKBS = new KeyboardState();

    Random Randomness = new Random();

    Texture2D NumberScrolly1;
    Texture2D NumberScrolly2;
    Texture2D NumberScrolly3;
    Texture2D NumberScrolly4;
    Texture2D NumberScrolly5;

    float XPosScroll = 0;
    float XPosScrollVel = 0;

    int i = 0;
    int meh = 1;

    public List<Texture2D> BackgroundScrollyTextures = new List<Texture2D>();

    public List<float> ScrollyNumberXPos = new List<float>(); //This list contains the final X positions for the number bars.
    public List<float> ScrollyNumberXStart = new List<float>(); //This will be used to calculate the final X positions for each bar.

    public List<int> ScrollyNumberMultiplier = new List<int>(); //List of Y position multipliers so that I can calculate the Ypos in the draw command.
    public List<int> ScrollyNumberType = new List<int>(); //List of randomized textures for each bar.

    protected override void Initialize()
    {
        base.Initialize();

        BackgroundScrollyTextures.Add(NumberScrolly1);
        BackgroundScrollyTextures.Add(NumberScrolly2);
        BackgroundScrollyTextures.Add(NumberScrolly3);
        BackgroundScrollyTextures.Add(NumberScrolly4);
        BackgroundScrollyTextures.Add(NumberScrolly5); //Add all of the possible textures to the list of textures so that each number in the "ScrollyNumberType" list can correspond to a texture.
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        NumberScrolly1 = Content.Load<Texture2D>("NumbersForBackground1");
        NumberScrolly2 = Content.Load<Texture2D>("NumbersForBackground1");
        NumberScrolly3 = Content.Load<Texture2D>("NumbersForBackground1");
        NumberScrolly4 = Content.Load<Texture2D>("NumbersForBackground1");
        NumberScrolly5 = Content.Load<Texture2D>("NumbersForBackground1"); //Loading :P
    }
    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {

        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        CKBS = Keyboard.GetState(); //Current Key Board State

        if (meh == 1)
        {
            for (i = 0; i < 18; i++)
            {
                ScrollyNumberMultiplier.Add(Randomness.Next(0, 11));
                ScrollyNumberType.Add(Randomness.Next(0, 5));
                ScrollyNumberXStart.Add(i * 80); //Each bar is 80 pixels wide
                ScrollyNumberXPos.Add(0);
            }
            meh = 0;
        }

        if (CKBS.IsKeyDown(Keys.Right))
        {
            XPosScrollVel += .6f;
        }
        if (CKBS.IsKeyDown(Keys.Left))
        {
            XPosScrollVel -= .6f;
        } //Scrolling - add to the velocity

        XPosScrollVel *= .9f;
        XPosScroll += XPosScrollVel; //Add the current X Velocity to the X Scroll

        for (i = 0; i < ScrollyNumberType.Count; i++)
        {
            if (ScrollyNumberXPos[i] < -79)
            {
                ScrollyNumberXStart[i] += 1440; //Instead of creating a new bar, use the bar that just went off of the screen and give it a new Y pos value
                ScrollyNumberMultiplier[i] = Randomness.Next(0, 11);
            }
            if (ScrollyNumberXPos[i] > 1365)
            {
                ScrollyNumberXStart[i] -= 1440; //Same thing as before, except reverse.
                ScrollyNumberMultiplier[i] = Randomness.Next(0, 11);
            }
            ScrollyNumberXPos[i] = ScrollyNumberXStart[i] - XPosScroll; //final XPos = where it started, plus how many times it's gone across the screen, minus how much you've scrolled.
        }

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin();

        for (i = 0; i < ScrollyNumberType.Count; i++)
        {
            spriteBatch.Draw(BackgroundScrollyTextures[ScrollyNumberType[i]], new Vector2((int)ScrollyNumberXPos[i], (-37 - 56 * ScrollyNumberMultiplier[i])), null, Color.White, 0, new Vector2(0, 0), new Vector2(1, 1), SpriteEffects.None, 0);
        } //And then draw everything.

        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

}

You can use this image to test my code (I didn't include the four others as that would make this post unnecessarily long) if you don't know the answer right away:

For anyone wondering, I use Microsoft Visual C# 2010 Express and XNA Game Studio 4.0.

# Answer
> 1 votes
I've found a possible solution. Set `this.IsFixedTimeStep` to false.

What this does is syncs Update to Draw so that the game gets updated only as the screen can be drawn. That means that if the game were to lag the game physics (if done in update) would go slower, but it's probably worth it if this graphical glitch is annoying you.

I found another post on the issue so it appears that it is not new. http://xboxforums.create.msdn.com/forums/p/75475/459289.aspx

---
Tags: c#, xna-4.0, scrolling
---


# Question
Title: How to find the point on a hypotenuse divinging triangle into two right triangles?
Consider the following image:

Knowing the (x,y) coordinates of A, B, and C; how would one find the point D? D being the point where line CD cuts the triangle into two smaller right triangles?

I feel like this is elementary, but searching for this is just giving me formulas to find the length of the lines, not the point I am trying to find.

EDIT:

Someone asked before deleting their post if this is a right triangle. Well; it COULD be, but not necessarily.

I should clarify why I need this. I have a quadratic bezier curve, and I want to find this point D on the triangle created by the 3 points (start, end, and control) of the bezier curve. I ultimately intend to check the angles formed by line CD at point C to restrict the "sharpness" of the curve (for road creation)

# Answer
> 2 votes
First you need to find the slope of the line from A to B, then find the perpendicular slope. Lastly, find where the lines intersect.

The trick is that this is not actually a real triangle problem. Instead, you are trying to find the point on a line that is closest to another point (point C). The point on the line that is closest to the point will /always/ be perpendicular to the line, so yeah. Here's a tutorial on that if you're still confused: https://www.youtube.com/watch?v=NFSdyike7g8

Next time, I believe this would go in the "Mathematics" stack exchange forum.

# Answer
> 1 votes
No trigonometry is necessary; just a little vector geometry and linear algebra.

Adopt the convention that \\$\vec v\\$ represents a 2D vector.

Then define two new vectors:

\\$\vec c\ = \vec C - \vec A\\$ *(with coordinates \\$c\_1\\$ and \\$c\_2\\$)*
\\$\vec b\ = \vec B - \vec A\\$ *(with coordinates \\$b\_1\\$ and \\$b\_2\\$)*

Now considering parameterized equations of:

* the line segment \\$\overline{CD}\\$ in terms of \\$t\\$; and
* the line segment \\$\overline{AB}\\$ in terms of \\$s\\$

yields the following affine matrix equation for the intersection point, \\$D\\$, of the two lines:

$$ \begin{pmatrix} 0 & t & c\_1\\ -t & 0 & c\_2 \\ 0 & 0 & 1\end{pmatrix} \times \begin{pmatrix} b\_1\\b\_2\\1 \end{pmatrix} = \begin{pmatrix} s\cdot b\_1\\s\cdot b\_2\\1 \end{pmatrix} $$

Solving for the scalar \\$s\\$ gives:

\\$s=(c\_1\cdot b\_1 - c\_2\cdot b\_2) / ( (b\_1 - b\_2) (b\_1 + b\_2) )\\$

The vector formula for \\$\vec D\\$ is then simply:

\\$\vec D=\vec A+s(\vec B-\vec A)\\$

# Answer
> 0 votes
I figure that there's a really efficient way of computing this but I don't have it in my knowledge, but I'll do my best.

> ΔXYC is a triangle with vertices on points X, Y and C
>
> VW is a line which starts ands ends in points W and V
>
> ^PQR is the angle on point Q that comes and goes to points P and R

Triangles ABC and CDB are congruent, so the scale (Original/Copy) is AB/CB:

> We can calculate the length of CD by using the equation :
>
> AC / AB = **CD** / CB
>
> So **CD** = (AC * CB) / AB

And

^DCB = **^CAB**

> To know the angle you can just use law of sines; (Remeber that SIN((90°)) = 1)
>
> \[ SIN(**^CAB**) \] / CB = \[SIN (90°)\] / AB
>
> SIN(**^CAB**) = CB * 1 / AB = CB / AB

Now you got your polar coordinates of point D **:D**

now you just need to convert from polar to Cartesian. Best of luck.

---
Tags: mathematics, trigonometry
---


title: Kinematic equations script fail

text:
# Question
Title: Kinematic equations script fail
I added the kinematic equations to my code and now none of it works. I get the error rigidbody.torque assign attempt for 'Enemy' is not valid. Input torque is { 0.000000, NaN, 0.000000 }. UnityEngine.Rigidbody:AddTorque(Vector3) EnemyBehavour:FixedUpdate() (at Assets/\_Scripts/Baddies/EnemyBehavour.cs:61)

it should be fine as far as I can tell, please help.

```
//speed of enemy
public float speed = .5f;
//base distance enemy will attack player
public float range = 3f;
//how far back enemy will stand
public float stopDistance;
//what the enemy will pursue
private GameObject target;
//targetable Enemies
private GameObject[] targetable;
//itself
private Rigidbody self;
//distance to check against
private float saveDistance;
//get the mass for physics stuff
float mass;
//gets drag for physics
float drag;
//gets angular drag for physics
float adrag;
//checks distance
float distance;
//the player
GameObject player;
GameObject[] turrets;
//the base
GameObject playerBase;
EnemyShoot Shoot;

void Start () {
    //get own rigidbody
    self = GetComponent<Rigidbody> ();
    //playerbase should be obviouse
    playerBase = GameObject.FindGameObjectWithTag ("Base");
    target = playerBase;

    Shoot = GetComponentInChildren<EnemyShoot> ();

    mass = self.mass;
    drag = self.drag;
    adrag = self.angularDrag;
}

void FixedUpdate () {
    target = FindFoe ();

    //checks range and
    if (Vector3.Distance (transform.position, target.transform.position) > range || target == playerBase) {
        target = playerBase;
    }
    Vector3 acceleration = AnglularAcceleration ();
    Vector3 torque = new Vector3 (0f, acceleration.y * mass,0f);
    print (torque.ToString ());

    //look at the pursueing target
    self.AddTorque (torque);
    //move towards the pursuing target
    self.AddForce (transform.forward * speed);

}

Vector3 AnglularAcceleration () {
    // the variables to figure out
    Vector3 AnglAcc;
    float radius;
    Vector3 theta;
    float time;

    //get the radius
    radius = Vector3.Distance (transform.position, target.transform.position);
    //get the dot product between the two points
    float dot = Vector3.Dot (new Vector3 (transform.position.x, 0f, transform.position.z),new Vector3 (target.transform.position.x, 0f, target.transform.position.z));
    //get the arccosine of the angle and convert that to radians
    theta = new Vector3 (0,(Mathf.Acos(dot))*180,0);
    print (theta.ToString ());

    //now find the time
    time = (2f * theta.y) / speed;
    AnglAcc = new Vector3(0f,(speed * speed) / (2f * theta.y),0f);

    return AnglAcc;

}

//checks if turrets or player is within range
GameObject FindFoe() {
    distance = range;
    targetable = GameObject.FindGameObjectsWithTag ("ETarget");

    //sets player base as default target

    foreach (GameObject test in targetable) {
        GameObject testing = test.transform.parent.gameObject;
        print (testing.ToString());
        saveDistance = Vector3.Distance (transform.position, testing.transform.position);
        if (saveDistance < distance) {
            distance = saveDistance;
            print (saveDistance.ToString());
            target = testing;
        }

    }
    return target;

}

```

}

# Answer
{ 0.000000, NaN, 0.000000 }. NaN smell of division by zero.

check `AnglularAcceleration ()`

```
AnglAcc = new Vector3(0f,(speed * speed) / (2f * theta.y),0f);

```

AnglAcc.Y will be NaN when theta.y =0
> 1 votes

---
Tags: c#, physics, scripting, torque
---


# Question
Title: Change sprite to animation in unity 5 2d (c#)
I want to do the same as this older post with one change:

Change the sprite of a Object in Unity

I want to use a .anim animation (created with unity) after the space key is pressed instead of another sprite. The problem is I can't drag the animation file to the sprite slot in the script component.

Thanks.

# Answer
> 2 votes
You do not have to drag drop animation controller to your script instead you can add component to game object using inspector. Add an `Animator` component first.

On your required key press you have two possibilities as i see:

1. Enable/disable the component as per your need.
2. If you want to run two different states you can use states based animations. Steady State, Running State.

Recommended Read:

Hope it helps!

---
Tags: unity, c#, 2d, animation, sprites
---


# Question
Title: Does converting quaternion to matrix cause a lot of overhead?
This is related to rendering creating a model, view, projection matrix for opengl. While matrix are fairly standard there's a lot of talk about using quaternions for rotations but why would u go from quaternions to matrix and back to matrix?

Quaternions might be faster but if you have to switch to matrix and back again doesn't that overhead eat into using just matrix only?

Is the typical workflow for using quaternions with matrix is to let the quaternion handle the rotation then create a 4x4 matrix from that rotation to concat with translation/ scale matrix in the model-\>view-\>projection matrix stack?

Does converting quaternion to matrix cause a lot of overhead?

# Answer
The best paper out there for performance comparison is from geometrictools according to the paper you need 12 multiplication and 12 addition to convert a quaternion to a matrix, but this is hardly a deciding factor.. you need to look at the bigger picture

Quaternions are great for interpolation because they are numerically more stable than matrices when dealing with interpolations because less operations are involved. This is especially important for skeletal animation. Other than than you can use a matrix for everything including rotations. But if you insist on using quaternions (which is fine btw) the scenario I can imagine you are talking about is that you can separately keep track of scaling vec3, translation vec3 and a quaternion in that you need to build a matrix from and sent it to the GPU, in this case you need to do this for every object every frame it moves. I hardly think this would be a bottleneck unless you profile and it proved to be the problem.

A deciding factor for using matrix vs quaternion for rotation is what your engine is supposed to do, matrices can be more than enough if no precise skeletal animation is involved. Quaternions have the advantage of less memory but unless you are dealing with limited memory (eg. consoles) this is not a problem.

I would hardly optimize unless it is proven to be a bottleneck or I am struggling to get every bit of performance. So the answer it depends on the scale of the game and where the bottleneck is. Read the paper I linked to get a detailed comparison. After all you can hide your transformation in a class and change the implementation if it proves to be troublesome.
> 2 votes

---
Tags: matrix, performance, transformation, quaternion
---


# Question
Title: How to handle collisions without ugly conditionals and type checking?
(I asked a similar question, but this one is far more specific).

How can I handle collisions without having to do a lot of type checking and `if` statements?

People here suggested that when spotting a collision, the collision detector should notify both entities in the collision, and the entities themselves will encapsulate the logic to react to the collision.

I like the idea of having the entities themselves decide how to handle the collisions. However I'm not sure how to avoid doing a lot of type checking and `if` statements inside the `handleCollision` methods.

For example (in psuedocode):

```
class CollisionDetector{
    foreach entity in entities
        foreach otherEntity in entities
            if(collision(entity,otherEntity)) entity.handleCollision(otherEntity);
}

class Entity{
    // .. stuff omitted
    void abstract handleCollision();
}

class Alien extends Entity{
    // .. stuff omitted
    void handleCollision(Entity entity){
        // lots of ugly conditionals and type checking
        if(entity instanceof Missile) die();
        if(entity instanceof Alien) lifePoints -= ((Alien)entity).getDamagePoints();
        if(entity instanceof Wall) setVelocity(0,0);
        // .. etc
    }
}

```

In OOP we should try to avoid type checking and employ Polymorphism. But I don't see how this can be done in this case.

**Is there a way to avoid the ugly type checking and lots of conditionals? Or should I just make my peace with it? How is this most commonly done?**

# Answer
You're correct that the problem (well, nuisance) is the `if` statements. Sadly, no matter what language your working in or what programming fanciness you employ you are going to have to check some component data / entity types / other flags on the colliding entity that will tell the present entity how to react to a collision.

## Good Practices (my experience)

There are 2 practices that I have found useful to minimize these checks.

1. First of all, I find it helpful to think about which entities would actually dictate the collision outcome in real life. Take your `Alien` for example. Imagine a real alien colliding with a real missile, and consider two scenarios:

* The alien, upon making contact with the missile says to himself:

    > By jove, it appears I've struck a missile. My alien behaviour manual says that I must promptly commit suicide.

    after which he pops out a potassium cyanide capsule from between his teeth and swallows.
    * Another possibility is that the missile, upon colliding with the alien says to itself:

    > Wot 'ave we got 'ere? An alien et seems. Looks loike I'm 'upposed to make a right massive explosion.

    The missle then detonates itself.

Neither of these scenarios are realistic, but the second one is a lot closer to what would actually happen than the first. When the `Missile` collides with an `Alien` the reaction should be to blow up. This should, in turn, trigger another event / function call to deal damage to surrounding entities (And methods for doing that have already been discussed). Once the `Alien`'s health reaches 0, *then* he can kill himself1. The code for when the `Alien`'s reaction when colliding with a `Missile` is ... nothing; there's nothing the `Alien` can really do at this point.

I found that when I continually asked myself *Who's really dictating this collision outcome?*, the `elseif` chains for checking types became remarkably short. For example, for a large number of `Entity` types it doesn't matter what the missile is colliding with, the response will be to explode. This might be the default behaviour (i.e. the `else` at the end of your `if`-`elseif` chain). In a similar way it's the `Wall` who stops the `Alien`, not the `Alien` who stops when it collides with a `Wall`. Then all of a sudden it matters little what the moving entity is when it collides with a `Wall`; the reaction will almost always be to stop it (`otherEnt.setVelocity(0,0)`).
2. If you use some variation of an Entity-Component System you can (in some cases, I have found) check for the existence of a component on the opposite entity to determine a subsequent reaction. I won't go into detail about that here since it will make the answer much longer than it already is, and you don't seem to be using an ECS (yet) anyway.

## Long `elseif` chains: A Game Design flaw?

Finally, I will say that if you find yourself coding long `elseif` chains, it could be symptomatic of a design issue: the rules of your game could be too complicated. If you have a long list of different behaviours for each combination of colliding entities, your players will need to memorize (through frustrating trial-and-error or mind-numbing tutorials) all of these potential collision outcomes. If the challenge of memorizing possible collision outcomes is part of what makes the game fun (and you carefully introduce these rules), then long `elseif` chains are to be expected, otherwise, they're sure to be the source of many curse words and damaged controllers / keyboards. If players are confident about the effects certain actions will have, they spend more time thinking about strategy and less time wondering how the game world works.

## An example: Portals

Consider Portal for example: there are walls that support portals (white panels, tan walls, etc...) and the rest don't. There are no walls that make small portals, nor are there walls that permit only orange portals, nor are there walls that periodically support portals... It's easy for game designers and players to understand. So the game could be designed so that when the blue/orange projectile that is shot from the portal gun (not sure what that thing's called) hits a wall it does this:

```
listOfPortalWalls = {'White Panel', 'Tan Wall', 'Concrete Floor', /*etc...*/}

...

class PortalBall{

  ...

  void handleCollision{
    if(listOfPortalWalls.contains(otherEnt.type)) //We can make a portal :)
      /* Test if there's already a portal there (edge case, don't sweat the if statement here) */
      /* Make a portal */
    else //We can't make a portal :(
      /* Explode the portal ball with a discouraging sound effect */
   }
}

```

That `elseif` chain was so short it didn't even have an `elseif`! Notice that it's the `PortalBall`'s job to make the portal (as I would expect if portals were real). The wall wouldn't do anything. All the player has to figure out is which walls support portals. The portal gun never runs out of energy and it has a pretty short cooldown (not to mention that there are seldom time pressure situations), so experimenting to figure out which walls support portals is a painless experience.

**Edit:** To clarify, the `elseif` chains are a fine way of going about things IMO; but you can make things easier by carefully probing which entities are actually responsible for the outcomes of a collision, and placing that code in the relevant `Entity` subclasses.

---

1 This case could potentially be made more realistic by making a system that slowly removes the Alien's available actions restricts behaviours as the health is lowered (e.g. when health is below 50% can no longer attack, and max movement speed is proportional to health). So that when the health reaches zero the alien is a complete vegetable (effectively dead). I would not recommend doing this excessively because if you keep trying to approximate realism your game may become needlessly complicated, making both debugging harder (more code) and game design harder (more complicated game states).
> 7 votes

# Answer
While the conditional block is inevitable, your implementation has one serious flaw:

Every new type of `Entity` you create will require you to alter the `handleCollision()` for **every** entity it could affect - in order for it to respond to the new type of collision. To prevent this you could rather use an attribute in the base `Entitiy` that "classes" each one's collision response.

For example, walls, trees, rocks, etc might all be of an "obstacle" type and they would all **stop** the player, whereas rockets, bullets, lasers, etc would be "weapon" types, which would cause damage...and so on. Then, for stuff like rockets which have a secondary response, i.e. to explode, this should be taken care of in it's own `handleCollision()` instead of the alien's one - because it will always explode, no matter what it collides with, but it may cause no damage to a wall (for instance).

Using this your code would become something like follows (in the alien's `handleCollision()`):

```
class Entity{
    Type type;   // entity type
    int damageAmount;  // damage amount (for required types)
    float bounceCoef;  // a bounce coefficient for static object
    // any other attributes you can think of goes here
    void abstract handleCollision();
}

class Alien extends Entity{
   // .. stuff omitted
   void handleCollision(Entity entity){
      // lots of ugly conditionals and type checking
       if(entity.type == weapon) damage(entity.damageAmount);
       if(entity.type == obstacle) setVelocity(0,0);
       // .. etc
   }
}

class Missile extends Entity{
   Missile(){
      type = weapon;          // just an example
      damageAmount = 100;      // again, example :)
      // setup other attributes here
   }

   void handleCollision(Entity entity){
      // the damage is already done, so this only needs to do it's
      // entity specific action - which is to...
      explode();
   }
}

```

Of course that is a very very basic implementation, but the main benefit here is that when you add new types of entities that fit into the current "types" no further changes are required - you just setup their attributes and create their entity specific collision behavior.
> 3 votes

# Answer
This is pretty much the same solution as the other answers here. However, this handles the question of if the collision should happen in the first place (jump through platforms, ect).

https://gist.github.com/izackp/67949de525305796244a

```
public class CollisionUpdater
{
    List<IPhysics> components;
    public CollisionUpdater ()
    {
        components = new List<IPhysics> ();
    }

    public void AddComponent (IPhysics newComp)
    {
        components.Add (newComp);
    }

    public void RemoveComponent (IPhysics oldComp)
    {
        components.Remove (oldComp);
    }

    public void ReactCollisions ()
    {
        for (int i = 0; i < components.Count; i++) {
            IPhysics objA = components [i];
            objA.Move ();

            if (i < components.Count - 1)
                FindCollisionsWith (objA, i + 1);
        }
    }

    public void FindCollisionsWith (IPhysics objA, int fromIndex)
    {
        for (int j = fromIndex; j < components.Count; j++) {
            PhysicsComponent objB = components [j];
            if (objA.frame.Intersects (objB.frame)) {
                if (objA.ShouldIgnoreCollision (objB))
                    continue;
                if (objB.ShouldIgnoreCollision (objA))
                    continue;
                objA.Collision (objB);
                objB.Collision (objA);
            }
        }
    }
}

```
> 0 votes

---
Tags: collision-detection, architecture, oop
---


# Question
Title: Animator.SetBool: am I supposed to call it only when its value changes?
I've searched around the web for a while, but didn't manage to find anything about it.

Despite using `Animator` in several projects so far, I've never been in this exact situation, so I'm unsure what to do.

Does calling `Animator.SetBool` have any performance issue, so that I'd better call it only when its value has changed, or when its value doesn't change it's so quick that I can call it every frame?

Keep in mind that, due to the nature of this question, I don't care if it's slow when I change its value, I only care if it's slow when it's `false` and I call it to set it to `false` again (same thing for `true` ofc).

# Answer
Those calls aren't free, but they are very fast and usually aren't a problem.

When in doubt, check the profiler for performance hotspots. Unless you're making thousands of these calls per frame, they're probably not a big time sink for your game.
> 2 votes

# Answer
This question falls into the subject of Runtime Analysis.

Assignments are, by nature, constant time operations. From a performance standpoint, you generally don't need to worry about constant time operations.

Since you asked: Any primitive operation(assignment, logical evaluation, etc) are generally considered to take one flop from a runtime standpoint. Occasionally there may be more cycles for other overhead, but as a general rule they are considered to take one flop.

Lets compare pseudocode:

```
Option 1 (Every Frame):
     SET variable = false;     (1 Flop)

Option 2 (Only if necessary):
     IF(variable != false)     (1 Flop)
       SET variable = false;   (1 Flop)

```

So theoretically speaking, with boolean assignment, it's actually slower to try to avoid assignment, than to assign it each frame.

The method declaration for the C# call is :: public void SetBool(int id, bool value); :: the id lookup is an O(1) operation off the heap from a hashtable, and the value assignment is an O(1) assignment.
> 0 votes

---
Tags: unity, performance
---


# Question
Title: What's the difference between the representation of a line and that of a line segment?
What is the difference between a line and a line segment from the implementation point of view?

To me, line segment means:

```
class LineSegment2d
{
Point2d start, end;
public:
    ......
}

```

This representation should be enough to represent a line for any practical purpose in CG. But how do we describe a line and distinguish it from a line-segment?

# Answer
> 0 votes
Technically, a line has no beginning or end. It is infinite in length. For disambiguation, this is often called a ray in graphics programming. A line of this type is described by any point on the line plus a direction.

A line segment is what most people are referring to when they say 'a line'. It has a beginning and an end point. It's common to refer to a line segment simply as a line, since we don't normally deal with lines of infinite length.

Computationally, they are identical. While it's possible to represent an infinite line with only an origin and a direction of arbitrary length, it's impossible to perform calculations on infinities so lines are generally handled the same as line segments, either as two points or as an origin plus a vector (direction with length). It's basically free to store an implicit working length in the direction vector anyway. The only difference is in the inherent meaning. A line segment connects two points, whereas a line or ray passes through two points.

pseudo-code:

```
// 1. defined with {point, point}
lineRay = {{1,2} , {2,3}}
lineSegment = {{1,2} , {2,3}}

// 2. defined with {origin, vector}
lineRay = {{1,2} , {1,1}}
lineSegment = {{1,2} , {1,1}}

```

Here, the lineRay and lineSegment are identical in both definitions. The only difference between the lineRay and lineSegment is in the implied meaning of the points. The difference between the two methods of definition is strategic, depending on how the lines will be used. Graphics are represented with points whereas calculations are generally performed using the vector format. They are also easily converted between by adding or subtracting the origin point.

If for example, you were calculating the intersection of two (non-parallel) unbounded lines (rays) you would simply find the intersection point and return it. If one or both lines are bounded (line segments), you would find the intersection point, then you would perform extra checks to determine if the point falls within the bounds of the segment.

The first method could also be thought of as two vectors where the origin is at {0,0}.

# Answer
> 0 votes
It's hard to tell what exactly you are looking for but line segments are commonly described by their endpoints, or by a point, a normalized direction vector and a length. Another way would be a starting point and a non normalized direction vector which also is the length.

For the purposes of raytracing, I usually use that second form (starting point, normalized direction and length).

The third form could be good if you wanted to work in a parameterized 0 to 1 value "time t". You multiply your time t value by the direction vector and add it to the starting point. This would be useful for moving something from one point to another over time.

Lines can also be described by two points on the line, or by a single point and a direction vector that may or may not be normalized.

There are also of course other ways to describe a line mathematically, but these are the ways I've seen most often in game development.

Does that help at all? If not lemme know, I might have better info for you.

---
Tags: mathematics, graphics-programming
---


# Question
Title: Using deltaTime and Frame Rate Independence
I'm working on one of my first games and I've read that linking your game logic to FPS is bad because it will run differently at different FPS (obviously). I have already made some of the basic game dependent on frame rate and now that I know this, I would like to unlink the logic and render. I've learned that LibGdx has deltaTime in its render method for this, however I believe I'm misunderstanding how I am to use it.

For example, my movement currently looks something like this:

```
if (rightKeyisPressed)
    setVelocityX(movementSpeeD)
playerPos.add(getVelocity)

```

In my case, I would like the player to move 6 units per second. Since I built this on 60 fps, that means that movementSpeed is 0.1. Now the way I have seen deltaTime used is by scaling the movementSpeed based on the time like this:

```
setVelocityX(movementSpeed * deltaTime)

```

However, now I move very slow because delteTime is a very small number. How can I make movement still the same speed without depending on the fps? Sorry if I'm missing something obvious, I just can't seem to wrap my head around this.

# Answer
> 3 votes
This is because movementSpeed should be how many units you would like your character to move *per second (so your movement speed should be 6, for 6 units per second)*, and multiplying that by deltaTime in LibGDX will give you a value that will achieve the movement of *movementSpeed* per second. Delta times work differently depending upon how they are implemented, and in LibGDX this is how the default way is done, I hope this all made sense - I can elaborate more if needed, I hope I understood your question.

---
Tags: libgdx
---


# Question
Title: LibGDX viewport touch coordinates transformation
I've been trying to get LibGDX's viewport and camera unproject() to work and so far none of the tutorials/answers I've found have worked for me. I have a game window of 840x480 units with FitViewport. If the screen resolution matches the aspect ratio of the viewport, the coordinates are unprojected correctly. If it doesn't and the viewport inserts black bars, the transformation is incorrect (see below):

I'd like for the shape to be drawn where the cursor is, since the current behavior makes touch input on Android absolutely useless...

Furthermore, on Android the viewport doesn't fill the entire screen and just produces a rectangle on the bottom left quarter of my 1920x1080 px display.

Here's the code that produces this:

```
public class MainScreen extends ApplicationAdapter implements InputProcessor {
OrthographicCamera camera;
Viewport viewport;
Vector3 worldCoordinates = new Vector3();
Shape shape, background;
public ShapeRenderer sr;

@Override
public void create() {
    worldCoordinates = new Vector3();
    camera = new OrthographicCamera(800,480);
    camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
    viewport = new FitViewport(800, 480, camera);
    viewport.apply();
    sr = new ShapeRenderer();
    shape = new Shape(this, 20, 20, 0, 0);
    background = new Shape(this, 800, 480, 0, 0, Color.WHITE);
    Gdx.input.setInputProcessor(this);
}

@Override
public void resize(int width, int height) {
    viewport.update(width, height);
    camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}

@Override
public void dispose() {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void render() {
    camera.update();

    Gdx.gl.glClearColor(0, 0.1f, 0.1f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    background.render();
    sr.setProjectionMatrix(camera.combined);

    shape.posX[0] = (int) worldCoordinates.x - shape.sizeX[0] / 2;
    shape.posY[0] = (int) worldCoordinates.y - shape.sizeY[0] / 2;

    shape.render();
}

@Override
public boolean mouseMoved(int screenX, int screenY) {
    worldCoordinates = camera.unproject(new Vector3(screenX, screenY, 0));
    return true;
}

@Override
public boolean keyDown(int keycode) {
    throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public boolean keyUp(int keycode) {
    throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public boolean keyTyped(char character) {
    throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    return true;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    return true;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}

@Override
public boolean scrolled(int amount) {
    throw new UnsupportedOperationException("Not supported yet.");
}
}

```

And the Shape class:

```
public class Shape extends Element {
public Color background;
ShapeRenderer sr;
public Shape( MainScreen ms, int sizeX, int sizeY, int posX, int posY){
    super(sizeX, sizeY, posX, posY);
    sr=ms.sr;
    sr.setAutoShapeType(true);
    background = new Color();
    background.set(1, 0.533f, 0, 1);
}
public Shape(MainScreen ms, int sizeX, int sizeY, int posX, int posY, Color background){
    super(sizeX, sizeY, posX, posY);
    sr=ms.sr;
    sr.setAutoShapeType(true);
    this.background = background;
}

@Override
public void render(){
    sr.begin(ShapeRenderer.ShapeType.Filled);
    sr.setColor(background);
    sr.rect(posX[0],posY[0],sizeX[0],sizeY[0]);
    sr.end();
}
}

```

I have tried literally every option I could find without any result. Thank you for any help.

# Answer
> 10 votes
I hope I am understanding your question correctly -- if not let me know.

I believe the following is where you are unprojecting the coordinates:

```
@Override
public boolean mouseMoved(int screenX, int screenY) {
    worldCoordinates = camera.unproject(new Vector3(screenX, screenY, 0));
    return true;
}

```

Because you are using a viewport, you must add the viewport's x/y/width/height to unproject as well:

```
worldCoordinates = camera.unproject(new Vector3(screenX, screenY, 0), viewport.getScreenX(), viewport.getScreenY(), viewport.getScreenWidth(), viewport.getScreenHeight());

```

And this should hopefully cause a more correct calculation, I hope I was able to help!

---
Tags: java, libgdx, transformation, touch, viewport
---


# Question
Title: Using fixed timestep and interpolating states makes physics fall behind one frame. Does that affect responsiveness?
The title says it all, but let me build more into the question:

I suppose everyone by now knows the Fix Your Timestep article, and its proposal to free your physics engine steps from your rendering steps. Which you can accomplish by accumulating time generated by the renderer and consuming it in fixed step sizes.

The interesting part is that Glenn Fiedler tells you to interpolate the previous and the current frame, which lead me to the following question:

**Doing such will make the rendering lag one frame behind the physics. Won't that affect my input responsiveness?** Since I'll take one more frame to see the results of my actions.

One may be inclined to say that one frame doesn't make that much of a difference, but then, these three articles of Mick West, one of the founders of Activision and former programmer of "Tony Hawk's Pro Skater" series says otherwise:

1. Pushing Buttons
2. Measuring Responsiveness in Games
3. Programming Responsiveness

So again, the question: **Interpolating the previous and current frame, will make me lag one frame behind. Will that hurt my input responsiveness?**

# Answer
> 0 votes
After some time and research, I got to know that you actually lose only one physics step, and not a whole game frame.

And if you're updating your physics at a high rate (you should update it at least two times faster than the expected frame rate!), then it will probably go unnoticeable.

In my game I'm using a 0.008s (125fps) physics step and can't barely notice the lost step due to interpolation, but if I turn the interpolation off, then I immediately notice the stuttering.

I went for 0.008s step because I found it a good value to avoid rounding errors (which happens on 0.0083333s for 120fps), which helps a lot to keep stability between runs in different architectures.

EDIT: Since PCs use a IEEE 754 representation of floating numbers, 128fps seems to be a sweet spot, since it's:

1. Divisible by two (giving less precision errors)
2. At least two times higher than 60fps (which should be most people rendering frequency)

Consider using this value.

# Answer
> 0 votes
Converting comment to answer:

Yeah it totally will. You can try and hide it through predictive animations and other things, but that's all smoke and mirrors. It will affect responsiveness definitely. How bad it is depends on your frame rate of course. It also depends on the needs of your game. A twitch game like quake would show the problem very clearly while in a typical rts, it wouldn't be noticeable.

---
Tags: physics, input, interpolation, fixed-timestep
---


# Question
Title: Create a "genie" effect in fragment shader GLSL
I have tried a while now to create a genie effect on a scrolling plane to emulate the background/floor from the Mad Hatter fight in Adventures of Batman and Robin (SEGA).
Judging the way the 16 bit era loved using scan-lines to create most of these (in this case amazing) effects I wanted to try and achieve this effect in GLSL. What I have tried to do so far was to adapt this tutorial code here and convert it to work in the fragment shader instead of the vertex shader, mostly because I haven't dabbled much with model loading (creating grids by hand isn't fun) but have created this monstrosity.

So far I am at step two where the float `t` gets introduced, instead of getting a leaning trapezoid like shape I only get this:
The square is just squished more on the x-axis instead of actually doing anything useful for me, this is my current fragment code for manipulating the image:

```
#version 330 core
precision lowp float;

out vec4 color;
in vec2 UV;

uniform sampler2D in_Tex_0;
uniform vec4 in_Val_0;

vec2 dist(vec2 coord)
{
    // xy range of transformation
    vec2 start = vec2( 0.0, 0.0 );
    vec2 end = vec2( 1.0, 1.0 );
    vec2 pos;
    // in_Val_0.x instead of size param in tutorial
    pos.y = mix( start.y, end.y, in_Val_0.x );
    float t = pos.y / end.y;
    pos.x = mix( start.y, end.x, t * in_Val_0.x );
    // should return a leaning trapezoid
    return coord * pos;
}

void main()
{
    // Pass through color data to bound framebuffer using distorted texture
    color = vec4( texture2D( in_Tex_0, dist( UV ) ) );
}

```

I'm suspecting there's something wrong with the ´t´ that gets added in the mix, but I am at a loss of what. Any idea of what might be wrong and/or how I could fix this?

# Answer
You don't need the mix calls if start and end are always 0 and 1, respectively. If you want a trapezoid:

```
vec2 dist(vec2 coord){
    vec2 pos;
    pos.y = in_Val_0.x;
    vec2 trapezoidSize = vec2(0.2, 0.8); //0.2 baseSize; 0.8 topSize;
    float t = trapezoidSize.x + trapezoidSize.y*coord.y;
    pos.x = t * in_Val_0.x;
    return coord * pos;
}

```

If you want that distorted "trapezoidish" image:

```
vec2 dist(vec2 coord){
    vec2 pos;
    pos.y = in_Val_0.x;
    vec2 trapezoidSize = vec2(0.2, 0.8); //0.2 baseSize; 0.8 topSize;
    float t = coord.y;
    t = (3.0 - 2.0 * t) * t * t;
    t = trapezoidSize.x + trapezoidSize.y*t;
    pos.x = t * in_Val_0.x;
    return coord * pos;
}

```
> 0 votes

---
Tags: glsl
---


title: Does SpriteKit follow the MVC pattern?

text:
# Question
Title: Does SpriteKit follow the MVC pattern?
I am currently working on an iOS project called Old Frank that I have been trying to follow a MVC design pattern.

The gist of it is.

```
GameObjects(model) <- Scene(controller) -> Sprites "SpriteKit" (View)

```

Now if I understand MVC correctly you can't use a lot of the features that SpriteKit has to offer if you want to follow MVC. For instance any `SKAction`, collision detection, etc.

Isn't it up to the model where game objects are located and how they should react when touching other objects? Isn't it up to the model to determine location over time?

Are there any parts of SpriteKit that would be considered okayto use as the "view" in MVC other than rendering?

# Answer
Your question is a good one. I've had exactly the same question regarding SpriteKit and have been very confused about the lack of information on the web about this. SpriteKit seems to encourage you to put all of your Model-View-Controller code into the same class (your SKScene subclass), which is really confusing to me. How would you ever build a game of any complexity using that technique? Combining game state (score, numLives, etc), with controller code like touchesBegan/Ended, and view rendering all in the same class gets really hard to manage beyond the simplest of games.

I agree that using the memento pattern to help with persistence is a good idea, but I also think moving to a MVC design could be beneficial. I am currently moving my game into an MVC architecture. My current approach is to have my model (game objects) manage the physicsBodies, the SKScene subclass act as the controller, and a separate class to act as the view to configure and render the visual aspects of SKNodes in the scene. I'm only part way through the process, so can't say for sure if this will be a good design, but it seems like it will be far better than have a 10,000 line subclass of SKScene.
> 5 votes

# Answer
In simple terms a common design in SpriteKit games is scenes, layers, nodes and child nodes.

You might make each part into a discrete class that encapsulates all of the parts, properties and methods.

For example a Background class that has layered images, particles, various properties like the speed each layer should move and public methods to start and stop scrolling the background.

In this design you assemble these discrete classes that do their own work into the Scene which mostly handles running update:, physics, touch events etc.
> 1 votes

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


# Question
Title: Mapping "Color" parameter from SpriteBatch.DrawString() function to a custom shader
I've recently found a nice way to render text in XNA with custom font AND custom shader.

Here is the game code\**:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Reflection;

namespace Custom_SpriteFont_Test
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont Font1;
        SpriteFont Font2;
        Effect FontEffect;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 768;
        }

        protected override void LoadContent()
        {
            Font1 = Content.Load<SpriteFont>("1");
            Font2 = Content.Load<SpriteFont>("2");
            FontEffect = Content.Load<Effect>("FontEffect");

            spriteBatch = new SpriteBatch(GraphicsDevice);
        }

        protected override void Draw(GameTime gameTime)
        {
            float fontScaleModifier = 1;

            GraphicsDevice.Clear(Color.CornflowerBlue);

            FontEffect.Parameters["Projection"].SetValue(Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1));

            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, FontEffect);

            FontEffect.Parameters["Color1"].SetValue(Color.Red.ToVector4());
            FontEffect.Parameters["Color2"].SetValue(Color.Blue.ToVector4());

            spriteBatch.DrawString(Font1, "Hello world ~!(*)     $100", new Vector2(0, 0), Color.Red, 0, Vector2.Zero, 0.6f * fontScaleModifier, SpriteEffects.None, 0);

            FontEffect.Parameters["Color1"].SetValue(Color.Green.ToVector4());
            FontEffect.Parameters["Color2"].SetValue(Color.Blue.ToVector4());

            spriteBatch.DrawString(Font2, "Hello world ~!(*)     $100", new Vector2(0, 100), Color.Red, 0, Vector2.Zero, 0.2f * fontScaleModifier, SpriteEffects.None, 0);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

And here is the shader code:

```
float4x4 Projection;
float4 Color1, Color2;
float FontHeight;
float2 Location;

Texture2D FontTexture;
sampler TextureSampler = sampler_state
{
    texture = <FontTexture>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = clamp;
    AddressV = clamp;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 Texture : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 Texture : TEXCOORD0;
    float2 OriginalPosition : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    output.OriginalPosition = input.Position;
    output.Texture = input.Texture;
    output.Position = mul(input.Position, Projection);

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    //float4 fontColor = lerp(Color1, Color2, (1.0 / FontHeight) * (input.OriginalPosition.y - Location.y));
    //return tex2D(TextureSampler, input.Texture)*  fontColor;
    float4 originalColor = tex2D(TextureSampler, input.Texture);
    float4 fontColor = lerp(Color1, Color2, originalColor.r)*originalColor.a;
    return fontColor;
}

technique Technique1
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

\**Mind: you will need two font files "1" and "2" in you content folder to run it.

If you launch it you will immediately see the problem: only the second pair of colors is being applied for every line of text rendered. Calling Effect.Passes\[0\].Apply() will not help. If you write text without the custom shader, you can write two lines of text within the same spritebatch.Begin()..spritebatch.End() construction with TWO different colors (as specified in spriteBatch.DrawString() method) - and that is precisely what I want.

You might have noticed that the font texture here is being mapped automatically (two different fonts will render properly without specifying the font texture into the custom shader), so I am sure there is some way to map the colors as well.

Ideally I want this:

```
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, FontEffect);

        spriteBatch.DrawString(Font1, "Hello world ~!(*)     $100", new Vector2(0, 0), Color.Red, 0, Vector2.Zero, 0.6f * fontScaleModifier, SpriteEffects.None, 0);

        spriteBatch.DrawString(Font2, "Hello world ~!(*)     $100", new Vector2(0, 100), Color.Green, 0, Vector2.Zero, 0.2f * fontScaleModifier, SpriteEffects.None, 0);

        spriteBatch.End();

```

And the output text should be rendered with Red and Green color respectively, only with my custom shader.

P.S. I might have been unclear with my shader accepting two colors and not one: it would be enough if I could map just one color for my shader.

# Answer
> 1 votes
Ok, found it. It sits in shader inputs, here is the shader that works:

```
float4x4 Projection;

Texture2D FontTexture;
sampler TextureSampler = sampler_state
{
    texture = <FontTexture>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = clamp;
    AddressV = clamp;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 Texture : TEXCOORD0;
    float4 Color : COLOR0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 Texture : TEXCOORD0;
    float4 Color : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    output.Texture = input.Texture;
    output.Position = mul(input.Position, Projection);
    output.Color = input.Color;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 originalColor = tex2D(TextureSampler, input.Texture);
    return originalColor*input.Color;
}

technique Technique1
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

**UPDATE:** as I subsequently learned, the shader can be further simplified like this:

```
Texture2D FontTexture;
sampler TextureSampler = sampler_state
{
    texture = <FontTexture>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = clamp;
    AddressV = clamp;
};

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 originalColor = tex2D(TextureSampler, texCoord);
    return originalColor*color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 main();
    }
}

```

See Custom SpriteEffects Sample for further info.

---
Tags: xna, shaders, fonts
---


# Question
Title: When prototyping, how can I more easily explore game behaviour?
I build indie games myself, but I'm usually out of energy once I've taken a newly developed game to a level where it's possible to play with behavior, so I settle for refinement instead of exploration. With awful results.

<sup>(picture from the Intercom blog)</sup>

For example, I find that the iteration cycles for tweaking behavior (i.e. linking and restarting a C++ application) are so long that they kill all creativity. I'm building a tool to deal with this.

What other ways exist to quickly explore game behavior? I'm interested in the methodologies used by indie developers as well as larger companies.

# Answer
> 2 votes
I built a prototyping tool called **Trabant** which:

* is 3D and game mechanic ***ONLY*** (no UI, no text, nothing);
* requires *extremely* little code and *no* assets to build a prototype;
* 3D models are created in *code using ASCII art*;
* allows sub-second iterations;
* has rigid-body simulation support;
* works on Windows, Mac, Linux and iOS;
* uses a well-known general-purpose language, Python;
* has an IDE for Windows and iOS.

I built 30 test prototypes in it to verify the above.

As Trevor Powell emphasized iterations need to be \<5 seconds, and I find \<1s iterations almost five times as good. `:)`

Anko mentioned that using a dynamic language is a good idea, I picked Python since it is one of the most widely used. Regarding build automation, testing in Trabant is as quick as pressing F5 in the IDE (or F6 to test it on your iPad), and since there is no build step involved it doesn't get more instant than this.

Throwaway code was one of Nevermind's takeaways. I totally agree, and Trabant enforces it.

# Answer
> 31 votes
As you've noted, when you're working on game mechanics, speed of iteration is critical. The longer the time between thinking of a modification and being able to test with that modification, the less productive you'll be, and the more distracted you'll become. As a result, you definitely want to be managing your iteration time.

For me, I find that my productivity really starts dropping off when the time to test a simple change exceeds about five seconds. So when you're experimenting to perfect the way the game feels, one of your goals has to be figuring out "how can I make a change and then be playing using that change in under five seconds". It doesn't really matter how you do it, as long as you can hold that iteration time down to about that level.

Lots of big modern engines (Unity, Unreal, etc) tend to do this by putting their editor inside the game engine, so you can make most modifications live, without ever restarting the game. Smaller engines/games typically focus work in the other direction; make the game compile and launch so quickly that it doesn't matter if you have to restart the game for each change; you'll still be in and testing before that five second period is up.

In my current project, it takes about ten seconds for me to do a small recompile, link, launch the game, and then reach gameplay (most of that is generating renderable world geometry when loading a saved game). And that's much too long. So I've created separate "testing" game modes which let me test different parts of the game without loading all the real game assets, so I can get in and out much, much faster; typically in about two to three seconds. If I want to test some UI, I can do that without loading into the real game. If I want to test rendering, I have a another mode where I can test that, again without loading up the whole game system.

I've seen other folks who have approached the problem by placing game logic into a DLL, and letting the already-in-memory game executable reload the DLL while the game is running, so you can rebuild the DLL and just reload it inside an already-loaded executable, so you don't need to reload/rebuild your game's art assets. This seems like madness to me, but I've seen it done.

Much simpler than that would be to specify game behaviours and/or configuration in scripts or data files, and provide a way to make your system re-load those files, either on demand, or perhaps just watching them for modifications, without needing to shut the game down, re-link it, and then start it up again.

There are plenty of approaches. Pick what works best for you. But one of the keys to successful refinement of game mechanic is extremely rapid iteration. If you don't have that, it almost doesn't matter what else you do.

# Answer
> 20 votes
To prototype well, reduce the cost of testing ideas.

My workflow is tuned for small games, but I've found these things helpful:

* **Prototype-friendly tech** I've found it helpful to use a dynamic programming language and framework, such as Lua (LÖVE is nice for 2D), JavaScript or Lisp/Scheme where getting the program to do something requires minimal keystrokes, even at the cost of everything else. Once you know what you want, and want to refine it, optimise or port to some other engine.
* **Version control** Keep prototypes in a revision controlled repository. Branch early, branch often. This keeps you comfortable trying things without worrying you'll lose or forget something. (Git has the cheapest branching model.)
* **Build automation** Make sure you need to do as little as possible to actually get the thing to run. In my opinion, even having to press a button is too much: I usually have a `Makefile` with a `make watch` target that runs `inotifywait` in a loop, reacting to file changes by automatically compiling/running the game. In an interpreted or JIT-compiled language, this is instant.

# Answer
> 11 votes
As a developer focusing mostly on prototyping, here's a bit of advice from my experience.

1. Use an engine that allows you to make changes FAST. This includes things like "Not waiting for compilation", but also "changing things at runtime", "ease of debugging", "availability of test assets" etc. I personally love Unity3D, but it's not *the* best tool out there. Best tool depends on the game: for example, Unreal Engine compiles code way slower than Unity3D, but it can quickly launch multiple connected clients. For a networked game, this often offsets the compilation costs. Consider also familiarity. If you're a whiz with C++, even the best Javascript engine won't do much good, and vice-versa. Don't spend time struggling with unfamiliar tech (I mean, do learn other languages/frameworks, but not at the same time as making important prototypes).
2. Learn to scrap existing features mercilessly. Clinging to stuff that you already implemented is anathema to successful prototyping, but letting go of your work is hard.
3. If you don't work with a game designer, put a clear line between "wearing a programmer's hat" and "wearing a designer's hat". Adding a new cool gameplay feature seems very tempting, but *don't* do that when you're in the designer position. Rather try to create fun gameplay (preferably multiple variants) with what you have; make a list of features that would help and *then* implement (some of) them.
4. Rapid prototyping involves balancing between two opposites. You want to make stuff as fast as possible, so you write bad code. But you want to *change* stuff as much as possible, so you have to write good code! Learn to balance these two. Sorry, I can't think of any concrete advice on how to actually do this, but at least be conscious of this problem (-8

Look at how much time your prototyping requires. In my experience, you want to have a playable version of anything in two day max - starting from scratch; and you want to be testing one or two new features every day. If you're not meeting these targets, search for ways to be faster.

# Answer
> 5 votes
One can split game development between these four phases:

* prototyping
* gameplay refinement
* development
* performance refinement

Gameplay exploration I believe happens mostly on the prototyping phase and these are some advice I try to follow:

* Begin designing with a paper prototype. After you have a clear idea of what the game could be, start coding it so that you can actually feel the interactions. Maybe this is useless for 3D games but personally it has helped me a lot in the past.
* Code knowing that you will throw away your code after you are done. This will allow you to be liberal when it comes to what game engine to choose.
* Fast iteration cycles are important (as others have pointed out previously). Choose a game engine based on its ability to quickly show you what you coded. You also don't have to care about performance or graphical fidelity at this phase.
* Limit your scope. If the actual gameplay is 2D (usual strategy game, JRPG), prototype in 2D. In this phase you only care about feedback on the **gameplay**.
* Don't waste time polishing or searching for assets. Scribble something on a paper, take a photo of it, cut it in Photoshop, maybe color it and use it as a sprite. Turn on your microphone and say "pew pew". Put two cubes and a sphere together and you have a robot. Always keep in mind, exploring gameplay possibilities is your first and only priority.

After deciding on a prototype that is fun, start refining it. I don't think there is a reason to switch technologies yet except if there is a gameplay element that needs it.

Later in the development phase, you'll keep the refined prototype at hand while developing a new, much better looking, much better sounding, much better feeling game. Here you have to choose the actual game engine to use.

In the end, take what you have and tune it to use less resources.

Most of what I describe above it common knowledge but putting it out on a list, compartmentalizing the whole development process, helps me put each step in perspective. I hope it helps you too.

# Answer
> 4 votes
I agree with Trevor Powell's answer that speed of iteration is critical for you to stay in the creative mood instead of just polishing. A big source of inspiration for me is Bret Victor's talk, "Inventing on Principle". Unfortunately, it's hard to find real tools at that level. I tried to build one myself for Python development that lets me run my Python code while I'm typing it. It's called Live Coding in Python.

# Answer
> 1 votes
In addition to Trevor Powell's iteration speed which is really important, here are some other useful considerations:

Its like good code...

A lot of IFs in there.

The more solid the concept the less you need to toy around. If you know what the meat of you are trying to do is, prototyping becomes - what to put and how to arrange things in relation to the central pillar (your main thing).

If you are starting out like many others - not quite sure what you want to do, you head in a direction and explore much in the way of the image you showed.

Either way commitment to a technology is irrelevant if what you are looking for can be simulated without much depth - prototype it on whatever you want/can.

Do not waste a single extra second on resources. Download everything off the internet. Proprietary or not. You are looking to get a feel of your concept at work - unless graphics is your main feature nobody's going to sue your for experimenting with other people's sounds, textures and everything, you're not putting it on the shelf in the store just yet. Unless you are already funded - convincing people the concept is worthwhile is the thing that is going to get you the money to get the resources you want. I've seen game studio folks present game concepts with modded versions of proprietary games that they have no rights to.

Its like you are building a scale model. While its awesome to have a miniaturized life replica of what you want. Sometimes its enough to cut it out of magazines, hand craft and glue the pieces together. Everybody with a smudge of imagination is not going to assume you will actually build the skyscraper out of the same cardboard you showed the scale model with. And in the creative industries - its kind of more preferable to work with people with some imagination. If they can't look past some draft problems to see potential behind a whole concept, they will rarely if ever appreciate a product. No appreciation means they are less willing to commit and thats a downward spiral. Its the difference between setting up your kid's attitude to conquer the world and instead telling "You can't even tie your shoes properly you little dipshit, whatever in the nine hells gave you idea you could succeed with making a kite?"

Whatever you may be doing always remember attitude alone is more than enough to ruin anything absolutely regardless of its technological or economic potential.

I once prototyped a game using exclusively gif images and giving them a little something to do with javascript. Its not dazzling but it served the purpose of showing what i wanted to show. Doesn't matter if you later develop it for Xbox exclusively.

If your idea is more complex than a simple prototype, then you are going to have to put research into the tech you'll use - since the prototype is going to the be scaffolding for the the final thing (simply because a lot is invested in it and it cannot be thrown away lightly) - if you get it approved obviously.

---
Tags: c++, game-design, prototyping
---


# Question
Title: How do I query a LibGDX Box2DLights "light" and "dark" regions?
I have lighting implemented using Box2dLight. I want to update/render things inside the player's PointLight area. Stuff in the dark area should not be rendered.

How can I find which areas are *lit* or *dark*?

---

My `PointLight`s and `Body` look like this:

# Answer
> 4 votes
I found the solution, so I think I should write here for other ones later. First I download the source code of box2dlights. Then open BaseLight.java and find "segments" member variable. This variable contains all information about what I was finding. This code below is just for debugging purpose:

```
    rayHandler.setCombinedMatrix(camera.combined);
    rayHandler.updateAndRender();
    //Only first two elements are positions
    float[] vertices = new float[spriteLight.segments.length/2];
    int count = 0;
    for (int i=0;i<spriteLight.segments.length;i+=4)
    {
        vertices[count++] = spriteLight.segments[i];
        vertices[count++] = spriteLight.segments[i + 1];

    }

    shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
    shapeRenderer.polyline(vertices);
    shapeRenderer.end();

```

Result:

---
Tags: java, libgdx, box2d, lighting, occlusion
---


title: Playing with hashmap in drawing

text:
# Question
Title: Playing with hashmap in drawing
I'm developing a game in Java for Android, using LibGDX. In my render(), between the batch.begin() and batch.end() I'm running through all the game objects and draw them.

Every game object is stored in a list, which that list is stored inside a hash map. I iterate through this hash map, getting every list and going through that list, like this:

```
    batch.begin();
    Iterator it = objectsMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        Array list = (Array) pair.getValue();
        for (int i = 0; i < list.size; i++) {
            GameObject object = (GameObject) list.get(i);
            drawObject(object);
        }
    }
    batch.end();

```

My drawObject() code:

```
private void drawObject(GameObject object, float x, float y) {
    if (object == null) {
        return;
    }
    if (object.getVisibility()) {
        TextureAtlas.AtlasRegion currentFrame = object.getCurrentFrame();
        if (currentFrame != null) {
            float objectAlpha = object.getAlpha();
            Color color = batch.getColor();
            if (objectAlpha != 1) {
                color.a = object.getAlpha();
                batch.setColor(color);
            }
            batch.draw(currentFrame, x - object.getOriginX(), y - object.getOriginY(), object.getOriginX(), object.getOriginY(), currentFrame.getRegionWidth(), currentFrame.getRegionHeight(), object.scaleX, object.scaleY, object.getSpriteDirection());
            color.a = 1;
            batch.setColor(color);
        }
    }
}

```

A method called setRegion() sets the current animation frames of the object:

```
protected void setRegion(String name, float frameDuration) {
    currentFrame = atlas.findRegion(name, 0);
    if (currentFrame == null) {
        currentFrame = atlas.findRegion(name, -1);
    }
    width = currentFrame.getRegionWidth();
    height = currentFrame.getRegionHeight();
    animationStateTime = 0;
    animation = new Animation(frameDuration, atlas.findRegions(name),      Animation.PlayMode.LOOP);
}

```

And in the update() of the objects this is called:

```
            currentFrame = (TextureAtlas.AtlasRegion) animation.getKeyFrame(animationStateTime, isLooping);

```

The getCurrentFrame() method only returns currentFrame variable. The alpha is a field with a value between 0 and 1. (getAlpha() returns only the field)

My question is that considered a "heavy" activity? Can this be a significant impact on the FPS values? Because I'm running my game on old devices (like Galaxy S2) and the FPS can get pretty low values. I'm trying to find the cause to it.
I used to have a reference to every list but with the time I realized I'm going to have too much lists, so I decided to do it like this. Maybe you know a better way of holding references to all game objects?

Thanks!

# Answer
> 2 votes
Basically, what a hashmap does is store the objects in a random location in your memory. Complexity is O(1) which means that it will always take the same amount of time to retrive an object from the hashmap. The amount of time depends on various factors. This might be quite fast for few objects, but as soon as you start drawing scene with hundreds of objects, I would consider a hashmap as very poorly performing (poor FPS as a result).
The reason for that is simple. Your memory has to go to get the object from a different location for every object. A more performant approach would be to store all objects right next to each other in memory (which in turn would be a very bad hashmap), so that you could go on where you left off in memory. Depending on the device and your application, this might as well be a major performance gain.
Also take a look at the Entity-Component-System, this article about data locality (which is the specific answer for this very question) and also all other articles on gameprogrammingpatterns.com. You might be able to improve other parts of your code as well :)

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


# Question
Title: Pathfinding and collision avoidance on mobile
Currently I'm developing a Diablo like game for mobile platform(iphone5+).

A simple A\* search will find the path, but collision avoidance still needs to be taken into consideration.

There will be about 50 monsters active at the same time, so performance is very important.

I found some methods that might work.

1. NavMesh + RVO

The recast/detour library works well on the `pathfinding` part, but its crowd simulation quickly reach the limit(more than 5ms for 30 agents).

Another library RVO2 seems fine(less than 2ms for 50 agents), but the library has some license issues.
2. Flow Fields \+ Physics Engine

Many RTS games use this method, but it seems that a physics engine is required to resolve collisions. If many agents don't share a common goal, this method might cost more than traditional A\* pathfinding.
3. Steering Behaviors \+ Physics Engine

Steering Behaviors includes many concepts, I think `simple avoidance behavior` might work(just turn left/right if there is something in front) , but the method still requires a physics engine to work together.

I'm still not sure which one to use, maybe there exists other pathfinding and collision avoidance methods.

P.S. `Halo:Spartan Strike` uses Havok AI(based on RVO?), but I didn't see many enemies in that game, so I wonder whether the first method(NavMesh + RVO) will works well on mobile platform.

# Answer
> 4 votes
This is a pretty interesting question, and i'm going to try to contribute with what I can.

First, I think you have to clearly define the boundaries for the game you are trying to create, and define those questions (some may already been answered).

* How far the is the monster aggro ?
* How many monsters at the same time is your target?
* How is your terrain organized? Is it tiled?
* How much collision avoidance do you want?

To quote an answer from here on how pathfinding is done in starcraft 2:

> Starcraft II uses a constrained Delaunay triangulation of the map terrain and buildings to produce a navmesh; A\* with a funnel filter is used to path along this mesh, taking into account unit radii; then local steering and collision avoidance layers are added on top of that, including a cooperative "push idle units out of the way" feature where it is possible to displace a unit instead of pathing around it in certain cases. Additionally, units moving in parallel are ignored for collision avoidance purposes since they can be guaranteed to not affect each other; \[...\] SC2 uses six steering forces: following, flocking, grouping, separation, avoidance, and arrival.

So going back to your 3 propositions:

1. **NavMesh + RVO** -\> If there are license issues, then it is not an option. It might be the easiest implementation though.
2. **Flow Fields + Physics Engine** -\> It depends honestly, but it seems really compute intensive in a semi dynamic environment as what you want
3. **Steering Behaviors + Physics Engine** -\> Steering behavior seems to me the way to go. That way you can define some pretty nice flock behaviors for your game, depending for example on the monster type. And it scales well with the mob number. However, i would stay away from physics for collision detection. Simple avoidance behavior is enough, reducing speed or increasing, turning, etc.

Some notes on the Steering behaviors, you can define as much steering forces as you need, with the areas you want. You need at least 3, for flocking/attraction/repulsion, but more are probably interesting.

Then, try to find a library that does steering behaviors to see if it fits your needs (like this? i don't really know any, but it exists).

If the library doesn't fit your needs, then you're up for some fun! But there are enough resources and algorithms to implement flocking behaviors yourself. Example 1 Example 2

If you choose to implement yourself, know there are some nice optimization to be done, as the scope of your agent is reduced for example by its location in the flock. It should anyway be included in some of the algorithms.

Well that's the best of my knowledge, I'm not sure anyway

# Answer
> 1 votes
If the enemy paths are not very dynamic (Dynamic would be every couple agents are attacking different targets and paths to those targets have to be updated every couple frames)

Then I would do a combination of flowfields and steering behaviours if performance is your main concern. There are some more complicated subjects involved like space partitioning your agents so finding neighbors is easier but it's your best bet for performance. (removing your A\* search and using flowfields to direct your agents)

Those two algorithms combined are generally considered the most optimized solution for agent dense scenes with not much dynamic pathing.

I'd avoid physics no matter your final option as it can get heavy.

Collision between agents can almost entirely be handled by steering behaviours and flowfields reduces the weight of 50 agents calculating paths. Keep in mind however that flowfields get more and more expensive the larger your map size, and smaller your grid size, and more dynamic your target selection has to be.

---
Tags: path-finding, steering-behaviors, collision-avoidance
---


# Question
Title: Random movement of game Object staying in a circle
I want to write a script which makes several objects move in a random direction but within a range around another game object. If the parent object moves then that range should also be changed accordingly.

How can I achieve such behavior?

Here is a video which demonstrates the behavior I am looking for.

It looks approximately like this:

---

```
   void Update ()
   {
        time += Time.deltaTime;

        if (time > 1.0f)
        {
            CalculateRandomRotation ();
            time = 0f;
        }

        FindSpiritsBound ();

    }

    void CalculateRandomRotation()
    {
        x       = Random.Range(-velocityMax, velocityMax);
        z       = Random.Range(-velocityMax, velocityMax);
        angulo  = Mathf.Atan2(x, z) * (180 / 3.141592f);
        time    = 0.0f;
        transform.localRotation = Quaternion.Euler(0, angulo, 0);
    }

    void FindSpiritsBound()
    {
        if (Vector3.Distance (parentObj.transform.position, gameObject.transform.position) < 3f)
        {
            gameObject.transform.localPosition += gameObject.transform.forward * 4f * Time.deltaTime;
        }
       else
        {
         transform.position = Vector3.MoveTowards(transform.position, parentObj.transform.position, 2.0f);
        }
    }

```

Here is my script which doesn't seem to work properly as on moving the main character, spirits are going wayward.

# Answer
In the script of the random movement of the sprites check the distance by using the command `Vector3.Distance(object a, object b)`. If the sprite is not in range than move/change direction of the movement.
> 1 votes

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


# Question
Title: How can I add a transparent overlay to a UI in libGDX?
I am attempting to use the following code

```
        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
        shapeRenderer.setColor(3,3,3,.3f);
        shapeRenderer.rect(0,0,gameWidth,gameHeight);
        shapeRenderer.end();

```

So that when the menu is accessed, a transparent background appears. The problem I am facing is that when I try to do this the objects rendered by the SpriteBatch seem to misbehave. Upon further research i found that attempting to nest that code within SpriteBatch.begin() and SpriteBatch.end() is the cause of that. However, If I try to place the code after the SpriteBatch.end(), because the SpriteBatch has ended the objects rendered by it do not appear behind the transparent rectangle. (I tried assigning SpriteBatch and Shaperender a different camera, however, that didn't fix the problem.) How can I fix this or find another way to implement the transparent background for the menu.

# Answer
> 3 votes
As mentioned above, you can start and stop a SpriteBatch in the same draw-method, also for transparency you need to enable BLEND. Here's what I did with one of my UIs.

```
    batchstuff...
    spriteBatch.end();

    Gdx.graphics.getGL20().glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

    shapeRenderer.setColor(new Color(1, 1, 1, 0.1f));
    shapeRenderer.rect(screenMargin + innerScreenMargin, screenMargin+innerScreenMargin + 5*(cellItemHeight+cellMargin+innerCellBorder)-innerCellBorder-cellMargin + innerScreenMargin, (innerCellBorder + innerCellWidth+cellMargin) * 10 - innerCellBorder-cellMargin, 380);

    shapeRenderer.end();
    Gdx.gl.glDisable(GL20.GL_BLEND);

    spriteBatch.begin();
    ... more batchstuff

```

---
Tags: java, libgdx, spritebatch
---


# Question
Title: Triangle data structure not working for LoD algorithm
I would like to implement a LoD algorithm to my 3D game in order to simplify meshes at certain distances from the player. My meshes are created / loaded using a VBO, so the vertex data is stored in a very large float array as

```
float[] vertices = {x1, y1, z1, x2, y2, z2, x3, y3, z3 ... xn, yn, zn};

```

How would I use this data in something like `edge colapse`? Would I need to convert this data into a more usable data structure such as a list of faces, or would it be possible to use this directly?

I feel like it would be very difficult to use the vertex array directly, so I have a simple class to represent a triangle using a `Vector3f` for each vertex, and an `Edge` class for each edge. The data structure for these are pretty simple, I dont feel that I need to show the whole code, so just a simple overview:

The `Triangle` class stores

* 3 `Vector3f`s to represent each vertex
* 3 `Edge`s to represent each edge
* an equals and hashcode implementation to be able to compare

And the `Edge` class stores

* 2 `Vector3f`s to represent each vertex
* a float representing the length of the edge: `abs(magnitude(subtract(v1, v2)))`
* an equals and hashCode implementation to be comparable

I have a method to convert the vertex array into a list of triangles, but it isn't working properly.

```
public static List<Triangle> vertexArrayToTriangles(float[] vertices, int[] indices)
{
    List<Triangle> result = new ArrayList();
    Vector3f[] vertexList = new Vector3f[vertices.length / 3];

    for (int i = 0; i < vertices.length / 3; i++)
    {
        vertexList[indices[i]] = new Vector3f(vertices[i], vertices[i + 1], vertices[i + 2]);
    }

    int i = 0;

    while (i < vertexList.length / 3)
    {
        result.add(new Triangle(vertexList[indices[++i]], vertexList[indices[++i]], vertexList[indices[++i]], new Vector3f(0, 1, 0)));
    }

    return result;
}

```

This just makes a spiky jumbled mess of triangles that is extremely laggy to render. Also, during rendering, the triangles are converted back into a float array of vertices.

How would I convert the vertex array into a `List<Triangle>` and keep the indices in order?

# Answer
```
for (int i = 0; i < vertices.length / 3; i++)
{
    vertexList[indices[i]] = new Vector3f(vertices[i], vertices[i + 1], vertices[i + 2]);
}

```

In your first run, you're taking `vertices[0]`, `vertices[1]` and `vertices[2]`, in your second run you're taking `vertices[1]`, `vertices[2]` and `vertices[3]`, see where the problem is?

And i don't get why you're using `vertexList[indices[i]]`, this makes no sense.

```
for (int i = 0; i < vertices.length; i+=3)
{
    vertexList[i/3] = new Vector3f(vertices[i], vertices[i + 1], vertices[i + 2]);
}

```

---

```
int i = 0;

while (i < vertexList.length / 3)
{
    result.add(new Triangle(vertexList[indices[++i]], vertexList[indices[++i]], vertexList[indices[++i]], new Vector3f(0, 1, 0)));
}

```

Here you're iterating from 0 to vertexList.length, but you can have more indicies than vertices.

```
for(int i = 0; i < indices; i+=3)
{
    result.add(new Triangle(vertexList[indices[i]], vertexList[indices[i+1]], vertexList[indices[i+2]], new Vector3f(0, 1, 0)));
}

```

If the indices start counting from 1, like the `wavefront .obj`-format does it, you have to subtract 1 from every index.

---

If this still doesn't work, try passing `{ 1, 2, 3, 4}` as vertices and `{0, 1, 2, 0, 2, 3}` as indices and step through it with the debugger.
> 1 votes

---
Tags: java, lwjgl, data-structure, vbo, level-of-detail
---


title: Shooting at mouse in unity

text:
# Question
Title: Shooting at mouse in unity
I'm using unity and trying to get my bullet to shoot at a target. I am clicking the mouse and I'm wanting to fire my bullet in that direction.

I have gotten the coordinates of the mouse click and tried to compute the vector. Then I've tried instantiate the bullet prefab (which has rigidbody component and is in front of the scene) at my position and then fire it in the direction of the mouse.

I can see that my objects being instantiated in my Hierarchy Pane but can't see anything on the screen!

Not sure if I'm doing the vector thing right (newb here), but if I click on Yoshi's head, I'm getting `(-2.0, -0.4)`. Does this sound right?

Code:

```
void fireBullet(float mousePositionX, float mousePositionY)
    {

        Vector2 position = new Vector2(mousePositionX, mousePositionY);
        position = Camera.main.ScreenToWorldPoint(position);
        GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject;
        bullet.transform.LookAt(position);
        Debug.Log(position);
        bullet.rigidbody2D.AddForce(bullet.transform.forward * 1000);
    }

```

# Answer
Try using raycast, from the point of your mouse.

By creating a variable of type hit and it should be equal to

```
Physics2D.Raycast(Camera.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

```

And then check if the variable is **not** equal to null, which means you hit something and then you can check the tag of the object and do what ever you want with it.
> 1 votes

# Answer
I'm on mobile, so excuse me if I miss some syntax, but:

```
float speed = 1000;
Vector2D mousePosition = GetMousePosition();
Vector2D bulletPosition = GetBulletPosition();
Vector2D direction = (mousePosition - bulletPosition).normalized;
bullet.rigidbody2D.AddForce(direction * speed);

```

Where `GetMousePosition()` and `GetBulletPosition()` retrieve their respective positions.
> 0 votes

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


# Question
Title: how to accurately select a sprite on a scene with a click?
I have a scene with some sprite on it (added), the gamer has to select one of them and take the next action.

# What is the simplest way to select one of the sprites accurately?

I am looking for a method that recieves a click coordinate and returns one of the sprites on the scene.

Since the sprites cant be well fitted in a bounding box I dont like to use a minimum bounding box approximation.

I was thinking of loading the sprites into a matrix and creating a scene matrix that each member belongs to a specified sprite, but it costs a lot( each pixel must be transformed using an affine transformation and it must be recalculated each time one of the sprites move)

Can someone show me a better way with a lower cost?

P.S I am using Swift and Apple's SpriteKit There is a code for minimum bounding box but I am looking for an accurate method.

Inaccurate method if some interested is something like this :

```
     for touch in touches
     {
            var location : CGPoint = (touch as! UITouch).locationInNode(self)
            for asprite in self.viewIso.children
            {
                if (asprite.containsPoint(location))
                {
                    println("Selected : \(asprite.name as String)")
                    return
                }
            }
     }

```

Thanks Iman

# Answer
If I remember correctly, I iterate through all sprites and use their inverse affine matrix to convert the click coordinate into local space for the sprite. I then use a trivial bounding box check to determine if the local coord can be ruled out quickly as a hit for that sprite.

If the bounding box check passes, I then perform an alpha test on the pixel of the sprite's texture. If it passes the required threshold, it is classed as a hit.
> 1 votes

---
Tags: sprites, selection
---