# Question
Title: Transparency temporarily lost from a rendertarget when drawn to for one frame
I have a transparent RenderTarget2D that I draw every frame. Before the first frame is drawn to the screen, an image is drawn to the render target. The image also contains some transparent pixels. Every frame, that render target is then drawn to the screen.

In response to a mouse click, a second image is drawn to the render target that is masked by any solid pixels, so that the transparent pixels aren't overwritten. I followed ClassicThunder's instructions here and modified the code so that the second image is only drawn when I need it to be. This code does the job well enough to achieve the end result, but exhibits some odd behaviour.

Although the end result is exactly how I want it, for the frame where the render target is modified the alpha channel seems to be ignored. The result is that all transparent pixels turn black for that frame. From the next frame onwards the render target behaves as I'd expect it to when drawn, and the transparency returns.

Edit: Here's everything from Game1.cs. It's a test project and doesn't require any external assets. I should probably also mention that I'm using MonoGame.

```
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace StencilTest
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D target;
        Texture2D projectile;
        Random random = new Random();

        RenderTarget2D layer;
        bool notRendered = true;

        bool gotHit = false;
        int hitX = 0;
        int hitY = 0;
        MouseState oldMouseState = new MouseState();

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

        protected override void Initialize()
        {
            IsMouseVisible = true;

            base.Initialize();
        }

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

            target = new Texture2D(GraphicsDevice, 128, 128);
            projectile = new Texture2D(GraphicsDevice, 64, 64);

            Color[] tArray = new Color[128 * 128];
            for (int i = 0; i < 128 * 128; i++)
                if (random.NextDouble() > 0.5d)
                    tArray[i] = Color.White;
                else tArray[i] = Color.Transparent;
            target.SetData<Color>(tArray);

            Color[] pArray = new Color[64 * 64];
            for (int i = 0; i < 64 * 64; i++)
                pArray[i] = Color.FromNonPremultiplied(255, 0, 0, 70);
            projectile.SetData<Color>(pArray);

            layer = new RenderTarget2D(GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.PreserveContents);
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            MouseState mState = Mouse.GetState();
            if (mState.LeftButton == ButtonState.Pressed)// && oldMouseState.LeftButton == ButtonState.Released)
            {
                hitX = mState.X - 32;
                hitY = mState.Y - 32;
                gotHit = true;
            }

            oldMouseState = mState;
            base.Update(gameTime);
        }

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

            if (notRendered)
            {
                var m = Matrix.CreateOrthographicOffCenter(0, graphics.GraphicsDevice.PresentationParameters.BackBufferWidth, graphics.GraphicsDevice.PresentationParameters.BackBufferHeight, 0, 0, 1);

                var a = new AlphaTestEffect(graphics.GraphicsDevice)
                {
                    Projection = m
                };

                var s1 = new DepthStencilState
                {
                    StencilEnable = true,
                    StencilFunction = CompareFunction.Always,
                    StencilPass = StencilOperation.Replace,
                    ReferenceStencil = 1,
                    DepthBufferEnable = false,
                };

                GraphicsDevice.SetRenderTarget(layer);
                GraphicsDevice.Clear(Color.Transparent);
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, s1, null, a);
                spriteBatch.Draw(target, new Vector2(20, 20), Color.White);
                spriteBatch.End();

                GraphicsDevice.SetRenderTarget(null);
                notRendered = false;
            }

            if (gotHit)
            {
                var m = Matrix.CreateOrthographicOffCenter(0, graphics.GraphicsDevice.PresentationParameters.BackBufferWidth, graphics.GraphicsDevice.PresentationParameters.BackBufferHeight, 0, 0, 1);

                var a = new AlphaTestEffect(graphics.GraphicsDevice)
                {
                    Projection = m
                };

                var s2 = new DepthStencilState
                {
                    StencilEnable = true,
                    StencilFunction = CompareFunction.LessEqual,
                    StencilPass = StencilOperation.Keep,
                    ReferenceStencil = 1,
                    DepthBufferEnable = false,
                };

                GraphicsDevice.SetRenderTarget(layer);
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, s2, null, a);
                spriteBatch.Draw(projectile, new Vector2(hitX, hitY), Color.White);
                spriteBatch.End();

                GraphicsDevice.SetRenderTarget(null);
                gotHit = false;
            }
            spriteBatch.Begin();
            spriteBatch.Draw(layer, Vector2.Zero, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

*gotHit* will be true whenever I need to draw to the render target, which is when the player presses the mouse. The problem exists whenever *gotHit* is true.

Edit: It occurred to me that should anybody run the code, it probably wouldn't make much sense. The window's background is set to a dark blue to make things more visible. Upon clicking (or dragging) on the speckled section, a red square is drawn to the render target at that position. It is masked such that it will only affect the white pixels. This works, but during this action the background will become black. From what I can tell, the render target (which is the size of the window) is losing its transparency for frames where it is being modified.

The red square is actually semi-transparent as in the target application it will be this way. It's not a symptom of the issue and doesn't affect the outcome when modified.

# Answer
This seems to give the effect you're looking for. Only moved some code around a bit.

```
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace StencilTest
{
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Texture2D target;
    Texture2D projectile;
    Random random = new Random();

    RenderTarget2D layer;
    bool notRendered = true;

    bool gotHit = false;
    int hitX = 0;
    int hitY = 0;
    MouseState oldMouseState = new MouseState();

    Matrix m;
    AlphaTestEffect a;
    DepthStencilState s1;
    DepthStencilState s2;

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

    protected override void Initialize()
    {
        IsMouseVisible = true;

        base.Initialize();
    }

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

        target = new Texture2D(GraphicsDevice, 128, 128);
        projectile = new Texture2D(GraphicsDevice, 64, 64);

        Color[] tArray = new Color[128 * 128];
        for (int i = 0; i < 128 * 128; i++)
            if (random.NextDouble() > 0.5d)
                tArray[i] = Color.White;
            else tArray[i] = Color.Transparent;
        target.SetData<Color>(tArray);

        Color[] pArray = new Color[64 * 64];
        for (int i = 0; i < 64 * 64; i++)
            pArray[i] = Color.FromNonPremultiplied(255, 0, 0, 70);
        projectile.SetData<Color>(pArray);

        layer = new RenderTarget2D(GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.PreserveContents);

        //initialize the matrix, alpha effect and depthstencil, so you won't need it every draw call.
        m = Matrix.CreateOrthographicOffCenter(0, graphics.GraphicsDevice.PresentationParameters.BackBufferWidth, graphics.GraphicsDevice.PresentationParameters.BackBufferHeight, 0, 0, 1);

        a = new AlphaTestEffect(graphics.GraphicsDevice)
        {
            Projection = m
        };

        s1 = new DepthStencilState
        {
            StencilEnable = true,
            StencilFunction = CompareFunction.Always,
            StencilPass = StencilOperation.Replace,
            ReferenceStencil = 1,
            DepthBufferEnable = false,
        };

        s2 = new DepthStencilState
        {
            StencilEnable = true,
            StencilFunction = CompareFunction.LessEqual,
            StencilPass = StencilOperation.Keep,
            ReferenceStencil = 1,
            DepthBufferEnable = false,
        };

    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        MouseState mState = Mouse.GetState();
        if (mState.LeftButton == ButtonState.Pressed)// && oldMouseState.LeftButton == ButtonState.Released)
        {
            hitX = mState.X - 32;
            hitY = mState.Y - 32;
            gotHit = true;
        }

        oldMouseState = mState;
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {

        if (notRendered)
        {

            GraphicsDevice.SetRenderTarget(layer);
            GraphicsDevice.Clear(Color.Transparent);
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, s1, null, a);
            spriteBatch.Draw(target, new Vector2(20, 20), Color.White);
            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);
            notRendered = false;
        }

        if (gotHit)
        {

            GraphicsDevice.SetRenderTarget(layer);
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, s2, null, a);
            spriteBatch.Draw(projectile, new Vector2(hitX, hitY), Color.White);
            spriteBatch.End();

            gotHit = false;
        }

        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Color.DarkBlue); // moved this downwards!

        spriteBatch.Begin();
        spriteBatch.Draw(layer, Vector2.Zero, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

}

The thing is you need to move the `GraphicsDevice.Clear` statement after the `SetRenderTarget(null)`. So there is a `prerender`-\>`clear`-\>`render` sequence. Your stencil operation should happen during the prerender phase. This was introduced to align graphic operations with the XBox architecture.

(note: during some testing I moved the a,n,s1,s2 variables out of the draw loop)
> 0 votes

# Answer
I think you need to set the RenderTargetUsage to PreserveContent, if you are not clearing it when modifying.
> 0 votes

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


# Question
Title: Camera rotation according to target direction
I am facing issue when camera is following to my target and target rotates to 90 degree or -90 degree than camera is not rotating.i want smooth rotation according to target when target is change the direction of movement.please help me if you can..thanks in advance.

# Answer
Make your Camera a child of your Player game object by dragging it onto the Player in the Hierarchy window. The camera will then keep its relative position to the player. When the player object rotates, the camera will rotate with it.

Possible problem: When the rotation of the player is not smooth, the rotation of the camera won't be smooth either. When this is a problem in your case, you need to solve it differently. Keep the Camera as an independent game object, but add a script to the Camera with an Update method which checks the transform of the player and changes the transform of the camera accordingly. How to do this in detail depends on your defintition of "smooth rotation" and "smooth following".
> 0 votes

---
Tags: unity, camera, rotation
---


title: Adjust postion only in X axis

text:
# Question
Title: Adjust postion only in X axis
I have two game objects named `A` and `B`, just as follows:

I want to move object `B` to this virtual line without any rotation so that the destination is `B'` . What I have are transformation of object `A` and `B`. I'm brand new to Unity3D and its APIs, so I don't know how should I get this done.

# Answer
The simplest and non mathematical (noob) way to do this is to make Game object B a child of Game object A , then make local position x as zero and remove B from the parent A.

```
B.transform.parent = A.transform;
B.transform.localPosition = new Vector3 (0, B.transform.localPosition.y, B.transform.localPosition.z);
B.transform.parent = null;

```
> 3 votes

---
Tags: unity, transformation, linear-algebra
---


# Question
Title: UE4: Subclass problem: cannot access private member declared in parent class?
I get the following error:

