# Question
Title: XNA/Monogame Change SpriteBatch Blendstate in between calls
I'm working on polishing up the particle system in the project I'm working on in Monogame.

Currently particles and objects are all drawn within the same Begin/End block to allow for FrontToBack depth sorting, however my particles use the Additive BlendState, while my actual objects use AlphaBlend.

How would one go about changing the BlendState mid block while still being able to preserve depth?

This is part of a much larger system that I've been working on over the course of a few months, so everything in my library code is pretty well ingrained within everything else, so I can't really post all of it. If there are any questions on something I can answer.

Particle:

```
using GurmLib.Framework.Graphics;
using GurmLib.Framework.Tools.Trig;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GurmLib.Framework.Particles
{
    public class Particle
    {
        #region Variables

        public float
            StartAge,
            EndAge;

        public Sprite SpriteIndex;

        public Vector2
            Pos,
            Vel,
            Gravity;

        public Vector2 MaxBounds;

        public Color
            Blend,
            StartBlend,
            EndBlend;

        public float
            Scale,
            ScaleVel,
            ScaleAcc,
            ScaleMax,
            Rot,
            RotVel,
            RotDamp,
            Depth,
            Friction,
            Speed;

        #endregion

        #region Properties

        public bool Dead
        {
            get
            {
                bool outside =
                    Pos.X < Width ||
                    Pos.X >= Window.Width + Width ||
                    Pos.Y < Height ||
                    Pos.Y >= Window.Height + Height;

                return (StartAge <= 0) || outside;
            }
        }

        public int Width
        {
            get { return SpriteIndex.Width; }
        }

        public int Height
        {
            get { return SpriteIndex.Height; }
        }

        #endregion

        #region Constructor

        public Particle(Sprite sprite)
        {
            StartAge = -1;

            Pos = Vector2.Zero;
            SpriteIndex = sprite;
        }

        #endregion

        #region Core

        public void Update(GameTime gameTime)
        {
            if (Dead)
                return;

            StartAge -= gameTime.ElapsedGameTime.Milliseconds;

            float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

            SpriteIndex.Update(gameTime);

            UpdatePos(deltaTime);
            UpdateRot(deltaTime);
            UpdateScale(deltaTime);
            UpdateColor(deltaTime);
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            if (Dead)
                return;

            SpriteIndex.Draw(
                spriteBatch,
                Pos,
                Blend,
                new Vector2(Scale),
                SpriteIndex.Origin,
                MathHelper.ToRadians(Rot),
                Depth,
                SpriteEffects.None);
        }

        #endregion

        #region Functions

        public void Create(Vector2 startPos, float age, Vector2 dir, Vector2 gravity, float friction, float speed)
        {
            StartAge = age;

            Pos = startPos;
            Vel = dir;
            Gravity = gravity;

            Friction = friction;
            Rot = Trig.PointDirection(Pos, Pos + Vel);
            Speed = speed;
        }

        public void Create(
            float age,
            float fade,
            Vector2 startPos,
            Vector2 dir,
            Vector2 gravity,
            float friction,
            float speed,
            float rotation,
            float rotVel,
            float rotDamp,
            float scale,
            float scaleVel,
            float scaleAcc,
            float scaleMax,
            Color colorStart,
            Color colorEnd)
        {
            StartAge = age;
            EndAge = fade;

            Pos = startPos;
            Vel = dir;
            Gravity = gravity;

            Friction = friction;
            Speed = speed;

            Rot = rotation;
            RotVel = rotVel;
            RotDamp = rotDamp;

            Scale = scale;
            ScaleVel = scaleVel;
            ScaleAcc = scaleAcc;
            ScaleMax = scaleMax;

            StartBlend = colorStart;
            EndBlend = colorEnd;
            Blend = StartBlend;
        }

        public void UpdatePos(float deltaTime)
        {
            Vel *= Friction;
            Vel += (Gravity * deltaTime);
            Pos += (Vel * deltaTime * Speed);
        }

        public void UpdateRot(float deltaTime)
        {
            Rot *= RotDamp;

            RotDamp += (RotVel * deltaTime);
        }

        public void UpdateScale(float deltaTime)
        {
            ScaleVel += (ScaleAcc * deltaTime);
            ScaleAcc += (ScaleVel * deltaTime);
            ScaleVel = MathHelper.Clamp(Scale, 0.0f, ScaleMax);
        }

        public void UpdateColor(float deltaTime)
        {
            if ((StartAge > EndAge) && (EndAge != 0))
            {
                Blend = StartBlend;
            }
            else
            {
                float amtInit = StartAge / EndAge;
                float amtFinal = 1.0f - amtInit;

                Blend.R = (byte)((amtInit * StartBlend.R) + (amtFinal * EndBlend.R));
                Blend.G = (byte)((amtInit * StartBlend.G) + (amtFinal * EndBlend.G));
                Blend.B = (byte)((amtInit * StartBlend.B) + (amtFinal * EndBlend.B));
                Blend.A = (byte)((amtInit * StartBlend.A) + (amtFinal * EndBlend.A));
            }

        }

        #endregion
    }
}

```

One of my spawner functions:

```
public static Particle Fire(Vector2 startPos, float fxScale = 1.0f)
{
    float age = 500 + _rand.Next(500);
    float fade = age + _rand.Next(100);
    float speed = 1;

    Vector2 origin = startPos;

    float radius = 50 * fxScale;
    Vector2 offset = Trig.LengthDir(_rand.Next((int)-radius, (int)radius), _rand.Next(360));
    origin += offset;

    Vector2 direction = Vector2.Zero;
    //direction.X = -(offset.X);
    direction.Y = (-500f) * fxScale;

    Vector2 gravity = new Vector2(0, - _rand.Next(300));

    float friction = 0.5f;

    float rotation = 0.0f;
    float rotVel = 2.0f;
    float rotDamp = 0.99f;

    float scale = 0.5f * fxScale;
    float scaleVel = -0.1f;
    float scaleAcc = 0.0f;
    float scaleMax = 1.0f;

    Color colorStart = Color.Blue;
    Color colorEnd = Color.Orange;
    colorStart.A = 1;
    colorEnd.A = 0;

    Particle part = new Particle(_Sprites.spr_part_circle);

    part.Create(
        age,
        fade,
        origin,
        direction,
        gravity,
        friction,
        speed,
        rotation,
        rotVel,
        rotDamp,
        scale,
        scaleVel,
        scaleAcc,
        scaleMax,
        colorStart,
        colorEnd);

    return part;
}

```

My Particle Manager:

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

namespace GurmLib.Framework.Particles
{
    public static class FxManager
    {
        #region Variables

        private static int
            _deltaTime = 0,
            _timer = 0;

        private static List<Particle> _particles = new List<Particle>();

        #endregion

        #region Properties

        public static int Count
        {
            get { return _particles.Count; }
        }

        #endregion

        #region Core

        public static void Update(GameTime gameTime)
        {
            _deltaTime = gameTime.ElapsedGameTime.Milliseconds;

            for (int i = 0; i < Count; i++)
            {
                _particles[i].Update(gameTime);

                if (_particles[i].Dead)
                {
                    _particles.RemoveAt(i);
                }
            }
        }

        public static void Draw(SpriteBatch spriteBatch)
        {
            foreach (Particle p in _particles)
            {
                if (p != null)
                    p.Draw(spriteBatch);
            }
        }

        #endregion

        #region Functions

        public static void Create(
            SpriteBatch spriteBatch,
            Func<Vector2, float, Particle> srcFunc,
            Vector2 startPos,
            float fxScale = 1,
            int amount = 15,
            int frequency = 16,
            float depth = 1)
        {
            Create(srcFunc, startPos, fxScale, amount, frequency, depth);
            Draw(spriteBatch);
        }

        public static void Create(
            Func<Vector2, float, Particle> srcFunc,
            Vector2 startPos,
            float fxScale,
            int amount,
            int frequency,
            float depth)
        {
            _timer -= _deltaTime;

            if (_timer <= 0)
            {
                for (int i = 0; i < amount; i++)
                {
                    Particle part = srcFunc(startPos, fxScale);

                    part.Depth = depth;

                    Create(part);
                }

                _timer = frequency;
            }
        }

        public static void Create(Particle part)
        {
            _particles.Add(part);
        }

        public static void Clear()
        {
            _particles.Clear();
        }

        #endregion
    }
}

```

FxManager.Create is called like...

```
public void Draw(SpriteBatch spriteBatch)
{
    Vector2 pos = new Vector2(100, 100);
    float depth = /* Some function to calc depth */

    FxManager.Create(
        spriteBatch, _Particles.Fire, pos, 0.08f, 5, 16, depth);
}

```

GameState.Draw:

```
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    Graphics2D.Clear(Color.Black);

    spriteBatch.Begin(
        SpriteSortMode.FrontToBack,
        BlendState.AlphaBlend,
        SamplerState.PointClamp,
        null, null, null,
        View.TransMatrix);
    {
        View.TileMaps[0].Draw(spriteBatch);

        DrawGameObjects(spriteBatch);
    }
    spriteBatch.End();
}

```

↑ And this is (basically) called by the main draw loop (there's a few more hoops to jump through to get to Game1, but I'd end up posting all my source). I only have one SpriteBatch throughout the entire program.

DrawGameObjects calls the draw event for every GameObject, passing the spriteBatch along as it goes. It's in here that I want to be able to change the BlendState while still using the same depth calculations as the GameObjects. Like if a GameObject called FxManager.Create in it's own draw event.

Minus a few asset references this is pretty much the entirety of my Particle system. Idk if it'll help formulate a solution, but it's here anyways. Everything should work as is, minus my assets, so feel free to copy pasta and use it on whatever.

# Answer
> 2 votes
You can't. `FrontToBack` means that it's going to sort it and do one draw call with the current sprite batch settings.

You are most likely going to have to split it into multiple sprite batches. You'll need to begin and end a sprite batch for each unique setting combination you have.

For example if you have these 5 unsorted objects:

1. Particle (Additive), Depth: 0.1
2. Particle (Additive), Depth: 0.2
3. Object (AlphaBlend), Depth: 0.15
4. Particle (Additive), Depth: 0.23
5. Object (AlphaBlend), Depth: 0.4

Then you'll need 4 logical sprite batch groupings:

1. Draw #1
2. Draw #3
3. Draw #2, #4
4. Draw #5

---
Tags: xna, monogame
---


# Question
Title: Two 2D objects in Unity aren't colliding together
In Unity 5, I have a player shooting a projectile in aim to hit a boss, and inflict damage upon contact with the projectile. Though for some reason, the projectile and boss aren't colliding with each other.

I've done the following;

* Made sure that both the projectile and boss have a BoxCollider 2D and Rigidbody 2D
* Made sure that they're on the same Z-Index and on the same layer
* Tried to Debug.Log() if there's any collision (there isn't)
* Made sure I'm using OnCollisionEnter2D on the boss' health script
* Compared the syntax I use with another collision (where the player collides with an object and dies - this works perfectly fine).

However, none of these seem to be working.
This is the boss' health script:

```
void OnCollisionEnter2D (Collision2D coll)
{
    Debug.Log("COLLIDED");
    bosshealth -= 1;
}