```
  [...]\ClassB.cpp:7: erreur : C2248: 'UClassA::UClassA' : cannot access private member declared in class 'UClassA'
  [...]\ClassA.h:12: see declaration of 'AClassA::AClassA'
  [...]\ClassA.h:9: see declaration of 'AClassA'

```

when I create a subsubclass.

The problem occurs with the following code:

ClassA.h

```
#pragma once

#include "GameFramework/Actor.h"
#include "ClassA.generated.h"

UCLASS()
class PROBUILDER_API AClassA : public AActor
{
    GENERATED_BODY()
    AClassA( const FObjectInitializer& ObjectInitializer );

};

```

ClassA.cpp

```
#include "ProBuilder.h"
#include "ClassA.h"

AClassA::AClassA(const FObjectInitializer &ObjectInitializer):Super(ObjectInitializer)
{

}

```

ClassB.h

```
#pragma once

#include "ClassA.h"
#include "ClassB.generated.h"

UCLASS()
class PROBUILDER_API AClassB : public AClassA
{
    GENERATED_BODY()
    AClassB( const FObjectInitializer& ObjectInitializer );

};

```

ClassB.cpp

```
#include "ProBuilder.h"
#include "ClassB.h"

AClassB::AClassB(const FObjectInitializer &ObjectInitializer):Super(ObjectInitializer)
{

}

```

(I tried with a subclass of AActor and UMeshComponent and got the same errors)

# Answer
> 0 votes
I just forgot to set my constructor to public.

---
Tags: c++, unreal-4
---


title: Modularization in a project

text:
# Question
Title: Modularization in a project
I'm writing a C# game in Mono, and I want the game to be as modular as possible.
I've started by writing the whole Item (inventory) System of the game in a seperate .dll library
But I've hit a problem. I want Items to have effects, so I've written a base Interface for this:

```
interface IBehavior
{
    bool ApplyBehavior(Player destinationPlayer);
}

```

I'm following guidelines from the answer on this post regarding the (Unit, Effect, Behavior, Ability \[Lets call it UEBA\]) structure. Problem is that Player is a class from like the main module in the game so I assume this breaks modularity in the code.
What would be the best solution to fix this conflict?
I'm considering writing another, separate module, of UBEA, that will use Player and then the Item System module will use that module instead of the main module, and then the UBEA module will break modularity.
Should I also move Player to another module?
Am I even able to create full modularity if this is the model of things I want to create?

Thanks for the answers!

# Answer
> 1 votes
You could introduce the interface IUnit (if you don't already have it). Place it in the Item-Lib or even in a third lib which is referenced by your main/item/../module then just implement the IUnit interface in your Player class.

```
interface IBehavior
{
    bool ApplyBehavior(IUnit destinationPlayer);
}

```

---
Tags: c#, monogame, software-engineering
---


# Question
Title: Loading different navmeshes at runtime in Unity 5
In order to improve the extend ability of our maps, we load different components of the map at run time. The idea is a user can use Unity to make a map, drop it into a folder and it will be loaded.

The problem I'm facing is loading in navmeshes at run time. Before Unity 5, it was possible to give a scene a navmesh using Resources.Load and then NavMesh.Instantiate. NavMesh.Instantiate is now gone for whatever reason, and nothing seems to replace it.

Now when trying to use Object.Instantiate with a navmesh asset and instantiating an agent, I get the error "Failed to create agent because there is no valid NavMesh". Is there any known way to set a navmesh at run time anymore?

# Answer
> 1 votes
If you want to load navmeshes baked with different settings you can not load it additively. What you can do is bake twice in a different scene (resulting in three scenes) then delete the geometry from the scenes containing the navmeshes and load like this:

```
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    bool _navMesh1Loaded;
    bool _navMesh2Loaded;

    void OnGUI()
    {
        if (GUILayout.Button("Load NavMesh 1"))
        {
            if (_navMesh2Loaded)
                Application.UnloadLevel(2);
            Application.LoadLevelAdditive(1);
            _navMesh1Loaded = true;
        }
        if (GUILayout.Button("Load NavMesh 2"))
        {
            if (_navMesh1Loaded)
                Application.UnloadLevel(1);
            Application.LoadLevelAdditive(2);
            _navMesh2Loaded = true;
        }

    }
}

```

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


# Question
Title: How can I render 3D frames quickly using VB?
I want to make a simple 3D engine using vb. It must be fast at creating frames obviously for a 3d game. So this code i have draws a frame at 4 fps

```
Dim SM = DateTime.Now.Millisecond
    Dim ETDFrame As New Bitmap(600, 600)
    Dim ETDGraphics As Graphics = Graphics.FromImage(ETDFrame)
    Dim DFrame As New PictureBox
    Dim x = 0
    Do Until x = 600
        Dim y = 0
        Do Until y = 600
            ETDFrame.SetPixel(x, y, Color.Black)
            y += 1
        Loop
        x += 1
    Loop
    DFrame.Image = ETDFrame
    DFrame.Size = New Size(600, 600)
    DFrame.Location = New Point(0, 0)
    DFrame.Visible = True
    Controls.Add(DFrame)
    Dim EM = DateTime.Now.Millisecond
    Dim FM = EM - SM
    If FM < 0 Then
        FM += 1000
    End If
    Dim fps As Integer = 1000 / FM
    MsgBox(fps)

```

This code draws a frame at 333 to 500 fps but it is a solid color.

```
Dim SM = DateTime.Now.Millisecond
    Dim ETDFrame As New Bitmap(600, 600)
    Dim ETDGraphics As Graphics = Graphics.FromImage(ETDFrame)
    Dim DFrame As New PictureBox
    ETDGraphics.FillRectangle(Brushes.Red, 0, 0, 600, 600)
    DFrame.Image = ETDFrame
    DFrame.Size = New Size(600, 600)
    DFrame.Location = New Point(0, 0)
    DFrame.Visible = True
    Controls.Add(DFrame)
    Dim EM = DateTime.Now.Millisecond
    Dim FM = EM - SM
    If FM < 0 Then
        FM += 1000
    End If
    Dim fps As Integer = 1000 / FM
    MsgBox(fps)

```

All i know is that something is setting all the pixels to black in this bitmap very fast, but doing it yourself is really slow i was wondering is there a different way to do it with just vb or if a need to download something like DirectX SDK?

# Answer
GDI+ is not the best way to go for this kind of thing. The issue with SetPixel is it locks and unlocks the image each loop.

Read up on using LockBits (There is a lot of info on the web about it).

Here is your code with a little adjustment for example.

```
        Dim SM = DateTime.Now.Millisecond
        Dim ETDFrame As New Bitmap(600, 600)

        Dim b As Imaging.BitmapData = ETDFrame.LockBits(New Rectangle(0, 0, ETDFrame.Width, ETDFrame.Height), Imaging.ImageLockMode.WriteOnly, Imaging.PixelFormat.Format24bppRgb)

        Dim ptr As IntPtr = b.Scan0

        Dim bytes As Integer = Math.Abs(b.Stride) * ETDFrame.Height
        Dim rgbValues(bytes - 1) As Byte

        Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)
        For counter As Integer = 0 To rgbValues.Length - 1 Step 3
            rgbValues(counter) = 255     'Blue
            rgbValues(counter + 1) = 255 'Green
            rgbValues(counter + 2) = 255 'Red
        Next

        System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes)

        ETDFrame.UnlockBits(b)

        Dim DFrame As New PictureBox

        DFrame.Image = ETDFrame
        DFrame.Size = New Size(600, 600)
        DFrame.Location = New Point(0, 0)
        DFrame.Visible = True
        Controls.Add(DFrame)
        Dim EM = DateTime.Now.Millisecond
        Dim FM = EM - SM
        If FM < 0 Then
            FM += 1000
        End If
        Dim fps As Integer = 1000 / FM
        MsgBox(fps)

```

For more speed you could skip the marshal and do it unsafe.
> 1 votes

---
Tags: 3d, vb.net
---


# Question
Title: MovieTexture error with augmented reality
Unity says, the following error, is this because I'm using a free Unity instead of pro ?

The type or namespace name \`MovieTexture' could not be found. Are you missing a using directive or an assembly reference?

tutorial what I followed: https://www.youtube.com/watch?v=YBc3ubr18ks

# Answer
If you building your game for mobile, Unity does not support MovieTexture for mobile platforms by default. By the way, there are several assets on the Store, not free though.
> 1 votes

---
Tags: unity, augmented-reality
---


title: How to manage special state in mecanim?

text:
# Question
Title: How to manage special state in mecanim?
I have a game in which there is a cat that has three states: On Ground, Going Up and Coming down.

This is handled by having 3 states, up,ground and down. Now, there is an additional requirement that the cat picks up a power up and becomes invincible. In this special state, the cat doesn't die if it falls through gaps etc. In this state also, there are same animation states : up, ground and down. However, when the cat is in this special state, it's sprite changes to a starry,shiny sprite.

So now we have two sets of animations : one normal, another power up. How can I manage these two sets?

# Answer
> 1 votes
You might also like to have a look into Animator's Layers.

They allow you to configure and blend several state machines based on the parameters you define (like the ones Exerion says). Giving the right weight and blending type could be easier than complicating the original animation state machine you already have.

# Answer
> 1 votes
You can add new boolean `PoweredUp` to mecanim, and set a new duplicate group of states upPowered, groundPowered and downPowered. Make transition between corresponding states, i.e ground -\> groundPowered, and use boolean PoweredUp as a condition for transition back and forth. Transitions between powered-up states can use the same triggers as non-powered.

---
Tags: unity
---


# Question
Title: Objects with custom shaders cast grayscale shadows when lightmapped
Unity 5 seems to be able to calculate colored shadows from objects mapped with standart shader and legacy shaders.

What should I do to make my custom shader to cast colored shadows as well?

# Answer
The solution is to add `UsePass "Mobile/Diffuse/META"` to all LODs of lightmapped shaders.

Here is fixed version of my shader:

```
Shader "Opaque/Lightmap"
{
Properties
{
    _MainTex ("Base (RGB)", 2D)     = "white" {}
}

SubShader
{
    Tags { "Queue" = "Geometry" "RenderType" = "Opaque"}
    LOD 100

    Pass
    {
        Name "FORWARD"
        Tags { "LIGHTMODE"="ForwardBase" "SHADOWSUPPORT"="false" "RenderType"="Opaque" }

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma fragmentoption ARB_precision_hint_fastest
        #pragma exclude_renderers d3d11_9x d3d11
        #pragma multi_compile_fog
        #pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON

        #include "UnityCG.cginc"

        sampler2D   _MainTex;

        struct appdata
        {
            float4 vertex : POSITION;
            half2 texcoord   : TEXCOORD0;
            half2 texcoord1  : TEXCOORD1;
        };

        struct v2f {
            float4 pos : SV_POSITION;
            half2 uv : TEXCOORD0;
            half2 lightmapuv : TEXCOORD1;
            UNITY_FOG_COORDS(2)
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.pos = mul( UNITY_MATRIX_MVP, v.vertex );
            o.uv = v.texcoord;
            o.lightmapuv = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw;

            UNITY_TRANSFER_FOG(o,o.pos);
            return o;
        }

        fixed4 frag (v2f i) : COLOR
        {
            fixed4 color = tex2D(_MainTex, i.uv);

            #ifndef LIGHTMAP_OFF
            fixed3 lightMap = DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, i.lightmapuv));
            color.rgb *= lightMap;
            #endif

            UNITY_APPLY_FOG(i.fogCoord, color);
            return color;
        }
        ENDCG
    }

    // to fix diffuse component bounce in the lightmaps
    UsePass "Mobile/Diffuse/META"
}
}