```

Here is the projectile prefab:
And the boss prefab:

Does anyone have a clue as to why they're not colliding? the projectile just glides over the boss

**EDIT:** I found a temporary fix! Disabling the Kinematics of the boss allows for both objects to collide, and successfully display a debug message! Just a problem though; I don't want the boss to freely float around in space. I use the kinematic to ensure it stays put at all times until told to by scripts.

Is there a way to get around not having to disable the kinematics?

EDIT 2: Then again, I am removing the projectiles on impact anyway, so the actual boss doesn't move, but that seems dirty :/

# Answer
> 1 votes
Thanks to @DMGregory for enlightening me on this.

It turns out that you can't collide objects that both have "Is Kinematic" enabled. To get around this personally, I just unchecked "Is Kinematic" from the projectile and set it's gravity to 0, so it doesn't fly down.

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


# Question
Title: Character on Character fighting animations
sorry about the vague title, but these couple of videos/images might explain my situation a bit better:

https://www.youtube.com/watch?v=MG1mNyjNuXk (Wolfenstein the Old Blood) https://www.youtube.com/watch?v=NVmsucYKlvo (Mad Max the Game) https://www.youtube.com/watch?v=XYWQ-UzTpZ8 (at 0:49 seconds, Credits go to: Ranon Sarono AKA Hyper)

I am basically wondering how you would animate the 2 characters if 1 of them knifed the other one, do they both have their separate animations? or do they just take the animation file?

# Answer
> 1 votes
The simplest way to do it is to synchronize animations between the two characters. Art-wise, you can edit them at the same time and export both when you're done. For programming, you can take some time to slide both characters towards their starting positions, then play the matching animations for both at the same time.

---

As for the other option, it's just generally harder to do - if you wanted to animate 2 characters with the same animation, you'd have to assign different bones to each of the 2 characters. There are some options to go about it, but none are easy and all of them build on parts of the previously mentioned method:

1. Use same animation for both characters programmatically - one of the characters will need dynamic bone remapping to get properly animated - it's doable but might be technically confusing;
2. Combine characters into one mesh - all combinations will have to be exported separately, lots of storage space waste;
3. Use same animation for both characters with static bone renaming, basically a mix of previous two techniques, probably most complicated.

---
Tags: animation, multiplayer, skeletal-animation, character
---


title: Gradual rotation of an object in Java

text:
# Question
Title: Gradual rotation of an object in Java
I'm using Java to learn some movement algorithm. I would like to implement the "wandering" algorithm, but in order to do it, i should understand how to rotate an Object gradually.

Actually, my Player changes its orientation instantly (and too many times!) and it is not so good.

This is my code:

**logic update**

```
public void update(float delta) {
    // WANDERING

    // orientation as a vector
    float orientation_x = (float)Math.sin(orientation);
    float orientation_y = (float)Math.cos(orientation);

    // update velocity
    velocity_x = maxSpeed * orientation_x;
    velocity_y = maxSpeed * orientation_y;

    int max = 1;
    int min = 0;
    int random1 = (rand.nextInt((max - min) + 1) + min);
    int random2 = (rand.nextInt((max - min) + 1) + min);
    orientation = (random1 - random2) * maxRotation; // random binomial (i don't know which value i have to assign to maxRotation
    System.out.println(orientation);

    x += (velocity_x * delta);
    if(x >= GamePanel.PWIDTH) {
        x = 0.0f;
    }
    y += (velocity_y * delta);
    if(y >= GamePanel.PHEIGHT) {
        y = 0.0f;
    }
}

```

**draw**

```
public void draw(Graphics dbg) {
    // draws the player
    Graphics2D g2d = (Graphics2D)dbg;
    g2d.setColor(Color.RED);
    AffineTransform old = g2d.getTransform();
    g2d.rotate(orientation, x + SIZE/2, y + SIZE/2);
    g2d.fillRect((int)x, (int)y, SIZE, SIZE);
    g2d.setTransform(old);
}

```

With this code, the behavior that i get is horrible. The Player changes his direction too many times and instantly.

This is the pseudocode of the algorithm:

```
# Holds the static data for the character
character

# Holds the maximum speed the character can travel
maxSpeed

# Holds the maximum rotation speed we’d like, probably
# should be smaller than the maximum possible, to allow
# a leisurely change in direction
maxRotation

def getSteering():

# Create the structure for output
steering = new KinematicSteeringOutput()

# Get velocity from the vector form of the orientation
steering.velocity = maxSpeed *
character.orientation.asVector()

# Change our orientation randomly
steering.rotation = randomBinomial() * maxRotation

# Output the steering
return steering

```

# Answer
*Orientation is a vector, so to rotate it all you have to do is apply basic vector math.*

First of all, your vector's components are swapped. Sin is for Y component and cos for X component. So your code ends up as:

```
 float orientation_x = (float) Math.cos(orientation);
 float orientation_y = (float) Math.sin(orientation);

```

Your object changes direction instantly because each update tick you are choosing a random variable between a range as the direction instead of allowing a smooth transition of the orientation angle.

A simple solution to your problem could be adding a small angle each tick (either positive or negative with respect to your orientation angle). This angle "differential" depends on where your object is trying to steer.. You could even add a steering acceleration to provide an even smoother rotation.
> 1 votes

# Answer
It seems to me like what you want is a slerp function, see: http://en.wikipedia.org/wiki/Slerp
> 0 votes

# Answer
One method you could use is instead of assigning a random rotation to `orientantion`, you should increment or decrement `orientation` by a small random amount. Pseudocode:

```
orientation += (randomFloat() - 0.5) * VARIANCE

```
> 0 votes

---
Tags: java, rotation
---


title: Laggy empty project at 60FPS

text:
# Question
Title: Laggy empty project at 60FPS
```
@Override
public void create() {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    if (x < 0 || x > 400) {
        speed = -speed;
    }
    x += speed * Gdx.graphics.getDeltaTime() * 60;
    Gdx.app.log("delta",Gdx.graphics.getDeltaTime()+"");

    batch.begin();
    batch.draw(img, x, 0);
    batch.end();

}

```

I had a problem and i created a new project. The problem libgdx tries to keep 60FPS and avarage deltatime is ~16ms.Some renders take +20ms then next render takes 12ms(render1 + render2 = 32ms) to achieves 60FPS. That makes game laggy. As you can see i don't have anything in the project and it is the same in desktoplaunch. How did you solve this ?

Note: I also tried reqeustRendering. But it is the same thing if the render takes more time than the avarage. I also tried to wait some times for the render if that is smaller than 16ms. It didn't help either. It doesn't have any GC problem. I use Libgdx 1.6.4.

# Answer
A guess here, but logging on the same thread as your rendering work, before you send gpu instructions, can add synchronous disk latency? Possibly in a sporadic fashion if it's buffered and dumping.

```
@Override
public void create() {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    if (x < 0 || x > 400) {
        speed = -speed;
    }
    x += speed * Gdx.graphics.getDeltaTime() * 60;

    float delta = Gdx.graphics.getDeltaTime ();

    batch.begin();
    batch.draw(img, x, 0);
    batch.end();

    Gdx.app.log("delta", delta+'"');
}

```
> 1 votes

# Answer
Editing, as i re-read the question again...

Try limiting the delta to 1/60, like:

```
float yourDelta = Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f);

```

Then do:

```
x += speed * yourDelta * speedMutator;

```

Does that improve the smoothness?
> 0 votes

---
Tags: java, libgdx, game-loop
---


# Question
Title: Should I tell the player they have no chance of completing the level?
Suppose a player has reached a point where they have absolutely no chance of completing the current level, and must restart it and try again.

Should I notify them that they will gain nothing by continuing the level and needs to restart? If so, how should I tell them that? Would a message box of some sort saying something like "No chance, start again" be good? Or should I let them continue to play and find out themselves?

Note that the levels are not huge, and mostly take about a minute each to complete. So for example, if the user missed the opportunity to level up after 30 seconds or so, should I stop the game and make them restart?

# Answer
Depends on the game.

In a obstacle course/parkour type game against a time limit it's common to add checkpoints that add to a time limit which is tight enough to that a big mistake will cause failure.

In a puzzle game however like your example then just letting the time run out is a better idea. It's probably also a good idea to let them undo actions that were wrong and let the player find out that they were wrong for themselves. If there is only 1 solution and you warn the player as soon as he makes a mistake then it becomes a not-fun game of trial and error. Rather than the mental challenge you are going for.
> 42 votes

# Answer
## Kill the player

Death is an easy way to tell the player they have made a big mistake. And you save them the trouble of restarting by restarting **for** them.

An easy way to retro-fit death into a scenario is to introduce a deadly time-constraint, like water flooding, or walls closing-in. Your imagination is the limit!
> 21 votes

# Answer
A "you have no chance" message can be a pretty jarring break of immersion. If the user is really trying to figure out how to beat the level, his/her mind is deep in their mental model of what is going on. Such a message would be interrupting.

If you do want to do this my advice would be one of:

* Bring the message up slowly, perhaps as just a warning blip at first, giving them time to choose to pay attention to the message
* Change the environment in a way which encourages the player to realize they've messed up on their own terms.
> 12 votes

# Answer
Tell the player, then save them.

A good example how to do this well is the Portal series. Despite the very well thought out puzzle designs where most mistakes can either be fixed or results in immediate death, there are a few situations in the game where the players can trap themselves or screw up the puzzle in a way that it can not be solved.

The developers have anticipated these situations. When they occur, the NPC which supervises the player reprimands them for being careless and then intervenes to remedy the situation (opens a hidden door, respawns a critical piece of equipment, etc). This happens completely in-character, so it is not immersion breaking at all.
> 11 votes

# Answer
The way the game Osmos solves this, when you've got to the point where the game is unwinnable, is to have a "Doesn't look good..." message appear unintrusively on the screen.

As a player, this is really helpful, as it is entirely possible for the game to look vaguely winnable when on the edge; also it allows the user to choose whether to restart or to continue playing, but clearly suggests that it's time to restart.

The key is that the option to restart should be made "more accessible", but still left up to the player, who may want to test your system's ability to calculate it, Kobyashi-Maru style.

Also, time matters. Osmos is a *slow* game, and getting to the point where you realise you can't win could be upwards of 5-10 minutes. This pushes the "Can't win" notification from "nice" to "critical".
> 5 votes

# Answer
Sounds like you have discovered a game- or level- design issue which you might want to address in other ways, such as reconsidering how the game rewards success, or shifting to an alternate game mode where there is a secondary goal when the main goal will no longer be possible. The details depend on the game, of course, the expected players' interests, and what you want to accomplish. But having some early mistake mean there's no point in continuing can be an annoyance for some players, depending on their expectations and how it's presented.

It doesn't have to be a bad thing. For example, if your players are perfectionists and want to practice something over and over till they get it right. Perhaps in many Olympic sports, the point is to have the best performance among experts, so if you stumble at some point, you might as well stop trying for that round, and that's expected. In that case, it may make sense to indicate when winning or proceeding becomes impossible.

Or, if it's a puzzle genre where again the expectation is you'll probably make mistakes as part of learning and need to start over, but part of the game is figuring out what to learn from mistakes, then you may not want to let them know, so they can figure it out. Or you might want to let them know, but in a relevant and interesting way that provides a clue to the mystery they are supposed to figure out.

In games where there is rich gameplay aside from the main goal, you may not want to announce a hopeless condition, because trying to continue play can be interesting in other ways.

In games with more going on outside the current mission context, or where you want to have it be fun even when things go wrong, you might want to detect failure states but instead of announcing it like a failure and suggesting trying over, you could have the gameplay respond or give clues that the player should now be focusing on some secondary or alternative goal. For example, if the main mission were to accomplish something without something happen, and that main goal becomes impossible or failed, you could let them know that (or not) but have the situation change or a new goal become apparent. For example, if you were trying to rescue someone from someplace but that becomes impossible, your next goal might be to not get caught yourself, and might be signaled by a companion or observer character pointing out the situation, or an alarm going off, or several guards showing up.

The above can even apply to a game with one-minute levels, and is a design decision. If you just have them stop and try over, that will have a certain flavor. If you have there be a secondary play mode, that could have another flavor. For example, if you can't win the current level, you might still be able to escape with your life, and/or gain some secondary points or power ups or cause some effects that would carry over to the next try.
> 4 votes

# Answer
It depends a great deal on what kind of game you're talking about.

If the game is a puzzle, and its rules permit reverting a move without any loss (beyond time), the player should generally expect to detect dead ends and recover from them on their own. Giving them notice that they've entered an unwinnable situation is probably unnecessary unless it's limited to detecting situations which are *immediately* unwinnable. Games of this type might include "pen and paper" puzzles such as crosswords, sudoku, or mazes, as well as certain other fully reversible puzzles such as Rubik's Cube or sliding-block puzzles.

On the other hand, if moves in a puzzle are not revertible, notifying players that they have entered an unwinnable situation may be appropriate. This is particularly important if the unrecoverability of the situation would not become apparent until much later. Games of that type might include block-pushing puzzles such as Sokoban, as well as many text-based adventure games. (Older text-based adventures often failed to follow this rule; this was a major factor in why they were considered so frustrating!)

Finally, if the game is not intended as a puzzle at all — for instance, if it is actually a first-person shooter — the situation changes entirely. Games of this type will usually end immediately if the player has entered a completely unwinnable situation. For instance, in sections of Half-Life 2 which the player must use a vehicle to complete, the game ends immediately if the vehicle falls into an unrecoverable position. Another option is to automatically take action to restore the game to a winnable state. For instance, if a player has run out of a consumable item that is mandatory to proceed, the game could make more of that item available to the player.
> 2 votes

# Answer
Others have given good ideas how to add the possible warning button without braking immersion. I'd like to add warning against forcing the restart before some player known resource (turns/time...) is used up. Depending on the style of the puzzle, it is possible that even if player knows s/he can't pass the level, there is some action which they want to try before restarting. For example: if I have 2 moves left and at minimum I would need 5 moves to pass the level, I might realize the futility. However, I still would like to use my final moves to determine what some possible actions will do ("will this weapon break that stuff", "can I reach something"). And then use that knowledge on my later tries.
> 0 votes

# Answer
Many of the enemies in the Legend of Zelda require specific consumable items to defeat (for example arrows, bombs, or magic), and this goes for dungeon bosses as well. Usually, the player cannot leave a boss chamber until it is defeated. The 2D era games (NES/SNES/Gameboy) offered minimal refills, if any, inside the boss chamber - once you ran out you either needed to die or reset. Ocarina of Time on the N64 and the games that followed it started adding regenerating grass to many of the boss chambers that would contain items needed to defeat the boss.

Even in the same series it can go both ways, neither one was right or wrong.
> -1 votes

---
Tags: levels, user-experience
---


# Question
Title: How do I use openGL shader to reproduce this Photoshop implementation?
Here are my Photoshop actions:

**step1 - convert the current image into gray**

**step2 - use the default parameters, as showed in the screenshot**

**step3 - use the 『Hue/Saturation』 to convert the grey image**

**step4 - use the parameters to complete**

I did some search and find some code to make it available to convert to Grey as:

```
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;

void main()
{
    vec4 c = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);
    gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b);
    gl_FragColor.w = c.w;

}

```

I would like to know whether the code is correct according to the parameters in Step 2 and what can I do with openGL shader to achieve step 3 & step 4.

Thanks!

# Answer
Yes, step 1 and 2 are correct. Here's proof.

Step 3 and 4 can be done in a couple of ways. Following your steps to the letter, you can convert the RGB color to HSV, modify the values, and convert back to RGB. The first conversion is unnecessary though, since the image is grayscale, so we know the only thing that is affected is the "V" in HSV.

So you can use your image as V, and use those constant H and S values to get something similar to what you want. Subject to tweaking and experimentation of course.

Converting back and forth between RGB and HSV isn't the best idea for something like this though; perhaps in this case - if all you want is a slight blue/cyan tint - then you could instead just slightly tweak the blue and green channels and get the same result.
> 1 votes

---
Tags: opengl, shaders, graphics-programming
---


# Question
Title: How do I find the set of regions that are fully enclosed by a color?
How do I get all areas surrounded by a certain color in a multidimensional array?

For example, this map has three regions that are fully enclosed by *red* tiles. They are highlighted enclosed in pink.

I'd want the algorithm to return three regions, with the positions of the tiles inside them.

How can I do this?

# Answer
> 2 votes
I would use this algorithm (in pseudocode):

```
iterate your whole playing field to create a list of all non-red tiles called LIST
while LIST has entries
    flood-fill from the first entry of LIST
    remove the results of the flood-fill from LIST
    if no result of the flood-fill is at the edge of the map
        add floodfill result to surrounded areas

```

# Answer
> 0 votes
If I understood what you are asking, for every non-red, border tile, flood red. At last the non-red tiles are surrounded by red.

In the example starting from top-left corner going anti-clockwise...

---
Tags: javascript, algorithm, tiles
---


# Question
Title: In terms of Game Design, is the definition more of designing the ENTIRE game, or can it be limited to contributing to the artwork?
I am a person who desires a job in the artwork development of a video game, but the exact term for the general career often confuses me. What I want to do is Character Design, but what general career does it fall under in terms of video games? Is the overall concept Game Design, or is it just Illustration? I get confused that Game Design is just creating the ENTIRE game from the top of your head and not just a specific area of the development, like the art. Am I wrong? Does Game Design work for both the idea and the artwork, and can the term be separated between the two? A helpful answer would be much appreciated.

# Answer
> 2 votes
## What is a Game Designer?

*A game designer designs games*. More specifically, they design the rules of the game, and how the player interacts with the game. They design the way Mario's physics work, they design the rules of jumping on Goomba's heads, and they design the levels in such a way that the player is forced to learn about Goomba-head-jumping-physics.

To do any work for a game, it would be helpful to know a little about Game Design. A Character Designer would benefit from understanding how the atheistics of the games effect game-play. For example, you don't want the player to confuse Goombas for One-Ups.

# Answer
> 1 votes
When I hear *game designer*, I think of somebody who thinks up game mechanics, freedoms and constraints, level designs, balance etc. The may well have no part in actually programming the game. What you are is a *game artist*.

That doesn't mean that you can't have more than one role in creating a game, and at the same time each role influences every other role significantly. At any rate, you are a *game developer*, as are programmers, testers, sound engineers, etc.

# Answer
> 0 votes
## Game Designers

In developing a game, anyone who is part of implementing the game is to some degree a game designer:

A developer writing code for a random event for example. Original versions of Tetris had completely random choice in pieces (waiting forever for a long piece). While some newer versions use a grab bag approach. While it's still random, it means that for every X pieces (size of the bag) you'll get at least 2 long pieces. A simple example of how a programmer decides to implement random affecting the game design.

Artists (models, texture, lighting) all have an effect on how the game looks. If an item is hard to see among other elements or does it really stick out. That changes the feel of the game. Is it now a matter of intensely inspecting the world around you, or just quick scan, there's the next pick up.

So a Game Designer is the one responsible for the overall vision and interaction of all these small pieces. A game designer might make a statement, "we want the pieces to be random" vs. "we want the pieces to be random, but want to prevent an extreme wait for a long piece". Or "these types of pickups should be easy to identify, but these special collectibles should require careful inspection of the environment".

Game Designers are responsible for the entirety of the game. To make sure that those building the game know what the result should be. The more a particular job function is concerned with the implementation (what language, coding patterns, what colors, how to light things) the less they are a Game Designer, but the more they affect the actual game's final design.

## Character Design

Depending on the studio the specifics can vary. But modern character design ranges from character concepts to the implementation details, models, animations, voice, etc.

The importance of character design is how the character serves the game. In Team Fortress 2 for example, the character design is cartoonish, but the characters really sell the individual classes. Being responsible for explicitly deciding key details of the character is the role of a character designer.

The game designer may say, we want a female character that in the beginning of the game is scared, lost, and injured, but slowly gets more confident. Then you build Lara Croft from the latest Tomb Raider. The parts in between can be part of Character Design. If it's a large studio, they may have animators and models, other artists, and your job is to provide them concepts, sketches, and to work with them to build the final product.

# Answer
> 0 votes
When you're talking about a titled role, what you're talking about is the answer to this question: If I have a problem with/concern about X, who do I talk to in order to get it fixed?

If you have a problem with how a character looks or whether something is visible, you talk to an artist. The artist may in turn direct you to a programmer if it's a rendering issue, but your first stop is the artist.

If the game crashes, you go directly to the lead programmer (or more likely submit a bug report which goes to the lead programmer). The lead programmer will then figure out where that bug came from and forward it off to the appropriate programmer who can fix it.

If you have a problem with how the game feels in some way, your first stop is a game designer. That person can then assess the problem and perhaps direct you to the AI designer (who may direct you to the AI programmer) or wherever. It may even require an art fix/modification. But ultimately, it's a game designer problem and the game designer is the one who comes up with the solution.

Game designers need to consult with others in order to solve game design problems. They need to be able to work with programmers to make the AI do what they need. They need to be able to work with scripters who put which challenges in which locations. They need to be able to work with artists so that the graphics don't get in the way of the gameplay and fulfill the overall vision.

A game's designer has the ultimate responsibility for how the gameplay is designed and behaves. This can include elements of art, sound, programming, scripting, etc. But this does not mean that artists, sound people, programmers and scripters are game designers.

Just like the guy mixing concrete at a construction site is not an *architect.*

---
Tags: game-design, art, character
---


# Question
Title: How do I induce collision events in LibGDX 3D?
In the code below I've put an example of something I want to do. I have the camera and I want it to stop moving whenever it hits one of the boxes, how do I do this?

```
public class Main extends ApplicationAdapter {