```

Thanks to Michael Steliaros for help.
> 0 votes

---
Tags: unity
---


# Question
Title: How to get plausible platformer physics with Farseer on MonoGame/XNA?
I am creating a 2D Vectorial (made of polygons, not tiles !) platformer using MonoGame and Farseer Physics Engine. Everything works perfectly, except the movement of the character which doesn't feels right for a platformer, because Farseer is a physics engine... I would like to have any advice to achieve a natural feeling -like Mario-. I didn't choose to make my own system because I'm simply not good enough to do something like this.

I've seen some questions already about it, but none had useful answers (they said like 'You have to do a lot of tweaking', but how do I do that exactly ?)

I could eventually use another engine that works for collision detection/response and that gives me more control over the player/entities, but i didn't find any yet. If you know any solution that's simple to use and that corresponds to what I need, then i'd love to hear it :)

Thank you for any help.

PS: Also, I am soon going to try to create AIs for my game. How would I make them move with great control (like the player) ?

# Answer
> 1 votes
I would control it all myself if I were you. Start with a float and a vector2 and from there create the 2D physics yourself.

```
vector2 pos = (100, 100)
float jump = 0; //this is the vertical momentum
protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        if(Gamepad.GetState().IsKeyDown(Keys.Space))
        {
            jump = -10; //upwards jump of 10
        }
        pos.Y += jump;

        base.Update(gameTime);
    }

```

Now just draw the sprite at `pos`.

---
Tags: physics, monogame, platformer
---


# Question
Title: Best practice to implement persistent data when using Tiled TMX map files?
A friend of mine and I are always talking about our current progress in learning game development. Recently, saving the game (data persistence) came up, and when I summarized how I tackled that for my project, he thought I should post a question here and see if anyone else had input on the scenario.

A little bit of background: I'm working on a top down 2d rpg and experimenting with different gameplay concepts here and there. I am using **cocos2d** for **Python**, and may eventually move to **Kivy**. Most importantly for the save portion, I'm using **Tiled** **TMX** files for my maps / levels, and **sqlalchemy**.

So, I wanted all the different objects in each map to maintain their states and positions when the player leaves the map, and when the players come back, everything is at or near where he left off...unless a great deal of time has passed or something. Now, I hadn't considered at all what to do to allow this at first. ...Another friend of mine decided to just 'pickle' his map objects to a file. I tried to do this but ran into a lot of problems – I was attempting to pickle an entire sprite entity instead of just the data bits, so I ran into issues of threading... it was a mess.

Then I went with a sqlite db for storing all the various data. The reason I had this trouble at all is because a tmx map file is just xml underneath – and I wouldn't want to have to make copies of the original map files and then commit the map objects' locations back to a separate xml file – that sounded messy.

My final plan was to create a tmx map object to db map object converter. The logic is, if the player hasn't been to this map yet, initialize the objects from tmx to the db, and mirror all their properties and value pairs as well... then get the actual map from tmx xml as usual, then load map objects from the db. On map exit, commit all the map objects back to db.

TL;DR: what would have been a better way to store persistent map object data if I'm using Tiled TMX maps? Was doing a db overkill? What's an example of best practice for map save data like this, where you want the objects on the map to remain as they were when you were last on the map?

Thanks, I hope that's clear enough!

**Edit**:

Here's the objectgroup of a tmx file I'm using

```
<objectgroup name="objects" width="30" height="30">
    <object name="Entrance1" type="start" x="159" y="326" width="32" height="32">
       <properties>
           <property name="start_name" value="Entrance1"/>
       </properties>
    </object>
    <object name="To hello1" type="portal" x="160" y="256" width="32" height="64">
       <properties>
          <property name="map_name" value="hello.tmx"/>
          <property name="portal_name" value="Entrance2"/>
       </properties>
    </object>
    <object name="Item1" type="item" x="480" y="288" width="29" height="30">
        <properties>
            <property name="image" value="ironbarstack.png"/>
            <property name="item" value="ironbar"/>
            <property name="quantity" value="3"/>
            <property name="requirements" value="0"/>
        </properties>
    </object>
    <object name="Item2" type="item" x="449" y="351" width="29" height="30">
        <properties>
            <property name="image" value="rope.png"/>
            <property name="item" value="rope"/>
            <property name="quantity" value="1"/>
            <property name="requirements" value="0"/>
        </properties>
    </object>
</objectgroup>

```

If I'm working on a level in Tiled (adding another item on the floor for instance) and then playtesting it, I need to check for updates each time I load up the map right now. So, I check to see if that tmx map name exists in the maps table of the save game db being used. If it exists, create a list of tmx objects and db objects, and iterate through the tmx objects, update/add the db counterparts with the key being their name value. Then, at the end if there are any db objects remaining from the db object list, remove them from the db. If the map doesn't exist in the db yet, then it's a straight conversion from tmx object to db object, no checks done.

At first when I went the db route, I *was* storing each *type* of map object in its own table with properties I expected to be required for each. That proved difficult, time consuming and rather unnecessary. I ended up just doing a one to one conversion from tmx map to db map, tmx object to db object, and tmx object properties to db object properties.

After the game content is completed, I plan on removing all of the tmx files and these sync checks, and just having a master db that the game content is copied from. As a bonus question, does this make sense, or am I making a lot of work by attempting to avoid the building of a proprietary map editor by using Tiled?

# Answer
TMX Files are basically a XML file describing your map/level; You usually read it to initialize your world and forget about it.

Now, if the lib you use to manipulate/display them (or your own code if you did it by hand) is able to regenerate the TMX from your world after the player interactions modified it I'd say the way to go is to just serialize the new TMX, either in a file or in a DB's TEXT field.

It can seem a little overkill, but it has a few advantages:

* No need to change your code if you redesign your levels
* It can handle totally or partially procedural worlds (let say a part of your TMX is a labyrinth which changes every time a player starts a new game, or some bonus/resources are randomly placed depending of things like the xp/score of the player when he enters the level, or anything you can think of, when the player continue his game after saving, everything will be in place
* Your DB schema/file format won't have to change if you add a new kind of object/actor to your game

Of course, you may also save a few extra data just to make the player game easier (total time played when the save was performed, thumbnail image of current screen, etc...).

(and you probably don't need to save the actual tileset images (unless you change them dynamically but I didn't seen any game doing this yet)).

Bottom line: It will not be the most "optimized" way, but it will be the most flexible and easy to maintain way (this means less bug, and the kind of bugs players hate the most is the one that lost their progress after saving/reloading a game).

**EDIT: The Bonus question:**

> As a bonus question, does this make sense, or am I making a lot of work by attempting to avoid the building of a proprietary map editor by using Tiled?

Well, developing a very crude level editor from scratch would take you at least a couple of weeks, and the result would be a lot less productive than using Tiled.

If you really want to get rid of TMX files (that's something I do most of the time), you can write a script which convert a TMX file into whatever format you'll be using (in your case, the script could output a list of SQL's INSERT statements that will add the new level to your DB).

This way, you can have the better of the two worlds (Great tilemap editor to design your levels (Tiled) and the data structure you want for your game).

If you're using some kind of Makefile, you can even treat your TMX files as source files (this way, whenever you want to change a level, you just have to save the file and rebuild your game (or at least the DB in your case; you may use a specific build target for the DB so the game itself won't have to be recompiled everytime you edit a level)).
> 1 votes

# Answer
This is an excellant question, I am developing an app for Android using AS3, Flash Builder and Tiled for the maps. I am running into complications with the shear amount of data taken up by the tmx files. Ive cut down a bit of the memory usage by creting bitmaps of the ground tiles and any canopy tiles, instead of parsing those. However when I load the map information they are still present. I am thinking I might develop a script which would convert my collision object layer and the interaction layer into sql information.

Now as per your initial question this is how I deal with persistance between objects and players. Lets take my chest object for example, this object gets instantiated each time there is a chest present in a map. At creation the chest will take on the stats of the chest from the tmx file. When the player travels to the map and therefore the chest has been added to the stage, I have the chest search for an element in my event array and return the data, which in my case is a secondary array that defines its locked and empty status. Ie. Game\_Events\[mapID\]\[chestID\] = new array(isLocked, isEmpty).

When the chest gets unlocked and opened (or opened if it exists as unlocked), then I will update my sqlite db to reflect the mapID, chestID and locked and emptied status.

I find this works the best and is the easiest method.
> 1 votes

---
Tags: tilemap, python, data, sql
---


# Question
Title: Unity3d. Overlay of clothes on a human model
I have:

* Clothes model (jackets, shirts, sweater etc. with various sizes,colors)
* Human model with dynamic height, width, position

Need overlay the clothes' model onto a human model.

Variant with a skeleton and skin is not suitable because of different clothing options and there will be a lot of variations of the model.

Need a mathematical combination of the inside of the clothes model with the surface model of the human. Can anyone help?

# Answer
I think this question is WAY outside the realm of an SE question (as far as getting code to do what you want) - This in not something easily done. You may be able to find something on the asset store that will calculate this for you - but in most professional game there would be a different clothing model for each character model.

What you probably want to look into is UMA: https://www.assetstore.unity3d.com/en/#!/content/13930

You will need to adjust your code to fit - and probably make some changes to your models - but overall it will probably do what you are wanting and more... Plus it's free!
> 1 votes

# Answer
Check out the Character Customization example project. You'll find it under Unity Technologies in the Asset Store. You'll need to merge the meshes into one at runtime so that your model only takes up one draw call.
> 0 votes

# Answer
You could create animation in blender 3d and use the gravity mode on your clothes. then import it to your game.
> 0 votes

---
Tags: unity, graphics, overlay, cloth
---


# Question
Title: How to design context menus based on whatever the object is?
I'm looking for a solution for a "Right Click Options" behaviour.

Basically any and every item in a game, when right clicked, can display a set of options based on whatever the object is.

**Right click examples for different scenarios**:

***Inventory:*** Helmet shows options (Equip, Use, Drop, Description)

***Bank:*** Helmet shows options (Take 1, Take X, Take All, Description)

***Floor:*** Helmet shows options (Take, Walk Here, Description)

Obviously each option somehow points to a certain method that does what is says. This is part of the issue I'm trying to figure out. With so many potention options for a single item, how would I have my classes designed in such a way as to not be extremely messy?

* I've thought about inheritance but that could be really long winded and the chain could be huge.
* I've thought about using interfaces, but this would probably restrict me a little as I wouldn't be able to load item data from an Xml file and place it into a generic "Item" class.

I'm basing my desired end result on a game called Runescape. Every object can be right clicked in the game and depending on what it is, and where it is (inventory, floor, bank etc.) displays a different set of options available to the player to interact with.

How would I go about achieving this? What approach should I take to first of all, decide which options SHOULD be displayed and once clicked, how to call the corresponding method.

I am using C# and Unity3D, but any examples provided do not have to be related to either of them as I'm after a pattern as opposed to actual code.

Any help is much appreciated and if I have not been clear in my question or desired results, please post a comment and I'll tend to it ASAP.

**Here is what I have tried so far:**

* I've actually managed to implement a generic "Item" class that holds all of the values for different types of items (extra attack, extra defence, cost etc...). These variables get populated by data from an Xml file.
* I have thought about placing every single possible interaction method inside of the Item class but I think this is unbelievably messy and poor form. I've probably taken the wrong approach for implementing this kind of system by only using the one class and not sub-classing to different items, but its the only way I can load the data from an Xml and store it in the class.
* The reason I've chose to load all my items from an Xml file is due to this game having the possibility for 40,000+ items. If my math is correct, a class for each item is a lot of classes.

# Answer
As with everything in software development, there is no ideal solution. Only the solution which is ideal for you and your project. Here are some you could use.

## Option 1: The procedural model

The ancient obsolete old-school method.

All items are dumb plain-old-data types without any methods but lots of public attributes which represent all properties an item could have, including some boolean flags like `isEdible`, `isEquipable` etc. which determine what context menu entries are available for it (maybe you could also do without these flags when you can derive it from the values of other attributes). Have some methods like `Eat`, `Equip` etc. in your player class which takes an item and which has all the logic to process it according to the attribute values.

# Option 2: The object-oriented model

This is more of a OOP-by-the-book solution which is based on inheritance and polymorphism.

Have a base-class `Item` from which other items like `EdibleItem`, `EquipableItem` etc. inherit. The base class should have a public method `GetContextMenuEntriesForBank`, `GetContextMenuEntriesForFloor` etc. which return a list of `ContextMenuEntry`. Each inheriting class would override these methods to return the context menu entries which are appropriate for this item type. It could also call the same method of the base class to get some default entries which are applicable for any item type. The `ContextMenuEntry` would be a class with a method `Perform` which then calls the relevant method from the Item which created it (you could use a delegate for this).

Regarding your problems with implementing this pattern when reading data from the XML file: First examine the XML node for each item to determine the type of item, then use specialized code for each type to create an instance of the appropriate sub-class.

# Option 3: The component-based model

This pattern uses composition instead of inheritance and is closer to how the rest of Unity works. Depending on how you structure your game it might be possible/beneficial to use the Unity component system for this... or not, your mileage may vary.

Each object of class `Item` would have a list of components like `Equipable`, `Edible`, `Sellable`, `Drinkable`, etc. An item can have one or none of each component (for example, a helmet made of chocolate would be both `Equipable` and `Edible`, and when it is not a plot-critical quest item also `Sellable`). The programming logic which is specific to the component is implemented in that component. When the user right-clicks on an item, the components of the item are iterated and context-menu entries are added for each component which exists. When the user selects one of these entries, the component which added that entry processes the option.

You could represent this in your XML-file by having a sub-node for each component. Example:

```
   <item>
      <name>Chocolate Helmet</name>
      <sprite>helmet-chocolate.png</sprite>
      <description>Protects you from enemies and from starving</description>
      <edible>
          <taste>sweet</taste>
          <calories>2560</calories>
      </edible>
      <equipable>
          <slot>head</slot>
          <def>20</def>
      </equipable>
      <sellable>
          <value>120</value>
      </sellable>
   </item>

```
> 23 votes

# Answer
So, Mike Hunt, your question so interested me, I decided to implement a full solution. After three hours of trying different things, I ended up with this step-by-step solution:

(Please note, that this IS NOT very good code, so I will accept any edits)

## Creating Content Panel

(This panel will be a container for our context-menu buttons)

* Create new `UI Panel`
* Set `anchor` to bottom-left
* Set `width` to 300 (as you wish)
* Add to a panel a new component `Vertical Layout Group` and set `Child Alignment` to upper-center, `Child Force Expand` to width (not height)
* Add to a panel a new component `Content Size Fitter` and set `Vertical Fit` to Min Size
* Save it as prefab

(At this point our Panel will shrink down to a line. It's normal. This panel will accept buttons as children, align them vertically and stretch to summary content height)

## Creating Sample Button

(This button will be instantiated and customized to show context-menu items)

* Create new UI Button
* Set `anchor` to top-left
* Add to a button a new component `Layout Element`, set `Min Height` to 30, `Preferred Height` to 30
* Save it as prefab

## Creating ContextMenu.cs script

(This script has a method that creates and shows Context Menu)

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[System.Serializable]
public class ContextMenuItem
{
    // this class - just a box to some data

    public string text;             // text to display on button
    public Button button;           // sample button prefab
    public Action<Image> action;    // delegate to method that needs to be executed when button is clicked

    public ContextMenuItem(string text, Button button, Action<Image> action)
    {
        this.text = text;
        this.button = button;
        this.action = action;
    }
}

public class ContextMenu : MonoBehaviour
{
    public Image contentPanel;              // content panel prefab
    public Canvas canvas;                   // link to main canvas, where will be Context Menu

    private static ContextMenu instance;    // some kind of singleton here

    public static ContextMenu Instance
    {
        get
        {
            if(instance == null)
            {
                instance = FindObjectOfType(typeof(ContextMenu)) as ContextMenu;
                if(instance == null)
                {
                    instance = new ContextMenu();
                }
            }
            return instance;
        }
    }

    public void CreateContextMenu(List<ContextMenuItem> items, Vector2 position)
    {
        // here we are creating and displaying Context Menu

        Image panel = Instantiate(contentPanel, new Vector3(position.x, position.y, 0), Quaternion.identity) as Image;
        panel.transform.SetParent(canvas.transform);
        panel.transform.SetAsLastSibling();
        panel.rectTransform.anchoredPosition = position;

        foreach(var item in items)
        {
            ContextMenuItem tempReference = item;
            Button button = Instantiate(item.button) as Button;
            Text buttonText = button.GetComponentInChildren(typeof(Text)) as Text;
            buttonText.text = item.text;
            button.onClick.AddListener(delegate { tempReference.action(panel); });
            button.transform.SetParent(panel.transform);
        }
    }
}

```
* Attach this script to a Canvas and populate fields. Drag-n-drop `ContentPanel` prefab to corresponding slot, and drag Canvas itself to slot `Canvas`.

## Creating ItemController.cs script

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ItemController : MonoBehaviour
{
    public Button sampleButton;                         // sample button prefab
    private List<ContextMenuItem> contextMenuItems;     // list of items in menu

    void Awake()
    {
        // Here we are creating and populating our future Context Menu.
        // I do it in Awake once, but as you can see,
        // it can be edited at runtime anywhere and anytime.

        contextMenuItems = new List<ContextMenuItem>();
        Action<Image> equip = new Action<Image>(EquipAction);
        Action<Image> use = new Action<Image>(UseAction);
        Action<Image> drop = new Action<Image>(DropAction);

        contextMenuItems.Add(new ContextMenuItem("Equip", sampleButton, equip));
        contextMenuItems.Add(new ContextMenuItem("Use", sampleButton, use));
        contextMenuItems.Add(new ContextMenuItem("Drop", sampleButton, drop));
    }

    void OnMouseOver()
    {
        if(Input.GetMouseButtonDown(1))
        {
            Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
            ContextMenu.Instance.CreateContextMenu(contextMenuItems, new Vector2(pos.x, pos.y));
        }

    }

    void EquipAction(Image contextPanel)
    {
        Debug.Log("Equipped");
        Destroy(contextPanel.gameObject);
    }

    void UseAction(Image contextPanel)
    {
        Debug.Log("Used");
        Destroy(contextPanel.gameObject);
    }

    void DropAction(Image contextPanel)
    {
        Debug.Log("Dropped");
        Destroy(contextPanel.gameObject);
    }
}

```
* Create sample object in the scene (i.e `Cube`), place it to be visible to camera and attach this script to it. Drag-n-drop `sampleButton` prefab to corresponding slot.

Now, try to run it. When you're right-clicking the object, the context menu should appear, populated with list that we made. Pressing buttons will print into the console some text, and the context menu will be destroyed.

***Possible improvements:***

* even more generic!
* better memory management (dirty links, not destroying panel, disabling)
* some fancy stuff

***Sample project*** (Unity Personal 5.2.0, VisualStudio Plugin): https://drive.google.com/file/d/0B7iGjyVbWvFwUnRQRVVaOGdDc2M/view?usp=sharing
> 11 votes

---
Tags: unity, c#, game-mechanics, design-patterns
---


# Question
Title: Getting a Specific Component in an Entity Component System
I've got component class:

```
class Component
{
public:
    Component();
    ...
};

```

then my various components derive from the base `Component` class

```
class VelocityCom : public Component
{
public:
    VelocityCom();
    ...
};