    private final ModelBuilder builder = new ModelBuilder();
    private final Environment environment = new Environment();
    private ModelBatch modelBatch;
    private PerspectiveCamera camera;
    private Model model;
    private ArrayList<ModelInstance> instance = new ArrayList<ModelInstance>();
    private FirstPersonCameraController controller;
    private BoundingBox[] boxBounds = new BoundingBox[1000];
    private BoundingBox cameraBox = new BoundingBox();
    private Vector3 cameraSpeed = new Vector3();
    private Vector3 oldCameraPos = new Vector3();
    private Vector3 newCameraPos = new Vector3();

    @Override

    public void create() {
        modelBatch = new ModelBatch();

        //build the camera
        camera = new PerspectiveCamera(67, graphics.getWidth(), graphics.getHeight());
        camera.position.set(0f, 10f, 0f);
        camera.lookAt(0, 10, 0);
        camera.near = 1f;
        camera.far = 1000f;
        camera.update();

        //build all the boxes
        for (int i = 0; i < 1000; i++) {
            model = builder.createBox(
                    (float) Math.random() * 50,
                    (float) Math.random() * 50,
                    (float) Math.random() * 50,

                    new Material(ColorAttribute.createDiffuse(

                            (float) random(),
                            (float) random(),
                            (float) random(), 1)
                    ), Position | Normal);

            instance.add(new ModelInstance(model));
            instance.get(i).transform.setToTranslation(
                    (float) random() * 1000 - 500,
                    (float) random() * 1000,
                    (float) random() * 1000 - 500);

            boxBounds[i] = new BoundingBox();
            boxBounds[i] = model.calculateBoundingBox(boxBounds[i]);
        }

        //build the ground
        model = builder.createBox(700f, 1f, 700f, new Material(ColorAttribute.createDiffuse(Color.GREEN)), Position | Normal);
        ModelInstance ground = new ModelInstance(model);
        instance.add(ground);

        //build the center
        model = builder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.RED)), Position | Normal);
        ModelInstance center = new ModelInstance(model);
        instance.add(center);

        //code the lights here
        DirectionalLight light = new DirectionalLight().set(255, 255, 255,
                (float) random(),
                (float) random(),
                (float) random());

        //set up the enviroment
        environment.set(new ColorAttribute(AmbientLight, 255f, 255f, 255f, 1f));
        environment.add(light);

        //set up the camera controller
        controller = new FirstPersonCameraController(camera);
        controller.setDegreesPerPixel(0.25f);
        controller.setVelocity(20);
        input.setInputProcessor(controller);
    }

    @Override
    public void render() {
        //set up OpenGL
        gl.glViewport(0, 0, graphics.getWidth(), graphics.getHeight());
        gl.glEnable(GL_BLEND);
        gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        gl.glClearColor(0, 0, 0, 0);

        //render the modelInstances
        modelBatch.begin(camera);
        modelBatch.render(instance, environment);
        modelBatch.end();
        controller.update();

        if (input.isKeyPressed(Input.Keys.R)) {
            camera.lookAt(0, 0, 0);
        }

        cameraSpeed = newCameraPos.sub(oldCameraPos);

        cameraBox = new BoundingBox(new Vector3(camera.position.x,
                camera.position.y,
                camera.position.z),

                new Vector3(camera.position.x + 10,
                        camera.position.y + 10,
                        camera.position.z + 10));

        for (int i = 0; i < 1000; i++) {
            if (cameraBox.contains(boxBounds[i])) {
                camera.position.x = camera.position.x - cameraSpeed.x;
                camera.position.y = camera.position.y - cameraSpeed.y;
                camera.position.z = camera.position.z - cameraSpeed.z;
            }
        }

        System.out.println(cameraSpeed.x + " " + cameraSpeed.y + " " + cameraSpeed.z);
    }

    @Override
    public void dispose() {
        modelBatch.dispose();
        model.dispose();
    }
}

```

Result:

# Answer
The physics engines that I have written work in three steps

Each frame:

1. All physics objects calculate their own velocity vector
2. The physics engine loops through the objects and updates their new positions based on

position += velocity * deltaTime;
3. The physics engine resolves all collisions

First, I suggest that instead of letting your FirstPersonCameraController set the position of the camera, make the camera a physics object by having the FirstPersonCameraController control the camera's velocity, not position, and then letting the physics engine update the Camera's position.

Writing a physics engine may sounds scary, but it is really just a method which moves all the objects in a scene and then makes sure that solid objects aren't overlapping.

Lastly, depending on your needs, there are two approaches that I have used for resolving the collisions.

1. Basic Overlapping

After your physics engine has moved every object. Then loop through the objects to see which are overlapping. If any are overlapping then they have collided. You have to decide how this collision will be resolved, but usually this means that you move one or both objects backward until they are no longer overlapping.

The biggest drawback to this approach is called the bullet through paper problem. If your camera is moving fast enough that it goes through an entire cube in one frame, then when you check for collisions, you won't register that the two objects collided. There are ways to overcome this such as making sure that no object goes horribly fast and fixing your timestep

2. Swept collision detection

I have had varied success with this method. Basically the idea is that you can combine the movement and collision detection phase to determine that given two objects' velocity vectors, what time will they collide if they will collide at all. Going into depth on how to accomplish this is out of scope for this already long response, but here's a good article

This method solves the bullet through a paper problem, but it is harder to understand/implement as well as more computationally expensive.

There may be more methods out there which may benefit you by searching the internet for collision detection.
> 1 votes

---
Tags: java, collision-detection, 3d, libgdx
---


# Question
Title: Unity: Restrict movement inside a gameobject (2D)
I've been sort of trying my own thing but it's super buggy so I'd like to see what other people have done to create moveable spaces. In essence, I just want to restrict my character's movement to inside of a sprite. So one of my sprites is the character and another one of my sprites is a box -- I want to make it so my character can't leave the box. I've been modifying transform.position on mouse click in order to move my character, but now I'm not sure if this was the smartest idea.

# Answer
If you're moving the transform relative to the wrapping parent, you could always `Mathf.Clamp(high,low)` your coordinates.

If not a box, I think you need to defer movement to physics engine for desired functionality.
> 1 votes

# Answer
2 ideas came to my mind. Look at illustrations:

First option is obvious, add colliders to boundaries of your game area.

The second option is, to limit your characters movement inside boundaries within your script.

For example, if you have a code that controls the position of character, check if your values falls inside the boundaries of your game area, then clamp it to max and min values if it exceeds.

Thankfully, unity has this feature built-in in Mathf library with "Mathf.Clamp" function. So in this example you need to check like this:

```
var finalVertical = Mathf.Clamp (rawVertical, -c, +c);
var finalHorizontal = Mathf.Clamp (rawHorizontal, -a, +b);

```

For more information about clamp, check this out:

http://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
> 0 votes

---
Tags: unity
---


# Question
Title: How to draw the elements that are in a Texture2D list in XNA
I have a Texture2D list called blockTexture that has 2 elements in it.

I use the following line to draw the first element.

```
foreach (Vector2 blockPosition in blockPositions)
for (int i = 0; i < blockPositions.Count; i++)
{
 spriteBatch.Draw(blockTexture[i], blockPositions[i], Color.White);
}

```

This allows me to draw the elements in different positions. However, while I run it after like 3-4 seconds it gives OutOfRangeArgument error.

I was wondering what am I doing wrong or is there another way to do this. I'm really sorry if my question sounds stupid but I'm a total beginner.

*PS: this is a game where different type of objects fall from the top of the screen to the bottom, and the person at the bottom needs to avoid some of the objects and try to catch the others.*

```
List<Vector2> blockPositions = new List<Vector2>();
List<Texture2D> blockTexture = new List<Texture2D>();

```

These are in the load content

```
blockTexture.Add(Content.Load<Texture2D>("Block"));
blockTexture.Add(Content.Load<Texture2D>("right"));

```

These are in the update section

```
for (int i = 0; i < blockPositions.Count; i++)
 {
  // Animate this block falling
  blockPositions[i] =
  new Vector2(blockPositions[i].X, blockPositions[i].Y + BlockFallSpeed);

  // Get the bounding rectangle of this block
  Rectangle sprite =
  new Rectangle((int)blockPositions[i].X, (int)blockPositions[i].Y,
                    blockTexture[0].Width, blockTexture[0].Height);

  // check collision with person
  if (personRectangle.Intersects(sprite))
   personHit = true;

  // Remove this block if it have fallen off the screen
   if ((blockPositions[i].Y > Window.ClientBounds.Height))
   {
    blockPositions.RemoveAt(i);
   // When removing a block, the next block will have the same index
   // as the current block. Decrement i to prevent skipping a block.
    i--;
    }
  }

  base.Update(gameTime);

```

}

# Answer
> 1 votes
I would do it so, so it can be safer and maybe easier to use :
Just use a class to hold the information of position and texture.

```
class yourClass
{
    Texture2D texture;
    Vector2 position;

    public yourClass()
    {

    }

    //your functions
    //...
}

```

And then you can use a List of this class, like:

```
List<yourClass> list = new List<yourClass>();

yourClass a = new yourClass();
a.texture = Content.Load<Texture2D>("blabla");
a.position = new Vector2(0, 0, 800, 800);
list.Add(a);
//...

```

# Answer
> 0 votes
This is a bit of a shot in the dark, since I'm just guessing at your intentions here. But I think you would want to change your drawing code to the following:

```
foreach (Vector2 blockPosition in blockPositions)
{
     for (int i = 0; i < blockTexture.Count; i++)
     {
           spriteBatch.Draw(blockTexture[i], blockPosition, Color.White);
     }
}

```

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


# Question
Title: How do I correctly use singletons in C++ engine programming?
I know singletons are bad, my old game engine used a singleton 'Game' object that handles everything from holding all data to the actual game loop. Now I'm making a new one.

The problem is, to draw something in SFML you use `window.draw(sprite)` where window is an `sf::RenderWindow`. There are 2 options I see here:

1. Make a singleton Game object which every entity in the game retrieves (what I used before)
2. Make this the constructor for entities: `Entity(x, y, window, view, ...etc)` (this is just ridiculous and annoying)

What would be the proper way to do this while keeping an Entity's constructor to just x and y?

I could try and keep track of everything I make in the main game loop, and just manually draw their sprite in the game loop, but that too seems messy, and I also want absolute full control over an entire draw function for the entity.

# Answer
> 3 votes
Only store data needed to render the sprite inside each entity, then retrieve it from the entity and pass it to the window for rendering. No need to store any window or view data inside entities.

You could have a top-level *Game* or *Engine* class which holds a *Level* class (holds all the entities currently being used), and a *Renderer* class (contains the window, view and anything else for rendering).

So the game update loop in your top-level class could look like:

```
EntityList entities = mCurrentLevel.getEntities();
for(auto& i : entities){
  // Run game logic...
  i->update(...);
}
// Render all the entities
for(auto& i : entities){
  mRenderer->draw(i->getSprite());
}

```

# Answer
> 30 votes
The simple approach is to just make the thing that used to be `Singleton<T>` a global `T` instead. Globals have problems too, but they don't represent a bunch of extra work and boilerplate code to enforce a trivial constraint. This is basically the only solution that won't involve (potentially) touching the entity constructor.

The more-difficult, but possibly better approach is to *pass your dependencies to where you need them*. Yes, this might involve passing a `Window *` to a bunch of objects (like your entity) in a fashion that looks gross. The fact that it looks gross should tell you something: your design might be gross.

The reason this is more difficult (beyond involving more typing) is that this often leads to refactoring your interfaces so that the thing you "need" to pass is needed by fewer leaf-level classes. This makes a lot of the ugliness inherent in passing your renderer to everything go away, and it also improves the general maintainability of your code by reducing the amount of dependencies and coupling, the extent of which you made very obvious by taking the dependencies as parameters. When the dependencies were singletons or globals, it was less obvious how interconnected your systems were.

But it is potentially a *major* undertaking. Doing it to a system after the fact can be downright painful. It may be far more pragmatic for you to simply leave your system alone, with the singleton, for now (especially if you're trying to actually ship a game that otherwise works just fine; players aren't generally going to care if you have a singleton or four in there).

If you do want to try doing this with your existing design, you may need to post a lot more details about your current implementation as there isn't really a general checklist for making these changes. Or come discuss it in chat.

From what you've posted, I think a big step in the "no singleton" direction would be to avoid the need for your entities to have access to the window or view. It suggests that they draw themselves, and you don't have to have entities draw themselves. You can adopt a methodology where the entities just contain the information that would *allow* them to be drawn by some external system (which has the window and view references). The entity just exposes its position, and the sprite it should use (or some kind of reference to said sprite, if you want to cache the actual sprites in the renderer itself to avoid having duplicate instances). The renderer is simply told to draw a particular list of entities, which it loops through, reads the data from, and uses its internally-held window object to call `draw` with the sprite looked up for the entity.

# Answer
> 6 votes
## **Inherit from sf::RenderWindow**

SFML actually encourages you to inherit from its classes.

```
class GameWindow: public sf::RenderWindow{};

```

From here, you create member draw functions for drawing entities.

```
class GameWindow: public sf::RenderWindow{
public:
 void draw(const Entity& entity);
};

```

Now you can do this:

```
GameWindow window;
Entity entity;

window.draw(entity);

```

You can even take this a step farther if your Entities are going to hold their own unique sprites by making Entity inherit from sf::Sprite.

```
class Entity: public sf::Sprite{};

```

Now `sf::RenderWindow` can just draw Entities, and entities now have functions like `setTexture()` and `setColor()`. The Entity could even use the sprite's position as its own position, allowing you to use the `setPosition()` function for both moving the Entity AND its sprite.

---

**In the end**, it's pretty nice if you just have:

```
window.draw(game);

```

**Below are some quick example implementations**

```
class GameWindow: public sf::RenderWindow{
 sf::Sprite entitySprite; //assuming your Entities don't need unique sprites.
public:
 void draw(const Entity& entity){
  entitySprite.setPosition(entity.getPosition());
  sf::RenderWindow::draw(entitySprite);
 }
};

```

OR

```
class GameWindow: public sf::RenderWindow{
public:
 void draw(const Entity& entity){
  sf::RenderWindow::draw(entity.getSprite()); //assuming Entities hold their own sprite.
 }
};

```

# Answer
> 3 votes
You avoid singletons in game development the same way you avoid them in every other kind of software development: *you pass the dependencies*.

With that out of the way, you can choose to pass the dependencies directly as bare types (like `int`, `Window*`, etc) or you can choose to pass them in one or more custom wrapper types (like `EntityInitializationOptions`).

The former way can get annoying (as you have found out), while the latter will allow you to pass everything in one object and modify the fields (and even specialize the options type) without going around and changing every entity constructor. I think the latter way is better.

# Answer
> 3 votes
Singletons are not bad. Instead they are easy to abuse. On the other hand, globals are even easier to abuse and have loads more problems.

The only valid reason to replace a singleton with a global is to pacify the religious singleton haters.

The problem is having a design which includes classes of which only a single global instance ever exists, and which needs to be accessible from everywhere. This breaks apart as soon as you end up having multiple instances of the singleton, for example in a game when you implement split screen, or in a sufficiently large enterprise application when you notice a single logger isn't always such a great idea after all.

Bottom line, if you really have a class where you have a single global instance **which you can't reasonably pass around by reference**, singleton is often one of the better solutions in a pool of suboptimal solutions.

# Answer
> 1 votes
Inject dependencies. A benefit of doing this is now you can create various types of of these dependencies via a factory. Unfortunately, ripping singletons out of a class that uses them is like pulling a cat by it's hind legs across a carpet. But if you inject them, you can swap out implementations, perhaps on the fly.

```
RenderSystem(IWindow* window);

```

Now you can inject various types of windows. This allows you to write tests against the RenderSystem with various types of windows so you can see how your RenderSystem will break, or perform. This is not possible, or more difficult, if you use singletons directly inside of "RenderSystem".

Now it is more testable, modular, and it's also decoupled from a specific implementation. It's only dependent upon an interface, not a concrete implementation.

---
Tags: c++, design-patterns, oop
---


# Question
Title: Apple iOS review and interpreted code download/execution
I'm looking for some information regarding two specifics rules of the App Store Review guidelines. More specifically rules 2.7 and 2.8 :

> 2.7 Apps that download code in any way or form will be rejected
>
> 2.8 Apps that install or launch other executable code will be rejected

I intend to make a multiplayer mobile game that I could update remotely. So I used a framework that allows me to use a script language (namely Lua) on the top of my engine to code game logic. My intention was to have the client submitted and validated by Apple, and then have it download the latest version of the game data (imagine a zip file with assets and Lua scripts). However this seems to be forbidden by Apple. I do know that some rather famous game do it anyway (downloading JSON/Lua/JS files) to update their games, but I would like some clarifications.

My questions are the following :

* Has anyone here made such a system on iOS ? If yes how did you deal with Apple ? Did you ask them about it ? Did you do it silently, hoping they don't notice ?
* Has anyone ever been rejected because of that ? What did they say ? What was the incriminated download ?
* Has anyone more information about those guidelines ? Where do they draw the line ? I suspect JSON/XML to be allowed, but it's unclear...
* I imagine they could make some concession for big companies. If it's the case and you had them agree on something with you, how did you manage to do it ? Who did you contact ?
* Broadly, any information regarding this would be welcome :

+ How did you / would tackle that issue ?
    + Are you aware of similar limitations for other platforms ?
    + Do you know a workaround for this situation ?

# Answer
> 2 votes
Do not count on getting an exemption for this. I haven't personally seen one. You can build stuff in a data-driven manner, but as soon as it's compiling code locally, you're in trouble.

Think of what's going on with Unity. They use Mono, and open-source version of the .NET framework. It has a Just-In-Time (JIT) compiler to handle some stuff. But on iOS, that's not allowed. So for iOS builds it does an Ahead-Of-Time (AOT) compile. This means certain parts of .NET don't work on iOS.

Unity is not a small company, and their engine has a very large userbase. Yet no exemption on compiling code locally.

# Answer
> 1 votes
Related: https://apple.stackexchange.com/questions/203189/will-the-app-store-reviewers-allow-scripts-downloaded-as-text-if-it-is-parsed-v

In short; Downloading Lua should be fine.

It's important to note the difference between executed code and an interpreted language; Lua is an interpreted language and is not itself an executed binary code and as such should be permissible with the current Apple guidelines. In this way, the Lua file is more like a configuration file that you are downloading to interact with your existing codebase.

Do note that it is extremely important that you lock down your Lua interpreter in your project to only allow access to what your scripts will need. Even though they are not executed code, they can be exploited by attackers to negatively impact your application.

---
Tags: ios, legal, mobile
---


# Question
Title: The Power of 2D Engines vs Modern 3D Games
I'm toying around a lot with Game Maker. I really like it. GML is very simple and with its nearly object oriented design you could create anything in 2D you can think of. However there is a limit. And this limit astonishes me in comparison to modern AAA 3D games. How can't Game Maker handle (let's say) 3000 Sprites without dropping the frame rate but something like Crysis, Assasins Creed, Far Cry, Star Citizen which seems to be handling much more calculations at one frame works without problems.

I know that there is a performance difference between languages and that a lot of code can be optimized to get the best results. But is it just how the code is written that 3D engines are so powerful? Why do modern 3D games seem like doing much more but at the end present better results then 2D engines like Game Maker? And would for example something like Unity be faster that is using a real language like C#? Are there C++ engines or frameworks known for their performance? I'm not going to get away from Game Maker soon since my programming skills are not that great. I'm just trying to understand why modern games engines seem so powerful against Game Maker. Or did I get something wrong?

# Answer
The bottleneck for games is usually the bandwidth and latency between cpu and gpu, not the number of calculations you're doing.

Using your example of 3,000 sprites, the reason it's so slow is because Game Maker draws them all individually, which means 3,000 draw commands going from the cpu to the gpu. Even though each draw command is really simple, every new command has a slight delay to it as it works its way through the driver and then through the wires to the gpu.

Particle systems also draw sprites, but they can draw thousands or even millions of them without hurting your fps any. This is because the information for all those sprites is combined into one buffer and drawn with one command. It comes with some limitations, though, especially if you want each sprite to have a different texture or behave differently. It's hard for a game framework to generalize this technique, so it's usually limited to particles unless you can write your own shaders.

When it comes to 3D, drawing 10 boxes is pretty close to drawing 10 sprites. The calculations are a little more complicated, but you're still using a miniscule fraction of the gpu's power. The number of draw calls is the same, so you'll get about the same fps. Once you add lighting, shadows, anti-aliasing, and so on, then you might get closer to that computational limit, but since you're still using the same number of draw calls, you'll stay under the bandwidth limit, which lets you do a lot more.
> 3 votes

# Answer
> seems to be handling much more calculations

Bad assumption. I have no idea abut the internal details of gamemaker, but in the worst case, it could be calculating 3000^2 2D collisions every game loop. Meanwhile, assassin's creed could be calculating a very small number (like less than 100) 3D collisions at any given time.

The fact that assassin's creed looks so much nicer is more due to the huge amount of work put into artwork, animation, and modeling than anything to do with 2D or 3D engines.
> 0 votes

---
Tags: 2d, 3d, game-maker
---


title: Using deltaTime

text:
# Question
Title: Using deltaTime
I got deltaTime calculated as 2.7855414E8 on my tablet. How do I get speed for specific device, calibred by deltaTime? For example, if I need object with moving speed, which is about reaching half device screen size per 1 second?

Edit: delta calculation

```
timeStart = System.nanoTime();
deltaTime = (timeStart - oldTimeStart) / 1000000;
oldTimeStart = timeStart;