```

and then an entity class that holds the components and is able to return a specific component for manipulation

```
class Entity
{
public:
    Entity();
    std::unique_ptr<Component> getComponent(...);
private:
    std::vector<Component> components;
};

```

The problem that I'm having with this approach lies withing the act of getting a specific component. Let's say I want to get a pointer to the velocity component. I can't just have `whateverEntity.getComponent(Types::Velocity);` because the method returns a `Component` and not a `VelocityCom`. I thought about casting the `Component` pointer to a `VelocityCom` pointer but it seems that a lot of people don't like the idea of downcasting. So my question is what is a good way to get a specific component in an entity component system? Is downcasting okay in this situation or should I change my implementation to where I don't have to?

# Answer
First, returning a `unique_ptr` makes no sense. In your design (which is *not* an ECS, btw) a `unique_ptr` expresses ownership. The entity owns the component. If you return a `unique_ptr` then the entity must necessarily give up its ownership of the component. You don't want that.

Second, just downcast. "A lot of people" can dislike it all they want, but they're wrong. It's perfectly valid when used in the appropriate circumstances. Just about every engine with a component model similar to yours end up with functions like these on their core game object type:

```
struct GameObject
{
  // get generic component based on generic type identifier
  Component* Get(std::type_index type);

  // get a specific component based on compile-time type
  template <class T> T* Get() { return static_cast<T*>(Get(typeid(T))); }
};

```
> 1 votes

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


# Question
Title: How to achieve lighting like this in Unity for 2D games?
How could I accomplish a lighting effect something similar to this game?:

I'm not talking about the shadows but about the glowing/lighting effect on the crystals and the torches.

Anyone got any clues?

More images from the games steam page

# Answer
> 0 votes
I've never used Unity, so I don't know what it has to offer for this specific problem, but I would create this effect with one of these methods:

* Implement a bloom shader. This is where the brightest pixels are taken, blurred, then drawn over the scene. Here is the Wikipedia page on that.
* Simply create a "glow" texture. This could be, for example, a blurred circle. Color it appropriately and draw it on top of the glowing objects using an additive blend mode.

Here is what I mean by "glow texture"

# Answer
> 0 votes
Create a new material, with shader Sprites \> Diffuse.

Select all the objects you want to react to lighting, go to their Sprite Renderer and change the material to the one you just created.

Create a point/spot light at Z=-1 and you should see the light.

link

---
Tags: unity, c#, 2d, lighting, glow
---


# Question
Title: How do I accept only one directional input per update?
I'm coding "Snake" as my first game and I'm facing the logical fail when pressing multiple keys simultaneously eg. { up, right}; {up, left}; {down, right}, etc. Snake is able to go back and forth and eat his own body (that's not supposed to be).

My question is how can I write the keypress condition for only one press per one update is allowed?

Thank in advance.

```
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
    if (dir == DOWN ) {
        head = new Point(head.getX(), head.getY() + SPEED * delta);
    }
    if (dir == UP) {
        head = new Point(head.getX(), head.getY() - SPEED * delta);
    }
    if (dir == RIGHT) {
        head = new Point(head.getX() + SPEED * delta, head.getY());
    }
    if (dir == LEFT) {
        head = new Point(head.getX() - SPEED * delta, head.getY());
    }

}
public void keyPressed (int key, char c) {
    if ((key == Input.KEY_LEFT) && dir != RIGHT) {
        dir = LEFT;
    }
    if ((key == Input.KEY_RIGHT) && dir != LEFT) {
        dir = RIGHT;
    }
    if ((key == Input.KEY_UP) && dir != DOWN) {
        dir = UP;
    }
    if ((key == Input.KEY_DOWN) && dir != UP) {
        dir = DOWN;
    }

}

```

# Answer
> 5 votes
Your issues does not seems to be "How do I accept only one directional input per update?" but rather "How do I prevent my snake to go backward?"

From the many comments and discussion, you seem to be having a frame-rate that is not appropriate for the game you're developing. Traditionally, *Snake* is a game with a *very low* frame-rate, the snake moved only 2-3 times per second.

With current computer capabilities, we can achieve a *much* higher frame-rate. This allows to have much smoother animations which are more pleasing to the eye.

However, the base logic for a snake game has not changed. The snake must be traveling on a grid and some care must be taken to make it move on that grid.

Here is the base logic that I wanted to illustrate with my comments on the answer by @Blue (which is a very fine answer, by the way).

This is pseudo code and logic:

```
FRAME_RATE       = 30
TILE_SIZE        = 30   // Visual positions of where the snake can be
BOARD_SIZE_PX    = 600  // Size of the board in pixels, so a tile is
                        // BOARD_SIZE_PX / GRID_SIZE --> 20 px
TILE_SIZE_PX     = BOARD_SIZE_PX / GRID_SIZE
SNAKE_SPEED_TILE = 2    // A snake can travel 2 tile every second
SNAKE_SPEED_RATE = FRAME_RATE / SNAKE_SPEED_TILE // 15 frames for traveling 1 tile

main
  // setup stuff

  frameCount = 0
  currentHeading = [random heading]
  nextHeading = currentHeading
  while( true )

    updateInput( currentHeading, nextHeading )

    snake_frame = frameCount % SNAKE_SPEED_RATE
    if ( snake_frame == 0 )
      // This is the moment to update the logic of where the snake is
      // and where it must go next
      updateSnakeLogicalPosition( nextHeading )
      currentHeading = nextHeading

    updateSnakeVisualPosition( snake_frame )

    frameCount++

updateInput ( in_currentHeading, inout_nextHeading )
  // is there an input, if no, the inout_nextHeading remains unchanged
  // if not, update the inout_nextHeading if the desired heading from keyboard
  // if it is not going backwards (according to the in_currentHeading)

updateSnakeLogicalPosition( in_nextHeading )
  // Actualy move the locigal position of the snake according to the in_nextHeading
  // In theory, it is not possible at this point that your snake goes backwards
  // because you have made a check agains that in your input method.

updateSnakeVisualPosition( in_snake_animation_frame )
  animation_percent = in_snake_animation_frame / SNAKE_SPEED_RATE
  offset_in_pixels = animation_percent * TILE_SIZE_PX

  // The offset_in_pixels is the distance into the tile.
  // Now update the head and the tail tip according to that value.

```

Of course, this is assuming a 'traditional' snake, where the position of the snake is very discrete on a grid. And this is also assuming that you have added a smooth animation feature for your snake.

---

**Addendum**

Based on your latest comments I understand a bit more your situation. This here is more specific to your situation.

The idea is still to limit the frequency at whcih the snake is updated. To achieve this in your framework I suggest adding an 'time' accumulator that will track when it's time to update the position of the snake.

This is to emulate the comment from @Blue to emulate a low frame-rate since you don't seem able to limit it yet.

I haven't tested this code:

```
int mLastDir = [random initial dir];
int mMsAccumulator = 0;
const int SNAKE_RATE = 2; // Times the snake will move each second
const int SNAKE_MOVE_EACH_MS = 1000 / SNAKE_RATE; // The snake will move once
                                                  // each of these ms
const int SNAKE_SPEED_FRAME_PX = 20; // This is realy up to you: how many px
                                     // the snake moves each time it moves,
                                     // based on the size of your tiles

public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
    mMsAccumulator += delta; // Accumulate to determine when we're ready
    if ( mMsAccumulator < SNAKE_MOVE_EACH_MS )
        return;

    // We're ready now, enough time has passed.
    mMsAccumulator -= SNAKE_MOVE_EACH_MS;

    // dir contains the last valid direction, it's safe to use.
    // The player will be able to change it until we're ready to update
    // the position of the snake.
    if (dir == DOWN ) {
        head = new Point(head.getX(), head.getY() + SNAKE_SPEED_FRAME_PX);
        mLastDir = dir;
    }
    if (dir == UP) {
        head = new Point(head.getX(), head.getY() - SNAKE_SPEED_FRAME_PX);
        mLastDir = dir;
    }
    if (dir == RIGHT) {
        head = new Point(head.getX() + SNAKE_SPEED_FRAME_PX, head.getY());
        mLastDir = dir;
    }
    if (dir == LEFT) {
        head = new Point(head.getX() - SNAKE_SPEED_FRAME_PX, head.getY());
        mLastDir = dir;
    }

}

public void keyPressed (int key, char c) {

    if ((key == Input.KEY_LEFT) && mLastDir != RIGHT) {
        dir = LEFT;
    }
    if ((key == Input.KEY_RIGHT) && mLastDir != LEFT) {
        dir = RIGHT;
    }
    if ((key == Input.KEY_UP) && mLastDir != DOWN) {
        dir = UP;
    }
    if ((key == Input.KEY_DOWN) && mLastDir != UP) {
        dir = DOWN;
    }

}

```

# Answer
> 8 votes
Firstly, you need to use a switch case statement and decide which direction overrides the others, for example, if they press all four buttons, which button should be listened to for input? This gets put in order within the switch statements.

*Edit:* For clarity about the above statement. You **do** need to use a switch case statement (or similar structural logic) to stop the following from happening.

```
dir = up
inputs == down left

if dir != right & input.has(left):
    dir = left

if dir != up & input.has(down):
   dir = down

# dir started as up but is now down, an illegal move in Snake

```

Original intent is to go from moving up, to moving left and not down (as this causes the snake to fold back on it's body and die. Instead your logic makes you move left, and then down before your input logic finishes. This is why having the if/else or switch/case statement is necessary.

You can now use a boolean field in the class to keep a track of the input being successfully processed, and update it each time. You can have different bools for different types of inputs, not just directions. For example, you can track if "Pause" has been pressed so you don't accidentally unpause in the same update loop, or if you had a "Run" / "Slow" button but you want Run to have a bigger priority.

```
// This boolean is used to show if an input has been accepted this update.
private bool directionSet = false;

public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
{
    switch(dir)
    {
        case DOWN:
            head = new Point(head.getX(), head.getY() + SPEED * delta);
            break;
        case UP:
            head = new Point(head.getX(), head.getY() - SPEED * delta);
            break;
        case RIGHT:
            head = new Point(head.getX() + SPEED * delta, head.getY());
            break;
        case LEFT:
            head = new Point(head.getX() - SPEED * delta, head.getY());
            break;
    }

   directionSet = false;
}

public void keyPressed (int key, char c)
{
    // You can still set more input logic here or at the bottom of the method:
    // ...

    // Check if a direction is set before accepting new directional input
    if(!directionSet)
    {
        switch(key)
        {
            case Input.KEY_LEFT:
                if(dir != RIGHT)
                {
                    dir = LEFT;
                    directionSet = true; // Set on each input
                }
                break;
            case Input.KEY_RIGHT:
                if(dir != LEFT)
                {
                    dir = RIGHT;
                    directionSet = true;
                }
                break;
            case Input.KEY_UP:
                if(dir != DOWN)
                {
                    dir = UP;
                    directionSet = true;
                }
                break;
            case Input.KEY_DOWN:
                if(dir != UP)
                {
                    dir = DOWN;
                    directionSet = true;
                }
                break;
        }
    }
}

```

# Answer
> 1 votes
I've also developed snake, and ran into the same problem. I run snake at 30fps, yet only 'update' every 10 frames, in between the player still has the freedom to change direction.

You're trying to prevent a player from going back where he came from in the input handling. Say you were moving up, your input handling will prevent the player from moving down, but doing {right, down} as you described will be two seperate, valid movements **in one update cycle** as it were.

I solved this by storing the direction a player moved in in the previous update, and use this to prevent the opposite direction from being a legal move.

EDIT: In your movement method you need to keep track of your previous movements. Say you've decided to move UP this cycle (based on the user's input) then the actual movement code would look like

```
private void move(int dir) {
  switch(dir) {
    //your own abstraction of the directions, you could use strings as well
    case DIRS.UP: player.y -= 10; previousMovement = DIRS.UP;
    ..
  }
}

```

The player has now moved, and stored the direction in which it has moved. Now all that's left do to in the input handling is to check for this variable.

```
private void handleInput(int key) {
  if ((key == Input.KEY_DOWN && previousMovement != DIRS.UP)) {
    directionToMoveNextUpdate = DIRS.DOWN;
  }
}

```

The clue is that you do not check based on your previous *input* but based on your previous *movement* before setting a new direction. `previousMovement` is only changed when the player moves, you can press as many buttons as you want during each update cycle and it wouldn't affect it.

I hope that clears it up, if not: look at my github (ThommyTheThird) for a working AS3 example.

---
Tags: c#, input, slick, keyboard
---


# Question
Title: Lightning bolt effect with particles is not continuous
I am Drawing a lightning effect animation using this image:

Below the result:

As you can see the outcome is not a continuous purple color as I wanted it to be, but it has black spaces in between some parts. The way i am drawing this animation is that i am drawing two `LightningBolts` every frame in Additive mode. Every `LightningBolt` is drawn with the help of 21 random points across the width of the animation which makes `20 lines` of **various angles**. So I rotate the texture I have to match each angle I calculated for each of those 20 lines for the two `LightningBolts` I am drawing in every frame in Additive mode.

What are your suggestions to overcome this problem ?

# Answer
Do not change the rotation. Change the y-position instead.

Another completely different approach which will look far better but might be far slower would be to draw the white core part of the lightning as a randomized path of line segments and then add the magenta halo in post-processing by taking the bolt, applying gaussian blur, removing the green channel (to make in magenta) and draw the blur first and the original bolt second.
> 1 votes

# Answer
Never done anything like that, but as an sugestion: what about the to draw the circle with gradient on each point between lighting parts? This will make the edges smooth, that might not be very much like a real lightning, but no ragged edges.
> 0 votes

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


# Question
Title: Why does Intersector.overlaps return false?
I am trying my hand at creating a simple game using libGDX.

The idea is: We have a hero who jumps and world consist of dynamically created moving platforms in an auto side-scrolling manner. In order to progress our hero need to jump on these platforms and avoid falling. I have figured out how to do this using the built-in libGDX collision detection mechanism.

Code is:

```
    public boolean collides(Hero hero){
    if (position.y < hero.getY() + hero.getHeight()) {
        return Intersector.overlaps(hero.getBoundingRect(),boundingRect);
    }
    return false;
    }

```

But, our hero need to die when hits side of a platform. Following code should do the trick but even though bounding rectangle of hero surely overlaps(see below image) the bounding rectangle of platform `Intersector.overlaps` returns false no matter what.

My code for this task:

```
    public boolean   collidesSide(Hero hero){
    float heroYH = hero.getY() + hero.getHeight();
    float heroXW = hero.getX() + hero.getWidth();
    if (heroYH > position.y && heroXW>position.x){ // Platforms position
        Gdx.app.log("Platform","hero.bound:" + hero.getBoundingRect().toString() + " plat.bound:" +boundingRect.toString());
        Gdx.app.log("Platform","Intersect: " + Intersector.overlaps(hero.getBoundingRect(),boundingRect));
        if (Intersector.overlaps(hero.getBoundingRect(),boundingRect)){
            Gdx.app.log("Platform","CollidesSide: True");
            return true;
        }
        return false;
    }

    return false;
    }

```

It seems that I have missed some logic or doing something wrong.

How should I handle this issue?

*Also this is the output log*

```
Platform: Intersect: false
Platform: hero.bound:20.0,64.65544,25.0,32.0   plat.bound:-3.0893557,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,65.13417,25.0,32.0 plat.bound:-4.4350085,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,65.74593,25.0,32.0 plat.bound:-5.779882,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,66.43762,25.0,32.0 plat.bound:-7.042242,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,67.29663,25.0,32.0 plat.bound:-8.372085,96.0,19.0,5.0
Platform: Intersect: false

```

**UPDATE:**

The Red and Cyan rectangles seen in images are rendered output of Bounding Rectangle(hit boxes) of each object, not actual sprite.

# Answer
After trying a few revisions I solved the issue. But not sure why it is resolved.

I was checking for collision in my GameWorld object as shown below:

```
    if (scroller.platformCollides(hero)){
        hero.walk();
        }
    else if (scroller.platformCollidesSide(hero)) {
        if (hero.isAlive()) {
            scroller.stop();
            hero.die();
            hero.decelerate();
            currentState=GameState.GAMEOVER;
        }

```

Then I changed the code to:

```
    if (scroller.platformCollidesSide(hero)) {
        if (hero.isAlive()) {
            scroller.stop();
            hero.die();
            hero.decelerate();
            currentState=GameState.GAMEOVER;
        }
    }
    else if (scroller.platformCollides(hero)){
        hero.walk();
        }

```

which magically solved my issue. But as I said above I don't understand why this worked.
> 0 votes

# Answer
It very much looks like your `boundingRect` is incorrectly calculated. From your log you've got 5 `boundingRect`s (I've re-ordered them here, right-to-left);

```
-3.0893557, 96.0, 19.0, 5.0
-4.4350085, 96.0, 19.0, 5.0
-5.779882,  96.0, 19.0, 5.0
-7.042242,  96.0, 19.0, 5.0
-8.372085,  96.0, 19.0, 5.0

```

This would mean that all of these 19x5 rectangles are located at Y=96 and then they overlap (for example `3.0893557 + 19.0 = 22.0893557`, which is overlapping all of them). This seems wrong to me because in your screen shot none of the platforms are overlapping with eachother.

Further, your `Hero` is located at `20.0` on the X-axis, but since all platforms are only `19.0` wide, and the right-most one is at `-3.0893557`, none of them will reach the `Hero`. The closest will be `20.0 - (-3.0893557 + 19.0) = 4.0893557` away from the `Hero`.

Double check how the bounding rectangles are calculated (or how the parameters for the bounding rectangles are calculated) and consider debug-rendering them using the `ShapeRenderer` class to visualize them.
> 2 votes

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


# Question
Title: Is there an optimal method to implement moving background?
I am trying to develop a little game using libGDX. We have a hero who jumps and world consist of dynamically created moving platforms in an auto side-scrolling manner. I wanted background to scroll at half speed of foreground objects to establish a moving background effect.

For this I came up with this idea: Have a 1024px X 240px image and each time render executes select a 256px X 240px region from that texture according to backgroundObject X position. Something like this:

And this is my code:

```
    bgTexture = new Texture(Gdx.files.internal("data/bg.png"));
    bgTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);

```

And this code executes inside render method.

```
    bgRegion= new TextureRegion(bgTexture, -1 * (int)bgObj.getX(),0,256,240); //bgObj is a scrollable object where in each update changes X value of position(Vector2): moves left.
    bgRegion.flip(false, true);

    batcher.draw(bgRegion, 0, 0, Variables.ScreenWidth / 2, Variables.ScreenHeight / 2);

```

Now, I am wondering if there is a better method to implement this effect? My method seems to have high system resource cost.

# Answer
> 5 votes
Don't keep newing up `TextureRegion`s, try re-using one and just change the parameters of that.

```
private TextureRegion bgRegion;

public void create() {
    bgRegion= new TextureRegion(bgTexture, -1 * (int)bgObj.getX(),0,256,240); //bgObj is a scrollable object where in each update changes X value of position(Vector2): moves left.
}

public void draw() {
    // Update the region here
    bgRegion.setRegionX(-1 * (int)bgObj.getX());
    batcher.draw(bgRegion, 0, 0, Variables.ScreenWidth / 2, Variables.ScreenHeight / 2);
}

```

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


# Question
Title: Havok Physics : "hkQuaternionf not normalized/invalid!" when hkpWorld::stepMultithreaded()
today I want to ask a question about Havok Physics 2012.
My havok version is 2014.1.0-r1 (x86 SIMD version), and I'm using Visual Studio 2012 on Windows 8.
My problem is, that once I add a rigid body to the world, the next time I call `hkpWorld::stepMultithreaded()`, it breaks in some SSE math related function and gives me this error message through my error report function.

> C:\NightlyJobs\09-07-Sun-01\Source\Common/Base/Math/Vector/Sse/hkSseVector4Util. inl(307): \[0x1FF88F0E\] Assert: hkQuaternionf not normalized/invalid!

Here's the stack trace:

> (null)(0):'hkDefaultError::message'
> (null)(0):'hkError::messageAssert'
> (null)(0):'hkVector4UtilImpl::convertQuaternionToRotation'
> (null)(0):'hkRotationf::set'
> (null)(0):'hkTransformf::setRotation'
> (null)(0):'hkSweptTransformUtil::calcTransAtT1'
> (null)(0):'hkSweptTransformUtil::\_stepMotionState'
> (null)(0):'hkRigidMotionUtilApplyForcesAndStep'
> (null)(0):'integrateJob'
> (null)(0):'hkpMultiThreadedSimulation::processNextJob'
> (null)(0):'hkJobQueue::processAllJobs'
> (null)(0):'hkpWorld::stepMultithreaded'

Here's how I create and add the rigid body.
It's so basic that I didn't think there would be any room for bizarre error in it...

```
hkpSphereShape* sphere = new hkpSphereShape(radius);  // radius is 10.0f here.