```

# Answer
> 1 votes
Ostensibly, `deltaTime` is measured by units of...time e.g. seconds, meaning the device itself is irrelevant for that.

What you want is to multiply by the number of pixels in the device's screen (or some fraction thereof). You'll have to look up how to get that yourself, but it's probably something like `Screen.width` or `Screen.screenWidth` (I've only done android and ios development in Unity, not Java so I do not know the appropriate class that has what you need).

For example, to move across the screen in 2 seconds and assuming that position is measured in device-pixels, you'd do this:

```
onUpdate() {
    pos.x += Screen.Width/2 * deltaTime;
}

```

---
Tags: java, android
---


# Question
Title: What's the best way to make multiple objects of the same thing?
I am coding in C#. Due to limitations of the environment I will be working in, I cannot use any framework like the XNA Framework; only what is provided by default on Windows.

I want to create multiple ledges in a platform game. This is what I currently have in the object class:

```
class Object
{
    Bitmap _image;
    Usables.Collisions collideType;

    public Object(string image, bool collideX, bool collideY)
    {
        //sets image for picturebox BG
        _image = new Bitmap(Usables.baseDir + image);
        // Collision also set here
    }

    public Bitmap Image
    {
        get { return _image; }
    }
}

```

and I am assigning it to a pictureBox this way in the form:

```
public void initGame()
    {
        pb_ledge1.Image = World.Ledge.Image;
    }

```

And the World class is like this:

```
class World
{
    static Object Ledge1 = new Object("test.png", true, true);

    static public Object Ledge
    {
        get { return Ledge1; }
    }
}

```

Obviously in a finished product the World class would not be set like that. The images for the different ledge types would be set dynamically.

But my main concern is if I had 8 blocks going across the screen, I would have 8 pictureBoxes, and I would assume professional game developers do not manually assign each 8 boxes individually. Is there a way around this?

# Answer
**Flyweight**

One approach is to use a form of the flyweight pattern.

You don't give each instance of an object the image. Instead, you have one object that represents a type of thing in your game and has all common non-instance data, like the image, physics properties, etc.

The individual instances then have per-instance information, like position, and a reference to the shared data object.

**Cloning**

Another approach is to clone a single object. Once you configure a single instance of an object the way you want, you just create copies/clones of that object.

In this approach, you'll often have a list of object types by name somewhere in your level and then the instances in the level reference those objects by name. During level load, you just call your `Clone` method on the shared object to create each instance.

All the images are such are just copied from the original so there's no need to respecify them for each copy.

**Reification**

Similar to cloning, you might just recreate the object from encoded data.

This is very similar to cloning objects; it's mostly just a different want of implementing the technique. Instead of loading a whole object and keeping a fully instantiated object, you instead cache some efficient serialized copy of the object configuration and then deserialize that for each instance.

The advantage of this approach is that your game objects and game logic don't need to handle the special case of template objects vs instance objects. You don't need much of that logic at first but it can add up as your game gets more complex.
> 1 votes

---
Tags: c#, platformer
---


title: Rotating object around a rotating one?

text:
# Question
Title: Rotating object around a rotating one?
I am developing a solar system animation in Unity3D. Planets rotates around sun. But ı have an issue simulating satellites like Moon. Moon should be rotating around world normally and moon should be rotating around World. Since World is rotating around Sun , i am having trouble about calculating true rotation for moon. I don't want to use rotateAround() since it is deprecated. I need to make this done using Rotate().

this is my planetScript

```
public class planetScript : MonoBehaviour {

    public GameObject target;//target is Sun for World, World for Moon etc

    public float rotateRatioCenter;//1 degree for World
    private float rotateSpeedTarget;

    public float rotateRatioAround;//365 for World
    private float rotateSpeedAround;

    public float counter = 0;
    void Start () {
    }

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

     rotateSpeedTarget = rotateRatioCenter * gameMasterScript.rotateAroundCenterRatio;//  rotateRatioCenter * 1 ,
     rotateSpeedAround = rotateSpeedTarget * rotateRatioAround;
     float yRotate = transform.eulerAngles.y;

     transform.Rotate(Vector3.up, rotateSpeedAround);

     rotateAroundTarget();
    }

    void rotateAroundTarget()//this is the method should be optimized
    {
        Quaternion quaRot = Quaternion.Euler(0, rotateSpeedTarget, 0);
        transform.position = quaRot * (transform.position - target.transform.position) + target.transform.position;
    }
}

```

gameView

# Answer
The easiest way to have one `GameObject` "orbit" around another (without `Transform.RotateAround()` would be to utilize the hierarchy. Each planet can have an empty `GameObject` as its parent that's a child of its `target` like so

```
> Sun
   > Rotator (empty GameObject)
      > Planet
         > Rotator
            > Moon
   > Rotator
      > Planet
   > Rotator
      > Planet

```

Here's how you can accomplish that with your script:

```
public class planetScript : MonoBehaviour {
    public GameObject target;

    void Start() {
        m_rotator = new GameObject("rotator");
        m_rotator.transform.parent = target.transform;
        m_rotator.transform.localPosition = Vector3.zero; // Might not need this

        this.gameObject.transform.parent = m_rotator.transform;
        this.gameObject.transform.localPosition = new Vector3(radius, 0, 0);
    }

    void Update() {
        // Rotate m_rotator
        m_rotator.Rotate(Vector3.up * Time.deltaTime);
    }

    private GameObject m_rotator;
}

```

Also, as a note, this makes sense if you're using `Transform.Rotate()` but `Transform.RotateAround()` is not deprecated and you're free to use it. Not sure where you got that info from but it's supported in the latest release of Unity.
> 1 votes

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


# Question
Title: How to remove destroyed clones out of the Hierarchy in Unity2D
I made a 2D edge collider which on contact destroys the other gameobject. When I launch the game all the other gameobjects in fact get destroyed but the clones are still listed in the Hierarchy. How can I get rid of this? Thanks in advance.

The corresponding code is:

```
using UnityEngine;
using System.Collections;

public class DestroyByBoundary : MonoBehaviour {

void OnTriggerEnter2D (Collider2D other)
{
    Destroy(other.gameObject);
}

```

}

# Answer
> 2 votes
You must add a `Collider2D` to any `GameObject` that is to be destroyed by `DestroyedByBoundary`. According to the documentation, just having the `RigidBody2D` isn't sufficient:

> Colliders are another kind of component that must be added alongside the Rigidbody in order to allow collisions to occur.

And for 2d, specifically:

> The collider types that can be used with Rigidbody 2D are the Circle Collider 2D, Box Collider 2D, Edge Collider 2D and Polygon Collider 2D

If you have the performance to spare, you should also change "Collision Detection" to "continuous".

---
Tags: unity, c#, 2d, collision-detection
---


title: Particles to Denote Movement in Space

text:
# Question
Title: Particles to Denote Movement in Space
I'm currently working on a WebGL project to realise an idea I've had for some years. On my desk is book on making a space sim written 15 years ago.

There I found some algorithm for particles in space. The idea is simple: A cloud of particles that stay in place so they fly past the player, but reset to be in front of the player when they move past the ship. This shows the player they're moving while there's nothing else around. For this, I reworked the algorithm found in the book a little:

```
ParticleField.prototype.updateCloud = function(frustum, position, direction) {
  var s = this.size, s2 = s * 2;

  for (var i = 0; i < this.vertices.length; i++) {
    if (!frustum.containsPoint(this.vertices[i])) {
      this.vertices[i].set(
        (position.x + s - Math.floor(Math.random() * s2)) + (s * direction.x),
        (position.y + s - Math.floor(Math.random() * s2)) + (s * direction.y),
        (position.z + s - Math.floor(Math.random() * s2)) +
                         ((s + Math.floor(Math.random() * s2)) * direction.z)
      );
    }
  }
};

```

Where `s` is the size of cloud. I played around with the sizes, but this simple function has several weaknesses.

* The particles 'pop up' in front of the player when they're moving.
* If the player backs up and moves backwards, the particles won't reset, leaving the cloud visible popping the illusion.
* Particles appear to be flying through the player.

Without regard of how the particles look (they're simple points right now), how can I make this look more natural? I've seen the effect in games like Elite: Dangerous and Freelancer, and I'd like to be closer to them, and I'd appreciate any hint on the topic.

# Answer
**"The particles 'pop up' in front of the player when they're moving."**

Your calculations aren't generating points outside the view frustum, and it seems they're going to be re-generated until they happen to be placed either inside the frustum (getting you the 'pop up' issue), or *right* outside the frustum, in the direction of travel.

*I'm assuming throughout this that you're allowing the player to move arbitrarily in all 3 dimensions.*

To fix this, you need two changes:

1. Generate your particles farther ahead. Without changing that you're generating in a uniform cube, a hack solution would mean changing the final `(s * direction.x)` into something like `(s * 5 * direction.x)`, where `5` is some number big enough to place things outside the frustum. Ideally you would calculate it based on the frustum.
2. Points generated outside the frustum need to be left alone until they appear on-screen, or they're behind the frustum, too old, or what-have-you. Lots of ways to do this. In your case, perhaps change the initial check to also verify the particle has appeared and isn't too old, and set those variables right after resetting the point. (Below, I use a max age of 5 seconds, which may be too much or too little, depending on player velocity.)

---

**"If the player backs up and moves backwards, the particles won't reset, leaving the cloud visible popping the illusion."**

I'm assuming here that you're describing the player facing one way, but moving the opposite direction. (If this is wrong, let me know. :P)

Without changing the meaning of "direction" anywhere else, you could fix this by passing the function a fourth parameter which is essentially a "facing" multiplier that's 1 when moving forwards, -1 when moving backwards. Then `(s * 5 * direction.x)` becomes `(s * 5 * direction.x * facing)`.

This should change particles so they generate behind the player instead.

---

**"Particles appear to be flying through the player."**

I'll take this literally and assume you're saying you don't want particles passing through your player's model. To fix this, you need to prevent particles from being placed in column your player's model will sweep as it moves forward.

You could maybe change the initial point generation to enforce this from the get-go, but I think in this case I'd recommend just re-generating any points that don't satisfy that constraint.

Given your direction vector and player's position, you can calculate two points (position, and position+direction) and build off of the javascript code in this answer.

Removing the two lines `if (t < 0) ...` and `if (t > 1) ...` \- should yield the distance from some point to some arbitrary infinite line defined by those two points.

Armed with this, you can check each generated point to ensure its result is far enough away from center to not hit the player's model. If it's too close, just generate it again. Unless your cube cross-section is similar in size to the sweep cross-section, this shouldn't usually take more than a couple of attempts.

I'm assuming the model is centered on the player's position and roughly symmetric. So then we want to calculate half the longest dimension, perpendicular to the model's "forward" direction. So for a humanoid model, this would be height. For a typical airplane it would be half the wingspan, etc. In the code below I'm calling this `modelWidth` and just hard-coding it, but you should get this value in whatever way fits your game.

---

Lastly, here's the code. **Deliciously untested!**

```
ParticleField.prototype.updateCloud = function(frustum, position, direction, facing) {
  var s = this.size, s2 = s * 2;
  var modelWidth = 11; // arbitrary magic number representing width of your model
  var d = new Date();

  for (var i = 0; i < this.vertices.length; i++) {
    if (!frustum.containsPoint(this.vertices[i])) {
      // you'll need to initialize the variables elsewhere of course
      if(this.vertices[i].dieAfter <= d.getTime() || this.vertices[i].hasAppeared)
      {
        do {
          this.vertices[i].set(
            (position.x + s - Math.floor(Math.random() * s2)) + (s * 5 * facing * direction.x),
            (position.y + s - Math.floor(Math.random() * s2)) + (s * 5 * facing * direction.y),
            (position.z + s - Math.floor(Math.random() * s2)) +
                ((s + Math.floor(Math.random() * s2)) * 5 * facing * direction.z)
                // I'm unsure why z has this extra factor in it. :P
          );
        } while( distToSegment(this.vertices[i], position, position+direction) <= modelWidth);
        // may want to cap how many times this can run

        this.vertices[i].dieAfter = d.getTime() + 5000; // 5s in milliseconds
        this.vertices[i].hasAppeared = false;
      }
    }
    else
    {
      this.vertices[i].hasAppeared = true;
    }
  }
};

...

// swiped from https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment
function sqr(x) { return x * x }
function dist2(v, w) { return sqr(v.x - w.x) + sqr(v.y - w.y) }
function distToSegmentSquared(p, v, w) {
  var l2 = dist2(v, w);
  if (l2 == 0) return dist2(p, v);
  var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
  return dist2(p, { x: v.x + t * (w.x - v.x),
                    y: v.y + t * (w.y - v.y) });
}
function distToSegment(p, v, w) { return Math.sqrt(distToSegmentSquared(p, v, w)); }

```
> 3 votes

---
Tags: javascript, movement, particles
---


# Question
Title: Rotate camera with quaternion around axis going through the origin
I am trying to implement my own third person camera using quaternions in DirectX. I first wanted to check that the camera rotates as expected so I started to rotate it around the world y-axis (0,1,0) and then x-axis (1,0,0) and it worked fine. But when rotating around the axis (1,1,0) the effect is not what I expected. Here is a description of what I do.

The scene is composed by a cube of side 2, centered at the world origin. The camera is originally placed at (0,0,-10), looking at the origin (0,0,0) and has the up vector (0,1,0). To test the rotation, at each frame I increase the angle of rotation theta by a constant amount dTheta. I build my quaternion from the axis of rotation (1,1,0) and the angle theta, transform the quaternion to its 3-by-3 matrix form and multiply both the position vector and up vector. I call the D3DXMatrixLookAtLH function to build the view matrix with the new position, the lookAt point (the origin of the world frame) and the new up vector.

What I get is my cube rotating in a very strange way (well, I know it is the camera that is rotating, but you know what I mean, everything is relative). Moreover it seems the distance between the cube and the camera changing because, as the cube rotates, its size oscillates.

I can put some code if someone asks but I first wanted to check there is no mistake in my approach. Thanks.

# Answer
Quaternions can encode both a rotation and a uniform scaling using non-normalized quaternion, this might be what is happening.

The axis of rotation (1, 1, 0) is not nomalized. Try with (0.707106781, 0.707106781, 0) which is the unit vector pointing in the same direction.
> 0 votes

---
Tags: directx, quaternion
---


# Question
Title: Unity 2D Hingejoints break under extreme force
I have added a rope to my game that is made up of multiple small gameobjects, each connected to eachother by a HingeJoint2D. Since 1 unit of mass in Unity is supposed to represent 1 kg, I've made the player's mass 60 (60kg). When the mass of each rope segment (of which there are 40) is 20, the rope supports the player when they jump off a cliff.

Now 20 kg per rope segment sounds ludicrous. However when I make each rope segment weigh 1 (1kg) the hingejoints break completely and jitter around crazily. The force of the 60kg player against the 1kg segments seems to be too much.

I would much rather have the rope be lighter, so it doesn't move the player when throwing and being dragged as much. Any suggestions on how to fix HingeJoint2D's and make them act, as you know, a joint should?

EDIT: Increasing the Position and Velocity Iterations in File-\>Project-\>Physics2D menu from the default 3 and 9 respectively, up to a whopping 40 fixes this problem. This is a massive increase. Unsure if performance will suffer too much with these new settings.

# Answer
> 1 votes
Yes, they do; all joints do. And there is no (realistic) solution as fas as i know.

I read somewhere in documentation that says two objects connected with a joint should have close masses. It's too weird, actually.

I encourage you to use good old parent-child technique; never breaks, never acts oddly, and never extends (or reverse) like your second image.

---
Tags: physics, unity, rope-physics
---


# Question
Title: Texture being stretched when using D3DTADDRESS_CLAMP
I'm trying to create a skybox using a cube and using one of this textures: http://forum.unity3d.com/threads/mundus-skybox-pack-01-released.202748/

I've got it working well, but I noticed there are some bugs on the edges of the cube, as it can be seen here:

I found that this could be fixed using clamping, so I set `D3DSAMP_ADDRESSU` and `D3DSAMP_ADDRESSV` to `D3DTADDRESS_CLAMP`. This, however, produced the following result:

Half of the cube wasn't being shown and the other half was only showing a one-pixel wide texture region. I saw this similar question (which uses wrapping though), but I'm already using 4 vertices per face. So, what could be causing this?

# Answer
What are the texture coordinates that you're using for those vertices? With `D3DTADDRESS_CLAMP`, they must be in the \[0;1\] range, anything else will be clamped to \[0;1\]. So, for example, using the \[-1;0\] coordinate range could cause this as it would make all of them effectively 0.
> 2 votes

---
Tags: textures, directx, directx9, skybox
---


# Question
Title: Is it possible to use Box2D or Chipmunk in Swift & Cocos2d?
I am new to iOs programming.

I wonder whether it is possible to use Box2D physic engine in Cocos2D with Swift. I am asking because I started to learn Swift. And I create Xcode project from Spritebuilder with Swift.

# Answer
> 0 votes
You can use box2d with cocos2d, you can check some tutorials on it or refer this http://www.cocos2d-x.org/wiki/Box2D

---
Tags: box2d, xcode, swift
---


# Question
Title: How to get an AbstractClientPlayer for all players?
I'm working on an minecraft forge mod (1.8.8). I have en custom (ownable) entity and want to set its texture to the texture of its owner, because it's a mini version of the owner.

I found out that i can get the texture of players with `AbstractClientPlayer#getLocationSkin()`, but i can't figure out how to access either `EntityOtherPlayerMP` or `EntityPlayerSP`, which implement `AbstractClientPlayer`, in my custom renderer. Is there a way to get all `AbstractClientPlayer`, regardless of SP or MP? I can access the GameProfile and i have the EntityPlayer of the owner.

# Answer
Ok, the solution is fairly simple: I was able to simply cast the `EntityPlayer` to an `AbstractClientPlayer`! I got the EntityPlayer with my EntityLiving, because its an ownable creature:

```
@Override
protected ResourceLocation getEntityTexture(EntityLiving entity) {
    IEntityOwnable creature = (IEntityOwnable) entity;
    AbstractClientPlayer player = (AbstractClientPlayer) creature.getOwner();
    return player.getLocationSkin();
}

```
> 1 votes

---
Tags: minecraft-modding, modding
---


# Question
Title: (GLSL) Lighting code outputting a black quad
So, ive been transitioning to modern opengl recently and it's going rather well. But alas, something must go wrong. As the titel says, all I'm getting is a completely black quad. (Ive double checked my C++ code and I'm pretty sure it has nothing to do with that.)

```
#version 330 core

//Vertex shader

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
layout(location = 2) in vec2 vertexUV;
layout(location = 3) in vec3 vertexNormal;

out vec3 vertNorm;
out vec3 fragmentColor;
out vec3 vertPos;
out vec2 UV;

uniform mat4 MVP;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1.0f);
    UV = vertexUV;
    fragmentColor = vertexColor;
    vertPos = vertexPosition_modelspace;
    vertNorm = vertexNormal;
}

//Fragment shader
#version 330 core

in vec3 Normal;
in vec3 fragmentColor;
in vec3 vertPos;
in vec2 UV;

out vec3 color;

uniform sampler2D textureSampler;
uniform mat4 Model;

void main(){
    vec3 lightPos = vec3(0, 0, 0);
    mat3 normalMatrix = transpose(inverse(mat3(Model)));
    vec3 normal = normalize(normalMatrix * Normal);
    vec3 fragPosition = vec3(Model * vec4(vertPos, 1));
    vec3 surfaceToLight = lightPos - fragPosition;

    float brightness = dot(normal, surfaceToLight) / (length(surfaceToLight) * length(normal));
    brightness = clamp(brightness, 0, 1);

    color = vec3(brightness * 1 * (texture(textureSampler, UV).rgb * fragmentColor));
}

```

But if you require my c++ code, say so and ill edit.

# Answer
> 2 votes
Note that `out vec3 vertNorm;` in your vertex shader does not match your corresponding input variable in the fragment shader `in vec3 Normal;`.

Since `Normal` in your fragment shader doesn't have any input it defaults to `vec3(0, 0, 0)`. So your end up with a lot of unspecified behavior since you are normalizing a zero-vector which in this case probably returns another zero-vector. I don't know if there is an OpenGL standard there, at least it did for me. Then when calculating brightness you divide by zero again. Your math teacher would be furious at your dividing by zero twice in just a little bit of your code.

The end result is that brightness is 0 which is multiplied with the colors making all of the output colors vec3(0, 0, 0) or black.

---
Tags: opengl, glsl
---


title: SDL2 and density-independent pixel

text:
# Question
Title: SDL2 and density-independent pixel
I'm currently using SDL2 on Android and that's my first experience with that library (to be honest, mainly chosen because I'd like to learn it).
What is puzzling me is how to deal with different resolutions and density-independent pixels, for I cannot figure out which is the recommended approach to create images and let them look decently on screen on the most of the devices.

Unfortunately, googling around I've not been able to find a decent example or a bunch of information sufficient to clarify the doubts.
It seems that the most common suggestion is to choose a fixed size virtual resolution for the content rectangle, thus draw on top of it and finally resize it to the actual one, but it would be appreciated to know if this one is really a widely used approach and if there are some others that are more suitable.

Thank you.

# Answer
## **Texture Filtering**

SDL2 allows you to use texture filtering. This interpolates the pixels of your textures to be smooth when scaled larger or smaller than 1:1 or if the texture is not lined up with the display pixels. This gives you nice smooth sprites that move smoothly and look pretty good at nearly any resolution.
> 1 votes

---
Tags: android, sdl, resolution, sdl2
---


title: Question on specific custom inspector

text:
# Question
Title: Question on specific custom inspector
Ive just finished Alex Stv's Voxel tutorial on http://alexstv.com/index.php/category/voxel-tutorial, and realized it would be very handy to have a custom inspector for the TerrainGenerator variables, so that I could easily tweak and test how the world would change by using it.

The problem is, the class doesn't actually implement MonoBehaviour, as it's always used by other classes. I could extend the class to MonoBehaviour, and that would allow me to use the inspector, but since this class only really governs how the height map are going to effect the position and type of the voxels, not the creation of the world itself, it would make the inspector less useful.

I wanted to be able to have a button in the inspector to regenerate the world, check the changes in a quick and efficient way. How would I go about to have an inspector that would both allow me to regulate and change the variables in TerrainGenerator, and also allow me to regenerate and (maybe) change some world variables?

Would I need to have multiple inspectors--one to change the variables used in the simplex, and another, smaller one for the regenerative button?

# Answer
This can all be done within one inspector window, but requires two scripts to be made.

Create a `TerrainGenerator : Monobehavior` script that is attached to an empty game object. This is going to hold your chunk data in the form of a `GameObject` called root. You can make this a private variable or expose it publicly to manually set a root `GameObject`.

Next, create a `TerrainGeneratorEditor : Editor` class. This class will expose variables for `width`, `height`, `noiseAmount`, etc. This inspector will also present a button to generate the terrain. You would instantiate all the generator classes required inside the `TerrainGeneratorEditor : Editor` class. `Chunk.cs`, `Block.cs`, etc.

Now your generate button will do two things.

First is calling some type of `Destroy()` on your `TerrainGenerator : Monobehavior` script to kill your current batch of chunks attached to the root.

Then you generate new chunks and parent them to the root `GameObject` found inside your `TerrainGenerator : Monobehavior` script.
> 1 votes

---
Tags: unity, procedural-generation, voxels
---


# Question
Title: Transforming normals along with vertex? (GLSL)
So, I got a model matrix (Via uniform variable) in the shader, is there any way to use the model matrix to transform the normal of a vertex that has been transformed with glm::transform/rotate?

If you want, here is the code:

VERTEX SHADER:

```
#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
layout(location = 2) in vec2 vertexUV;
layout(location = 3) in vec3 vertexNormal;

out vec3 Normal;
out vec3 fragmentColor;
out vec3 vertPos;
out vec2 UV;

uniform mat4 MVP;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1.0f);
    UV = vertexUV;
    fragmentColor = vertexColor;
    vertPos = vertexPosition_modelspace;
    Normal = vertexNormal;
}

```

FRAGMENT SHADER:

```
#version 330 core

in vec3 Normal;
in vec3 fragmentColor;
in vec3 vertPos;
in vec2 UV;

out vec3 color;

uniform sampler2D textureSampler;
uniform mat4 Model;

void main(){
    vec3 lightPos = vec3(1, 1, 1);
    mat3 normalMatrix = transpose(inverse(mat3(Model))); // I think this line could do it, but it doesn't seem to work.
    vec3 normal = normalize(normalMatrix * Normal);
    vec3 fragPosition = vec3(Model * vec4(vertPos, 1));
    vec3 surfaceToLight = lightPos - fragPosition;

    float brightness = dot(normal, surfaceToLight) / (length(surfaceToLight) * length(normal));
    brightness = clamp(brightness, 0.2, 1);

    color = vec3(brightness * 1 * (texture(textureSampler, UV).rgb * fragmentColor));

}

```

# Answer
> 1 votes
Managed to fix it:

VERTEX SHADER:

```
#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
layout(location = 2) in vec2 vertexUV;
layout(location = 3) in vec3 vertexNormal;

out vec3 Normal;
out vec3 fragmentColor;
out vec4 vertPos;
out vec2 UV;
out mat4 mvp;

uniform mat4 MVP;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1.0f);
    UV = vertexUV;
    fragmentColor = vertexColor;
    vertPos = MVP * vec4(vertexPosition_modelspace,1.0f);
    Normal = vertexNormal;
    mvp = MVP;
}

```

FRAGMENT SHADER:

```
#version 330 core

in vec3 Normal;
in vec3 fragmentColor;
in vec4 vertPos;
in vec2 UV;
in mat4 mvp;

out vec3 color;

uniform sampler2D textureSampler;
uniform mat4 Model;
uniform mat4 lmvp;

void main(){
    vec4 lightPos = lmvp * vec4(-0.5, 0.5, -0.5, 1);
    mat3 normalMatrix = transpose(inverse(mat3(Model)));
    vec3 normal = normalize(normalMatrix * Normal);
    vec3 fragPosition = vec3(Model * vec4(vertPos.xyz, 1));
    vec3 surfaceToLight = lightPos.xyz - fragPosition;

    float brightness = dot(normal, surfaceToLight) / (length(surfaceToLight) * length(normal));
    brightness = clamp(brightness, 0.2, 1);

    color = vec3(brightness * 1 * (texture(textureSampler, UV).rgb * fragmentColor));
}

```

---
Tags: glsl, transformation
---


# Question
Title: How can I manipulate a static 2D sprite so that it looks alive?
I've got a stick figure in the corner of my UI, but I don't like the way he's just standing there, without moving. I'm stuck without additional frames of animation, so my only recourse is the manually move the sprite up and down, left to right, rotation, or whatever else you can think of. Basically I can do everything besides drawing another sprite of animation.

I've tried things like have it subtly bounce or rotate a bit to give it a little bit of dynamism, but I don't believe its the best approach.

I've got a static sprite of a stick figure, how do I give it a bit of life?

# Answer
> 3 votes
There are many ways. I'll try to list some, from simplest to more advanced:

* Stretch your sprite vertically/horizontally a bit, as if it was breathing
* If that fits your game, make it skew, rotate, move around a bit
* Draw several more sprites and loop through them
* Generate UV map for your figure and shift map coordinates for head, body, limbs, etc each frame
* Split your figure into parts and animate the parts (head, body, limbs)

# Answer
> 1 votes
In addition to what others have suggested, you can also vary:

1. Color
2. Luminance
3. Opacity
4. Apply transitions to it, such as a vertical or horizontal wipe, blinds, page curl, etc.
5. Apply filters to it, such as distorted TV, getting sucked into a black hole, etc.
6. Do other things around it, such as making it rain, snow, etc.
7. Change the lighting on it so it appears to cycle through a day and/or night
8. Make it hold various items at different times - balls, flags, tools, whatever

EDIT: Another option you have is to animate the background the figure is against rather than the figure itself. You could have a texture or procedural pattern that you move in some way (translate, scale, rotate, whatever).

---
Tags: animation, art
---