hkpRigidBodyCinfo rigidBodyInfo;
rigidBodyInfo.m_shape = sphere;

m_RigidBody = new hkpRigidBody(rigidBodyInfo);

world->markForWrite();
world->addEntity(m_RigidBody);
world->unmarkForWrite();
m_RigidBody->removeReference();

```

I don't set position or rotation of the rigid body myself, so why it breaks in some quaternion related function is beyond me.
I speculated it might be one of those multithreading-related bizarre errors, so I tried changing

```
m_WorldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_MULTITHREADED;

```

to

```
m_WorldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_DISCRETE;

```

and

```
m_World->stepMultithreaded(m_JobQueue, m_CpuThreadPool, timeStep);

```

to

```
m_World->stepDeltaTime(timeStep);

```

but the problem persisted.

Do you know something that I could be doing wrong ?
Please tell me in the comments if you need to see some of my other code to help!
Any help would be greatly appreciated, thanks!

# Answer
> 1 votes
Answering my own question...

It appears that if you're using the SIMD-enabled version of havok, you need to define `HK_CONFIG_SIMD`=1.

Not setting it with the SIMD-version, and setting it with the non-SIMD-version can **both** result in a crash.

**For future-visitors**:
Whichever version of havok you're using, if you encounter SSE-related crashes or errors, make sure you're not accidentally defining or not defining `HK_CONFIG_SIMD` in your code or in the project settings in your IDE.

---
Tags: physics-engine, havok, simd
---


# Question
Title: Do the lookDirection vector and upVector have to be orthogonal? What happens if they are not?
I'm currently starting with DirectX and building a small framework for myself and ran into a problem comprehending the camera vectors (position, lookDir, up).

What they represent exactly is clear, but here's the problem:

For my understanding the lookDirection Vector and the up Vector have to be orthogonal to each other. **It this true? What happens if they are not?**

# Answer
> 3 votes
The Up & look direction that you plug into the function as arguments do not need to be orthogonal. But then the 'behind the scenes' part of the function will make them orthogonal.

When they made XNA, they created similar functionality and since it's managed code, you can reflect it and see the 'behind the scenes' code that uses double cross product equations that make the 2 vectors orthogonal. The following snippet is slightly different in that it takes point in space that the camera is looking at instead of a looking direction but the first line converts it into a looking direction like yours does. The result is a view matrix.

```
public static Matrix CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector)
{
    Matrix matrix;
    Vector3 vector = Vector3.Normalize(cameraPosition - cameraTarget);
    Vector3 vector2 = Vector3.Normalize(Vector3.Cross(cameraUpVector, vector));
    Vector3 vector3 = Vector3.Cross(vector, vector2);
    matrix.M11 = vector2.X;
    matrix.M12 = vector3.X;
    matrix.M13 = vector.X;
    matrix.M14 = 0f;
    matrix.M21 = vector2.Y;
    matrix.M22 = vector3.Y;
    matrix.M23 = vector.Y;
    matrix.M24 = 0f;
    matrix.M31 = vector2.Z;
    matrix.M32 = vector3.Z;
    matrix.M33 = vector.Z;
    matrix.M34 = 0f;
    matrix.M41 = -Vector3.Dot(vector2, cameraPosition);
    matrix.M42 = -Vector3.Dot(vector3, cameraPosition);
    matrix.M43 = -Vector3.Dot(vector, cameraPosition);
    matrix.M44 = 1f;
    return matrix;
}

```

# Answer
> 4 votes
LookAt functions construct an orientation from a pair of non-colinear vectors.

As long as they are not completely parallel, it is possible to via repeated cross product construct a set of orthogonal vectors representing the new orientation.

There are numerical stability concerns when they start becoming parallel as the cross product magnitude starts approaching zero.

If you do not do the orthogonalization steps and try to use a non-orthogonal set of basis vectors, you no longer have a rotation.

# Answer
> 2 votes
They don't need to be orthogonal. For example a traditional first person camera would have the up vector locked as (0, 1, 0) and with the change of the direction vector when looking around, it's not orthogonal most of the time. This prevents the roll effect when you turn sideways that you can see in flight simulators, where the up vector changes all the time to enable free rotation.

---
Tags: mathematics, directx
---


# Question
Title: Database for a diablo 2 like item system?
Diablo 2 has a very sophisticated item system and I want to create something similar. But I am having a hard time getting the architecture right. In Diablo 2 most different kind of gear has different kind of attributes and they can all hold X amount of modifiers depending on the quality.

However my server creates items randomly based on several factors. And each item is pretty much unique. To lower the amount of records a player can only have X amount of items. I tried to get some thought on "paper" and would like some insight in how this can be done properly. These are my findings:

Having all my different kinds of gear separated since weapons have damage, boots alter speed and armor, shield give armor and block rate, etc. A modifier table holds all the modifiers and has a FK to weaponId, bootsId, shieldId and only one should be set where the others are null. I could add requirements in the main tables as well but in the diagram below I opted for a separate 1 to 1 relation table.

And this could be a variation of it where there is a single table linking them together.

To clarify table `modifiers`, the column `modifies` should hold something like `undead` and percentage could hold `10` to make the armor or weapon 10% more effective to undead. Or `strength` & `5` to increase strength by 5.

But I might be over complicating things. I could have a single item class that defines the type, damage, armor, etc and keep them null if that attribute does not belong to the item. I could even throw in the requirements since thats a 1 on 1 relation anyway. The modifier relation would stay the same where a single item can have more modifiers. Something like this:

But this made me wonder, why would I store any attributes in the actual item table? Damage could be a modifier too and so can defense. I would handle it like so:

```
modifies = "baseDamage"
amount = "10"

modifies = "bonusDamage"
amount = "3"

```

Now I can show the player what the base damage of the weapon is and how much the bonus is. Heck, I could even handle the item name and description using this and combine them all by coding in there proper classes. This would make it really flexible where a stat like strength in code is just a String and an int.

The downfall is a lot more coding and calculations and a large table since each item has at least a 3 or 4 of modifiers. With 10.000 players all holding 100 good items with like 10 modifiers this would translate into 10.000.000 records. Nothing that MySQL could not handle but it does make me wonder about performance a bit.

I really need some advice or maybe a whole different view on the topic to make this work properly.

**Edit**

I was thinking about something a bit different. If I would make a class to hold a property, or even stats and store that as a binary field alongside the item? Would this be a good solution? Take a look at the following code:

```
public class WeaponExample {
    Weapon weapon = new Weapon();

    public WeaponExample()
    {
        weapon.name = "sword";
        weapon.damage = 10;
        weapon.levelRequirement = 4;

        //create a modifier that adds extra strength to the character
        Modifier modifier1 = new Modifier();
        modifier1.type = "strength";
        modifier1.amount = 5;

        //create a modifier for 10% extra damage against undead
        Modifier modifier2 = new Modifier();
        modifier2.type = "undead";
        modifier2.percentage = 10;

        //add them to the weapon
        weapon.modifiers.add(modifier1);
        weapon.modifiers.add(modifier2);

        //serialize weapon.modifiers to store in database.
        //..
    }
}

class Weapon {
    //Basic weapon data
    public String name;
    public int damage;
    public int levelRequirement;
    //... etc

    //Data to be serialized to binary and stored
    List<Modifier> modifiers;
}

class Modifier {
    public String type;
    public int percentage;
    public int amount;
}

```

Serializing those 2 modifiers generates a byte array of 183 bytes. This will likely be a bit larger as I add some extra stuff. I will do some more testing. Now I am by far an expert on these things but if I would have a separate table I would end up with:

* 2 varchars of 16 bytes (14 characters + 2 overheat).
* 2 ints of 8 bytes (since the others will be null?).

That makes 24 bytes instead of the whopping 283. So I'm thinking this is not such a good idea. This does save me a lot of looking up in the SQL table and if I deserialize on the clients end then my server does not have to do the job of deserializing all those items when requested.

# Answer
> 2 votes
Given your requirements I would recommend not using a RDBMS. I'd look at a JSON type document database for storing your data. It tends to be me more flexible and matches the data structures you'll design in a cleaner way.

If you do want to use an RDBMS though I'd look at PostgreSQL rather than MySQL. PostgreSQL 9.4+ has JSON binary support. You can essentially design a table that looks like characters(id serial, inventory jsonb). With the database module plv8 you can write Javascript functions to operate on the objects. As an example your inventory data could just look like:

```
[
    {
        "name": "sword",
        "damage": 10,
        "levelrequirement": 4,
        "modifiers":
        [
            {
                "type": "strength",
                "amount": 5
            },
            {
                "type": "undead",
                "percentage": 10
            }
        ]
    }
]

```

In plv8 you can implement trade operations between players and modify or delete items. It's up to you though how much you do on the database and how much you do on the server.

```
create or replace function add_item(character integer, item json) returns json as
$$
    // No error handling is done here. Good idea to try/catch
    plv8.subtransaction(function()
    {
        var inventory = JSON.parse(plv8.execute('select inventory from characters where id=$1', [character])[0].inventory);
        inventory.push(item);
        plv8.execute('update characters set inventory=$2 where id=$1', [character, JSON.stringify(inventory)]);

        // Can even setup database notifications so others can listen for events
        plv8.execute('notify inventorychanged, \'{ "character": ' + character + '}\'');
    });
    return { success: true };
$$
language plv8 stable strict;

```

I should mention you can still setup indexes and query json binary objects in postgresql. Also since jsonb is binary it's fairly compact. Not as compact as you'd probably like, but it's manageable.

---
Tags: architecture, databases, sql
---


# Question
Title: Unity3d - Transform rotation(angle) help
Im trying to rotate an object 90 degrees to the left but instead of rotating straight left it rotates 270 degrees to the right.

Here's the part of the code which controls the rotation:

```
rotationDestination = new Vector3(60, 270, 0);
if (Vector3.Distance(transform.eulerAngles, rotationDestination) > 0.2f) {
  transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles,
                                       rotationDestination,
                                       rotationSpeed * Time.deltaTime);
}

```

If I try to make the Y axis -90 a.k.a (60, -90, 0) then it rotates constantly to the left.

How do I make it rotate straight to the left (90 degrees) ?

Thank you.

# Answer
You can use Quaternions instead of Euler Angles to solve this.

```
transform.rotation = Quaternion.Lerp(transform.rotation,
    Quaternion.Euler(rotationDestination), Time.deltaTime * rotationSpeed);

```

If you want to test distance still, you can use...

```
if(Quaternion.Angle(transform.rotation, Quaternion.Euler(rotationDestination)) > 0.2f)

```

I'd suggest you make 'rotationDestination' into a quaternion too. Just so that you're not converting back and forth between quaternions, and euler angles as much.
> 2 votes

---
Tags: unity, rotation, vector, transformation, lerp
---


# Question
Title: Which parts of game should belong to engine and which should belong to scripts?
Often, a game is split into engine code (i.e. C++) and scripts (i.e. Lua).

Which parts / modules of game code should typically belong to engine, and which should belong typically to script-domain code?

For example: AI for characters is typically put in scripts. What about GUI, sound, asset / resource management, levels / maps, quests etc?

# Answer
> 2 votes
Whatever's most amenable to encapsulation or is already well specified - and thus well encapsulated - in C++ classes / functions, i.e. exists behind a stable, solid interface.

Aspects that are ever-changing, and aspects that are coded at a low level and need fine control like rendering and low-level network code, are poor candidates for scripting. It depends on just how much control you need, and at just what level. Once the need for control and speed becomes too great, you'll gain little out of wrapping that logic in script, and in fact may stand to lose performance due to the overheads of making scripting calls, even with a nice fast scripting engine like LuaJIT.

Yes, all the things you list are good candidates, though again, you'll probably do some work on each front to improve your interface to the C++ that your relevant scripts will call into. Something like sound would be a nice, easy place to start. Start where your code is already most stable.

# Answer
> 1 votes
> What about GUI, sound, asset / resource management, levels / maps, quests etc.?

These are all good candidates for scripts. Most of the game can typically be written in a scripting language. Typically the only thing that may require being written in the core language (C, C++, C#, Java, etc) is anything that is performance critical or core game algorithms. It allows for faster development as changing scripts doesnt require a rebuild of the game. This answer has a bunch more information on scripts vs core language

# Answer
> 1 votes
It does not matter what you handle in Lua. Almost everything in a game engine can be handled explicitly via Lua. All that matters in the end is what you want to do with the language.

For example, when desiging your game:

* You can choose to use Lua only for scripting AI. C++ will then have a call back for events and data to be handled via Lua. (Cry Engine)
* You can choose to have Lua directly call to low level systems in your engine. (Love2D, Polycode)
* You can choose to literally write almost everything in Lua, with the exception of a few key systems: Rendering, threading API, etc. (The Legend of Grimrock I and II)

Just do what ever you feel is necessary, the easiest, or convenient to you.

---
Tags: architecture, scripting
---


title: OpenGL Mapped Memory Shader Source

text:
# Question
Title: OpenGL Mapped Memory Shader Source
Is there any way to get a pointer to a newly created shader object's source? I'd like to load a shader directly from file in to my shader object instead of loading to an intermediary variable and then using glShaderSource().

I haven't been able to find any information regarding this, only regarding buffers.

# Answer
Oops, this was a misunderstanding of memory mapping on my part. I should be able to grab a pointer to the file data and pass it in directly as a parameter to glShaderSource.
> -1 votes

---
Tags: opengl, shaders, loading, memory-efficiency
---


# Question
Title: Tween - keeping a constant velocity at different distances
I am using a tweening library to move my units around. The problem is that the speed varies depending on the distance that the unit has to move because of the tweening:

```
var time = 1000;
var tween = new TWEEN.Tween({ x: startX, y: startY })
    .to({ x: endX, y: endY }, time)
    .start();

```

^No matter the x and y values it will always take the same amount of time.

I tried fixing this by dividing the distance by the speed:

```
// distance = speed * time
// time = distance / speed
var x = endX - startX;
var y = endY - startY;
var distance = Math.sqrt(x * x + y * y);

var time = distance / speed * dt;
var tween = new TWEEN.Tween({ x: startX, y: startY })
    .to({ x: endX, y: endY }, time)
    .start();

```

However it still doesn't move at the same speed! Grr!

I made a snippet that shows a square endlessly moving in a rectangle, when done correctly *( which this isnt... )* it should move at the same velocity no matter the distance.

```
var rect = document.getElementById("rect");

var pos = [ [0, 0], [200, 0], [200, 50], [0, 50] ];
var i = 0;
var time = 1000;
var speed = 10 * 1000; // 10px per second

var tweenStart = { x: 0, y: 0 };
var tweenEnd = { x: pos[i][0], y: pos[i][1] };

var tween = new TWEEN.Tween(tweenStart)
    .to(tweenEnd, time)
    .onUpdate(function () {
        rect.style.top = this.y + "px";
        rect.style.left = this.x + "px";
    })
    .onComplete(function () {
        tweenStart.x = pos[i][0];
        tweenStart.y = pos[i][1];
        i += 1;
        if (i >= pos.length) i = 0;
        tweenEnd.x = pos[i][0];
        tweenEnd.y = pos[i][1];
        // time = distance / speed
        var x = tweenEnd.x - tweenStart.x;
        var y = tweenEnd.y - tweenEnd.y;
        var distance = Math.sqrt(x * x + y * y);
        time = distance / speed * dt;
        tween.start();
});

setTimeout(initiate, 0);

var now, then, dt;

function tick() {

    now = perfNow();
    dt = now - then;
    then = now;

    TWEEN.update();

    requestAnimationFrame(tick);

};

var perfNow = (self.performance && self.performance.now) ? self.performance.now.bind(performance) : Date.now;

function initiate() {

    var x = tweenEnd.x - tweenStart.x;
    var y = tweenEnd.y - tweenEnd.y;
    var distance = Math.sqrt(x * x + y * y);
    time = distance / speed * dt;

    tween.start();

    then = perfNow();

    tick();

};
```

```
body {
    margin: 0;
    overflow: hidden;
}
div {
    position: absolute;
    width: 10px;
    height: 10px;
    background-color: black;
}
```

```
<script src="https://dl.dropboxusercontent.com/u/53738503/tween.min.js"></script>
<div id="rect"></div>
```

# Answer
> 2 votes
For some reason the tween library requires you to update the tween inside your `onComplete` function, and calculate the time using something like the following:

```
.onComplete(function () {
        tweenStart.x = pos[i][0];
        tweenStart.y = pos[i][1];
        i += 1;
        if (i >= pos.length) i = 0;
        tweenEnd.x = pos[i][0];
        tweenEnd.y = pos[i][1];

        var x = tweenEnd.x - tweenStart.x;
        var y = tweenEnd.y - tweenStart.y;

        var distance = Math.sqrt(x * x + y * y);
        time = (distance / speed) * dt;
        tween.to(tweenEnd, time);

        tween.start();
}

```

So the main point is the `tween.to` line inside the function, which I suppose updates the tweening time. Also make sure to use a small speed, or tweak the time calculation otherwise. A speed of 2 seems to look nice to me.

---
Tags: javascript, linear-algebra, tweening
---


# Question
Title: Calculate future 3D Position of object(Unit)?
I've looked around and almost all examples is see have a velocity vector which I do not have, or at this point am unable to figure out. Im trying to find the 3D position where i can launch a trap in game to land in the targets path of movement assuming constant speed.

What I do Have

Two Coords: Initial and a second set of X,Y,Z after 1 frame. Unit speed as a number from the game, hoping i can calculate a better number based on the one frame difference above. The speed of the trap - 25yards/s The time between frames 1/ Games current FrameRate

This works on still targets but I cannot find out how to get the units speed into the calculation:

```
function PredictTrapPosition(unit)
unit = unit or 'target'
local x1, y1, _ = UnitPosition(unit) --forget z assume they are running on flat ground.
C_Timer.After(1/GetFrameRate(), function() -- after one frame
    local x2, y2, z = UnitPosition(unit)
    local px, py, _ = UnitPosition('player') --My position
    local distance = math.sqrt((x2 - px)^2 + (y2 - py)^2)
    local trapSpeed = distance / 25 -- trap travel time.
    local angle = atan2(x2-x1, y2-y1)
    local x = x2 + cos(angle) * trapSpeed
    local y = y2 + sin(angle) * trapSpeed
    WorldClick(x, y, z)
end)

```

end

Hopefully a math guru can chime in and help me fix this probably simple formula.

# Answer
I am a little curious on why you don't have the velocity vector. But, no matter it can be calculated.

Note that there will be error in here somewhere... it's 5am. The framework is the same however.

**First step. We need that Vector.**

We know the position before, and after the frame step. You should have the delta time as well. if not, there really isn't much you can do.

Let xi be Inital Player position before render, xf be position at the frame's render.

Let yi be initial Player y position before render, yf be the position at the frame's render.

let dt be Delta Time

Distance 2d Distance= Sqrt((xf-xi)^2 + (yf - yi)^2 ))

Radians = Atan((yf-yi)/(xf-yi))\]

Find Speed = Distance\*( dt\*(dt/1))

*Now we can find our vector!*

vecVelocity.x = cos(radians)\*speed

vecVelocity.y = sin(radians)\*speed

**Second Step. We need to know how long it takes for the trap to land.**

TimeNeeded = Trap.Distance / Trap.Speed

**Third Step. Find the minimum distance we need to launch the trap.**

AngleFromTrap = ATan((Unity.y - Trap.y)/(Unit.x - Trap.x))

*Using the distance line between trap and unit as a reference, we calculate the angle from the reference frame to*

AngleBetweenVectors = ACos((unit.x) / (unit.x + unit.y))

*NOTE: This is a distance from the trap, that is perpendicular to the distance between Unit and Trap. This intersects the trajectory of the unit.*

Distance from traps center = Cos(AngleBetweenVectors)\*(unit.x + unit.y)

*Before we continue... this is a safety check.*

If Distance from the traps center is larger than Trap's affect radius, we don't bother with activating.

Other wise... Find out how the minimum activating distance.

We start from the "Distance from Traps Center" and calculate back towards the unit. We multiply the unit's velocity by the number of seconds it will take for the trap to land.

Once we find the point. Find the distance from that to the center. And that is your radius.
> 1 votes

---
Tags: 3d, lua, movement-prediction
---