title: Logic only GUI library

text:
# Question
Title: Logic only GUI library
I'm not sure whether this place is the correct for asking this. If it's the wrong place I'm sorry, please tell me if so!

I'm making a small game for fun which would uses an own engine with OpenGL and Vulkan as underlying renderer implementation. The engine itself is targeted for *Mono/.Net.*

Currently I'm not yet there but I'll come to the point where I'm pushed to implement some kind of GUI (I'm thinking ahead because of good design). I already searched the Internet for render independent GUI systems but I wasn't lucky yet. As result I thought about how I could implement the GUI on my own and came to the conclusion:

* a independent implementation is needed which takes care only for layout, positioning of GUI objects with responding to inputs.
* another implementation is needed which only takes the results of calculations for rendering (the renderer)

Before I start inventing the whole wheel new I simply want to know:

Is it a correct approach to doing it this way? Is there a different common approach doing what I described?

# Answer
For a video game, consider your... ern... non-widget-GUI. If you use your game window to handle rendering and to handle widgets, you are mixing concerns. Therefore, either you make the widgets a subsystem (which probably means you have to roll your own), or you render your game inside of a widget.

## OpenTK.GLControl

OpenTK.GLControl is a WinForms control that allows you to render using OpenGL (via OpenTK). Since it is a WinForms control, it is a widget you can add to a regular WinForms form and use it to render.

That will allow you to add other regular WinForm controls (such as button, text boxes, etc...) ontop of it.

I have been able to get the verion 1.1.1589.5942 to work on WinForms. To have it work properly, you need to:

1. Use `Application.Idle` to place your render codde.
2. Make sure you call `control.Context.SwapBuffers();`
3. If you want to have multiple `GLControl`, you will have to call `MakeCurrent`. Your `GL` calls only apply to the current control.

Futhermore, Mono supports WinForm on Linux and other platforms. In theory this can work without additional changes to the code.

*Tested no Windows on .NET 4.6, working correctly. Not tested on Linux.*

## Roll your own

**MVC**

Do you remember SmallTalk? Yeah, me neither. But I'm aware the MVC was introduced in SmallTalk by Trygve Reenskaug.

*The real MVC, not that thing the PHP frameworks claim to be.*

It is a simple idea... You have an object-oriented model of reality, and to access it you create a tool that presents a view and handles the interaction with the user:

It is better to understand with this diagram from Wikipedia:

But using MVC isn't enough...

---

**Widgets**

**Plot twist! MVC is dead.** well, sort of.

MVC was dethroned by the concept of *GUI components* (A.K.A Controls, A.K.A Widgets) a long time ago.

Using widgets it is common to implement a "fat"※ view class, because it does not have to deal with the actual display instead its concern is to handle the widgets (which will worry about rendering the interface).

※: I say "fat" because it has the controller logic. It no longer has to worry about rendering, so this is not really mixing concerns.

---

To implement GUI widgets you need a hierarchical structure that as the window as root and contains the different GUI widgets.

Each widget is a class, it has an internal view model (state) and behavior, and it is responsible of rendering its appearance. Therefore, the widget class is an encapsulation of fragments of view, controller and view model. It should be noted that the view model in the widget is a surrogate for a fragment of the actual model of the application... if you do not want your "fat" view to handle synchronizing the model (reading and writing attributes to the widget), you would have to implement some kind of binding. And then you have MVVC.

The object in charge of that hierarchy is the "composer", it should compartmentalize the window to give each widget the space where it will render. It should take care of Z order, it could handle widget sizes and preferably it should abstract the coordinates in such way that the widget code does not need to worry about its own position on the parent widget when rendering.

Speaking of handling the coordinates, one of the important features of the GUI widget system is scrolling. The composer should allow you to scroll all the contents of the window by some offset, and the widgets should not have to have special code to handle that. You should also think about positioning and resizing. For instance, Layouts are a useful model, also Dock and Anchors. And you may also want to borrow the ideas of `fixed`, `relative` and `absolute` position from HTML + CSS.

Finally, for a modern widget system, you also need to implement an "event dispatcher", capable of bubbling events.

---

While the above is enough to make a good GUI widget system, I want to note that some modern systems has opted to support CSS (or a subset of it) to manage the attributes of the widgets. So, if you want to create a general solution, consider to support *selectors*, to facilitate the creation of tools that apply CSS (or similar) to the system.

---

Of course, you still would need to implement buttons, sliders, input boxes, etc...
> 1 votes

---
Tags: gui, logic, mono
---


# Question
Title: Player Movement in direction of camera facing
I developing FPS multiplayer game.

I have my Player Camera that rotate Around the Player.

Player can touch the screen and rotate the camera using swipe.

My Problem is when the camera facing is change my player movement is not follow the camera facing.

when my camera rotate Left side to then player rotate to the left side but when i press my joystick button forward then player can't move forward can't change the moving direction of Player.

# That is my Player Script.

```
public class FPScontroller : MonoBehaviour {

// Should this script respond to input?
public bool canControl = true;
public GameObject lookObj; //This is root object that containc MainCamera, Weapons etc.
public GameObject joystick;
bool useFixedUpdate = false;

//Check when run, walk or when can run or not
[HideInInspector]
public bool Running ;
[HideInInspector]
public bool Walking;
[HideInInspector]
public bool canRun;
[HideInInspector]
public Vector3 rorationDir;

//Ladder variables
private GameObject mainCamera = null;
[HideInInspector]
public bool onLadder = false;
//private float ladderHopSpeed = 6.0f;

// For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!

// The current global direction we want the character to move in.
[System.NonSerialized]
public Vector3 inputMoveDirection = Vector3.zero;

// Is the jump button held down? We use this interface instead of checking
// for the jump button directly so this script can also be used by AIs.
[System.NonSerialized]
public bool inputJump = false;

[HideInInspector]
public bool inputRun = false;

[HideInInspector]
public bool inputCrouch = false;

[HideInInspector]
public bool inputProne = false;

[System.Serializable]
public class  FPScontrollerMovement {
    // The maximum horizontal speed when moving
    [HideInInspector]
    public float maxForwardSpeed = 10.0f;
    [HideInInspector]
    public float maxSidewaysSpeed = 10.0f;
    [HideInInspector]
    public float maxBackwardsSpeed = 10.0f;

    //Run and walk variables
    public float WalkSpeed = 6.0f;
    public float RunSpeed = 9.0f;
    //Crouch
    public bool canCrouch = true;
    public float CrouchSpeed = 3.0f;
    public float crouchHeight = 1.5f;
    public float crouchSmooth = 8;
    //prone
    public bool canProne = true;
    public float ProneSpeed = 1.5f;
    public float proneHeight = 0.7f;

    // Curve for multiplying speed based on slope (negative = downwards)
    public AnimationCurve slopeSpeedMultiplier = new AnimationCurve(new Keyframe(-90, 1), new Keyframe(0, 1), new Keyframe(90, 0));

    // How fast does the character change speeds?  Higher is faster.
    public float maxGroundAcceleration = 30.0f;
    public float maxAirAcceleration = 20.0f;

    // The gravity for the character
    public float gravity = 10.0f;
    public float maxFallSpeed = 20.0f;

    [HideInInspector]
    public bool enableGravity = true;

    // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
    // Very handy for organization!

    // The last collision flags returned from controller.Move
    [System.NonSerialized]
    public CollisionFlags collisionFlags;

    // We will keep track of the character's current velocity,
    [System.NonSerialized]
    public Vector3 velocity;

    // This keeps track of our current velocity while we're not grounded
    [System.NonSerialized]
    public Vector3 frameVelocity = Vector3.zero;

    [System.NonSerialized]
    public Vector3 hitPoint = Vector3.zero;

    [System.NonSerialized]
    public Vector3 lastHitPoint = new Vector3(Mathf.Infinity, 0, 0);
}
public FPScontrollerMovement movement = new FPScontrollerMovement();

    void Awake () {
    if (GetComponent<NetworkView> ().isMine) {

    joystick = GameObject.Find ("Joystick");
    controller = gameObject.GetComponent<CharacterController>();
    standartHeight = controller.height;
    /*if(GameObject.FindWithTag("LookObject") != null){
        lookObj = GameObject.FindWithTag("LookObject");
    }*/
    centerY = controller.center.y;
    tr = transform;

    canRun = true;
    canStand = true;
    StartCoroutine(setupBools());

    }
}

    void Update () {
    if (GetComponent<NetworkView> ().isMine) {
        if (!useFixedUpdate) {
            UpdateFunction ();
        }

        movement.velocity.x = joystick.GetComponent<VirtualJoystick> ().Horizontal () * 5f;
        movement.velocity.z = joystick.GetComponent<VirtualJoystick> ().Vertical () * 5f;

        //Run input
        if (Input.GetAxis ("Vertical") > 0.1f && inputRun && canRun && !onLadder && Walking) {
            if (canStand && canStandCrouch) {
                OnRunning ();
            }
        } else {
            OffRunning ();
        }

        //Check when walk or not
        if ((movement.velocity.x > 0.01f  || movement.velocity.z > 0.01f) || (movement.velocity.x < -0.01f || movement.velocity.z < -0.01f)) {
            RunAnimation1 ();
            Debug.Log ("Forward");
            Walking = true;
        }else if (movement.velocity.x > 0.01f) {
            Walking = true;
            Debug.Log ("Right");
        } else if (movement.velocity.x < -0.01f) {
            Walking = true;
            Debug.Log ("Left");
        } else {
            RunAnimation ();
            Walking = false;
        }

        if (!canControl)
            return;

        if (movement.canCrouch) {
            if (!onLadder) {
                Crouch ();
            }
        }

        if (movement.canProne) {
            if (!onLadder) {
                Prone ();
            }
        }

        if (onLadder) {
            grounded = false;
            crouch = false;
            prone = false;
        }

        if (!crouch && !prone && controller.height < standartHeight - 0.01f) {
            controller.height = Mathf.Lerp (controller.height, standartHeight, Time.deltaTime / movement.crouchSmooth);
            controller.center = new Vector3 (controller.center.x, Mathf.Lerp (controller.center.y, centerY, Time.deltaTime / movement.crouchSmooth), controller.center.z);
            lookObj.transform.localPosition = new Vector3 (lookObj.transform.localPosition.x, Mathf.Lerp (lookObj.transform.localPosition.y, standartHeight, Time.deltaTime / movement.crouchSmooth), lookObj.transform.localPosition.z);
        }
    }
}

void RunAnimation(){
    GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 0);
}
void RunAnimation1(){
    GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 1);
}
void RunAnimation2(){
    GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 2);
}

[RPC]
void SysnAnimation(int index){
    if (index == 0) {
        GetComponent<Animator> ().Play ("Idle Aim");
    } else if (index == 1) {
        GetComponent<Animator> ().Play ("Walk Aiming");
    } else if (index == 2) {
        GetComponent<Animator> ().Play ("Jump");
    }
}

 void OnRunning (){
    Debug.Log ("Run");
    Running = true;
    movement.maxForwardSpeed = movement.RunSpeed;
    movement.maxSidewaysSpeed = movement.RunSpeed;
    //Make bigger extra height when player run to increase jump distance
    jumping.extraHeight = jumping.baseHeight + 0.15f;
}

void OffRunning (){
    Running = false;
    if(crouch || prone)
        return;
    movement.maxForwardSpeed = movement.WalkSpeed;
    movement.maxSidewaysSpeed = movement.WalkSpeed;
    movement.maxBackwardsSpeed = movement.WalkSpeed/2;
    //Change extraheight value to default when player walk
    jumping.extraHeight = jumping.baseHeight;
}}

```

# That is my joystick Script

```
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler,IPointerDownHandler {

private Image bgImg;
private Image JoyStickImage;
private Vector3 InputVector;

private void Start(){
    bgImg = GetComponent<Image> ();
    JoyStickImage = transform.GetChild (0).GetComponent<Image> ();

}

public virtual void OnDrag(PointerEventData ped){
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle (bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos)) {
        pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
        pos.y = (pos.y / bgImg.rectTransform.sizeDelta.y);

        InputVector = new Vector3 (pos.x * 2 + 1, 0, pos.y * 2 - 1);
        InputVector = (InputVector.magnitude > 1) ? InputVector.normalized : InputVector;

        JoyStickImage.rectTransform.anchoredPosition = new Vector3 (InputVector.x * (bgImg.rectTransform.sizeDelta.x / 2.5f),
                                                                    InputVector.z * (bgImg.rectTransform.sizeDelta.y / 2.5f));

        Debug.Log (InputVector);
    }
}

public virtual void OnPointerDown(PointerEventData ped){

    OnDrag (ped);
}

public virtual void OnPointerUp(PointerEventData ped){

    InputVector = Vector3.zero;
    JoyStickImage.rectTransform.anchoredPosition = Vector3.zero;
}

public float Horizontal(){

    if (InputVector.x != 0)
        return InputVector.x;
    else
        return Input.GetAxis ("Horizontal");

}
public float Vertical(){

    if (InputVector.z != 0)
        return InputVector.z;
    else
        return Input.GetAxis ("Vertical");

}

```

# CameraRotate Script when touch to swipe

```
public class SwipeCam : MonoBehaviour {

private Vector3 firstPoint;
private Vector3 secondPoint;
private float xAngle = 0.0f;
private float yAngle = 0.0f;
private float xAngleTemp = 0.0f;
private float yAngleTemp = 0.0f;

void Start(){
    xAngle = 0.0f;
    yAngle = 0.0f;
    this.transform.rotation = Quaternion.Euler (yAngle, xAngle, 0.0f);

}

void Update(){

    if (Input.touchCount > 0) {

        for (int i = 0; i < Input.touchCount; i++) {

            Touch touch = Input.GetTouch (i);

            if (touch.position.x > Screen.width / 2) {

                if (touch.phase == TouchPhase.Began) {

                    firstPoint = Input.GetTouch (0).position;
                    xAngleTemp = xAngle;
                    yAngleTemp = yAngle;
                }
                if (touch.phase == TouchPhase.Moved) {
                    secondPoint = Input.GetTouch (0).position;

                    xAngle = xAngleTemp + (secondPoint.x - firstPoint.x) * 180.0f / Screen.width;
                    yAngle = yAngleTemp + (secondPoint.y - firstPoint.y) * 180.0f / -Screen.height;

                    yAngle = Mathf.Clamp (yAngle, -30f, 30f);

                    this.transform.rotation = Quaternion.Euler (yAngle, xAngle, 0.0f);
                    this.gameObject.GetComponentInParent<FPScontroller> ().transform.rotation = Quaternion.Euler (0.0f, xAngle, 0.0f);
                }

            }
        }
    }

}
}

```

When i Change the Code Don't Understand.

If anyone have understand then help me. Thanks in Advance.

# Answer
> 1 votes
Hello Friends i Solve the problem of my question as i say above player movement using joystick based on Camera Facing.

In my PlayerScript there is two line read joystick input is,

```
    movement.velocity.x = joystick.GetComponent<VirtualJoystick> ().Horizontal () * 5f;
    movement.velocity.z = joystick.GetComponent<VirtualJoystick> ().Vertical () * 5f;`

```

In this Line i modify little bit, as given below.

```
Vector3 DirectionVector =
            new Vector3 (joystick.GetComponent<VirtualJoystick> ().Horizontal (), 0f, joystick.GetComponent<VirtualJoystick> ().Vertical ());

        movement.velocity = transform.rotation * DirectionVector * 10f;

```

I am doing in previous code directly add joystick value in movement vector because of when time to movement that doesn't read player rotation, I just multiply it to the joystick input vector and solve my problem.

Now player move based on the player rotation and also when camera is facing. Thanks everyone for help.

# Answer
> 1 votes
Simply use this direction vector to move `Camera.main.transform.forward` \- gives local z axis in world space of main camera. Or another way - use player `transform.forward`. No need for fancy calculations.

---
Tags: unity, movement, multiplayer
---


# Question
Title: How does glfw handle input in terms of implementation?
GLFW is clearly an OpenGL framework, which means we are aming to work with graphics card initially. How input gets handled then? According to the docs, the input and window are just two main purpuses and that's just an implementation detail.

# Answer
First of all, GLFW is not a *OpenGL framework* but a *OpenGL applications framework*. It's basically a set of libraries and source files which facilitate you the task of build applications. This layer of abstraction allows you to write multi-platform applications without knowing *anything* of the Operative System API; you don't need to know how *Linux* manages keyboard events, just learn how *GLFW*.

To respond your question, keyboard, mouse, window... events are probably processed by the CPU, on the function call `glfwPollEvents()`. Callbacks may be added with the `glfwSetKeyCallback` function, as stated here. GLFW will maintain a *list* of functions (callbacks) to execute when the OS triggers an event.

To simplify the answer, GLFW will manage the following modules of your application (OS independent):

* **OpenGL**: OpenGL API management. Mostly processed by the GPU.
* **Window**: System window management (resize, resolution, etc). Processed by the GPU (rendering) and CPU (processing).
* **Events**: Events fired by the Operative System (keyboard events, mouse events, window events...). Mostly processed by the CPU.
> 2 votes

---
Tags: opengl, glfw
---


# Question
Title: How to correctly reference a texture bound using SetTexture in Direct3D 9
In Direct3D 9, after assigning a few textures to samplers using SetTexture, what is the correct way to access/create the samplers in the relevant pixel shader? Previously I was creating samplers like this:

```
texture tex : register(r0);
sampler2D sam = sampler_state {
    texture = <tex>;
    minfilter = none;
    magfilter = none;
    mipfilter = none;
};

```

Which seemed to work fine, however, now that I'm binding multiple textures this doesn't work consistently. However, the following *appears* to work:

```
sampler2D sam : register(s0);
sampler2D sam1 : register(s1);

```

The documentation for SetTexture says:

> Programmable shaders reference textures using the sampler number.

But I'm not sure whether or not this means that the sampler registers should be used to sample textures set with SetTexture, or whether the sampler requires any further initialisation aside from the call to SetTexture.

# Answer
In Direct3D 9 HLSL all you need to declare is the sampler; you do not need to declare the texture at all.

So:

```
sampler sam0: register(s0); // s0 = sampler register 0

```

To bind the texture use:

```
device->SetTexture (0, tex); // 0 is the sampler register number

```

And to sample it use:

```
tex2D (sam0, coords); // sample using the sampler declared above

```

Setting a sampler state at declaration time (via the "`= sampler_state {...}`" syntax) is actually not part of HLSL at all; it's part of the Effects framework instead, which is a software library written by Microsoft and which abstracts some of the details of dealing with shaders.

You can add this code to regular HLSL but it will have no effect.

What you should do instead is use SetSamplerState calls to setup the sampler from the C/C++ side.

Direct3D 10+ is a lot more flexible in that it fully decouples samplers from textures, but Direct3D 9 doesn't have that flexibility.
> 0 votes

---
Tags: directx, hlsl, directx9
---


# Question
Title: With Monogame is it possible to await SoundEffect or SoundEffectInstance before playing another SoundEffect or Song?
I am trying to do some proof of concept work using Monogame, mostly for my own knowledge. One thing I am having trouble with, however, is timing sounds effects and background music to my liking.

So in my scenario I would like to play a series of `SoundEffect` objects when the game first loads, and when those effects have finished, play a `Song` in the background until the game is finished. When either the player or computer meets victory conditions the game will end, which involves stopping the background `Song`, playing a win/lose `SoundEffect`, and loading the end screen.

Here's where I started:

```
var open0 = Content.Load<SoundEffect>("Open0");
var open1 = Content.Load<SoundEffect>("Open1");
open0.Play();
open1.Play();
bgMusic = Content.Load<Song>("BGTrack");
MediaPlayer.Play(bgMusic);
MediaPlayer.IsRepeating = true;
MediaPlayer.Volume = 0.25f;

```

This approach ends up just playing all three items simultaneously. Its more noise than good game experience.

I also tried moving the `Play()` method calls into an `async` method and using `await` on the threads, but of course `Play()` doesn't return `Task` so that didn't work. Likewise, `SoundEffectInstance` and `DynamicSoundEffectInstance` don't seem to offer any kind of awaitable method calls, unless I'm missing them.

I also tried wrapping subsequent calls in a `while` loop, using the `SoundEffectInstance.State` property as my logic control:

```
var open0 = Content.Load<SoundEffect>("Open0");
var open1 = Content.Load<SoundEffect>("Open1");
SoundEffectInstance open0Instance = open0.CreateInstance();
SoundEffectInstance open1Instance = open1.CreateInstance();

open0Instance.Play();
while (open0Instance.State != SoundState.Playing)
    open1Instance.Play();

while (open0Instance.State != SoundState.Playing &&
        open1Instance.State != SoundState.Playing)
{
    bgMusic = Content.Load<Song>("BGTrack");
    MediaPlayer.Play(bgMusic);
    MediaPlayer.IsRepeating = true;
    MediaPlayer.Volume = 0.25f;
}

```

Ugly code, but I was trying to figure out what would work...and this didn't. The first sound played and nothing else, so I'm guessing the `State` property doesn't implement `INotifyPropertyChanged` (although I'm not even sure that's relevant outside of MVVM now that I think about it).

The sounds at the end of the game are not giving me trouble because I can simply stop the `MediaPlayer` and play my closing Effect:

```
MediaPlayer.Stop();
gameObjects.PlayerWinEffect.Play(1.0f, 0.0f, 0.0f);

```

So is there a way to control `SoundEffect` and `MediaPlayer` timing more explicitly?

# Answer
> 1 votes
As far as I can tell, there is no way to explicitly wait on `SoundEffect` or `SoundEffectInstance`, aside from pooling.

What you are gonna do is check on each call to `Update`. You do not need to use a while loop, because the system will call `Update` for you.

Place these as members of your game class:

```
SoundEffectInstance open0Instance;
SoundEffectInstance open1Instance;
Song bgMusic;
int state;

```

Place these lines in `LoadContent`:

```
var open0 = Content.Load<SoundEffect>("Open0");
var open1 = Content.Load<SoundEffect>("Open1");
bgMusic = Content.Load<Song>("BGTrack");
open0Instance = open0.CreateInstance();
open1Instance = open1.CreateInstance();
state = 0;

```

Place these lines in `Update`:

```
switch (state)
{
    case 0:
        open0Instance.Play();
        state = 1;
        break;
    case 1:
        if (open0Instance.State == SoundState.Stopped)
        {
            open1Instance.Play();
            state = 2;
        }
        break;
    case 2:
        if (open1Instance.State == SoundState.Stopped)
        {
            MediaPlayer.Play(bgMusic);
            MediaPlayer.IsRepeating = true;
            MediaPlayer.Volume = 0.25f;
            state = 3;
        }
        break;
     default:
        break;
}

```

Place these lines in `UnloadContent`:

```
open0Instance.Dispose();
open1Instance.Dispose();
bgMusic.Dispose();

```

---

Ok, why does that work? First off, Monogame will call `Update` repeatedly, so you don't have the need to create a loop. Second, what we are doing is an state machine... using the field `state` to keep track of the progress we are doing we know what to check and to do next. Finally, I'm showing you the appropiate code to unload the resources.

Now, let's go on the switch step by step...

At the start `state = 0`, that is the default value (and we have also set it in `LoadContent`, just for convinience). So, the flow of execution enters here:

```
case 0:
    open0Instance.Play();
    state = 1;
    break;

```

That will set the first sound effect to play, and update the `state` to 1. Since `state` is now 1... the next time MonoGame calls `Update`, it will enter here:

```
case 1:
    if (open0Instance.State == SoundState.Stopped)
    {
        open1Instance.Play();
        state = 2;
    }
    break;

```

Here, we check if the sound effect we set to play have stopped... if it hasn't we do nothing. MonoGame will continue calling `Update`, until, eventually the condition evaluates to true, meaning that the sound effect has stopped playing. We proceed to play the second sound effect and set the `state` to 2. Since `state` is now 2... the next time MonoGame calls `Update`, it will enter here:

```
case 2:
    if (open1Instance.State == SoundState.Stopped)
    {
        MediaPlayer.Play(bgMusic);
        MediaPlayer.IsRepeating = true;
        MediaPlayer.Volume = 0.25f;
        state = 3;
    }
    break;

```

Similarly to the prior case, we check if the sound effect we set to play have stoppd... once it have, the flow of execution enters the conditional, at which point we start playing the background music and set `state` to 3. Since `state` is now 3... the next time MonoGame calls `Update`, it will enter here:

```
default:
        break;

```

That does nothing.

---

Alternatively consider using the sound effects as songs. Btw, dispose your `SoundEffectInstance`. When using `MediaPlayer`, you can subscribe to the event `MediaStateChanged` of it, you should get a notification when the song stoped playing (verify the state). You might want to use a ManualResetEventSlim which you `Set` in the event handler, so you can `Wait` for it.

Another thing that may come handy is `SpinWait.SpinUntil`.

---
Tags: c#, monogame, sound-effects
---


title: Running Slick2d outside of the IDE

text:
# Question
Title: Running Slick2d outside of the IDE
I am looking for advice how to solve an exception I am getting,

I've looked around and seen people get the same error but most people whom had it seems to run on old graphics drivers and once they fixed that it seemed to work for most people.

I doubt that's the reason causing it for me since I have the latest nVidia drivers and the game runs well from the IDE. I also did create a jar of the game before I implemented Slick2d and that ran without exceptions.

I used to get another exception, that it couldn't find the right natives for lwjgl so I removed the natives from the build and made a fat jar with jarsplice and added them during that process and that's when I ended up at this point.

I've tried and tried for days and it's probably something really stupid and easy to fix but I havn't built a lot of project to be ran from outside Eclipse so any help would be greatly appreciated.

Some basic info on my rig:

OS: Windows 7: Enterprise

CPU: Intel Core i7-2600K

GPU: nVidia GTX 980

RAM: 8192MB (forgot the brand and make, it's old lol)

# Answer
For anybody who has this issue in the future, slicks Image class can't be initialized pointing to an image in a jar in a straight forward kind of way.

Just move them outside to the jar directory and call them with something like

```
    Image img;

public static void main(String[] args) throws URISyntaxException {
    CodeSource codeSource = Board.class.getProtectionDomain().getCodeSource();
    String sourceCoded = codeSource.getLocation().toURI().toString();
    try {
        sourceDecoded = java.net.URLDecoder.decode(sourceCoded, "UTF-8").substring(5);
        sourceDir = sourceDecoded.substring(0, sourceDecoded.lastIndexOf("/"));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
        img = new Image(Board.sourceDir+"/art/"+"specificImagePath.png");}

```
> 0 votes

# Answer
The first thing you should check is if the natives are in your class path and are up to date with the version of LWJGL you're using.

It's also possible that your graphics drivers are out of date, or your card doesn't support the version of OpenGL you're trying to initialize. Windows 10 is usually the culprit in this case:

Some versions of LWJGL can cause problems with newer JDK builds. Find out which JDK your version of LWJGL is built with. If you can't find that information, try building on JDK 7. If that doesn't work, try JDK 8.

Please let me know which, if any, solved your problem.

Thanks.
> 0 votes

---
Tags: opengl, java, slick, gpu, eclipse
---


title: Season Change Reveal Effect

text:
# Question
Title: Season Change Reveal Effect
I was watching the teaser trailer for Seasons After Fall, and I was struck by the effect they use to transition between seasons (around 21-24 seconds):

The level art, including the background and the foreground platforms, change from a sepia-coloured autumn to a lavender winter, with the effect spreading outward from the player character a bit like water soaking through paper.

It looks like more than just a palette change, as details in the leaf and bark patterns change in the transition.

How could I achieve an effect similar to this in a 2D Unity game?

# Answer
> 12 votes
One way to accomplish this would be to blend between the two backgrounds using an alpha map. A simple approach would be to render the "back" (hidden) background, and then the "front" (initially-visible) background. Use the alpha channel of the front background, or a separate alpha texture, to control the transparency of the front background as you would any transparent or translucent sprite. Where this alpha map is less than one, parts of the back background will show through.

Then it's just a matter of building that alpha map according to the effect you'd like. In the video you show off, it looks like such a map was built with a "painterly" kind of approach. This might involve randomly placing circles of zero alpha (that feather off to 1.0 alpha around their edges). Start placing these circles tightly biased around the origin of the reveal, and over time relax the bias so they spread outward. As you do this you'll probably want to expand the radius of the circles as well.

You can tweak this approach as you need it to tailor the effect to your desires; plain circles might end up looking a little too "blotchy" for example, and you might instead want to randomly stamp a randomly-selected pre-authored "brush stroke" into the mask instead. Even random placement itself might look a little too disorderly, and you might instead opt for stamping the alpha mask along some pre-authored curve or spline to highlight a particular style.

# Answer
> 7 votes
I'd approach this using a custom shader on my SpriteRenderers that takes two textures, one for each version you want to transition between.

(Even if using this effect to transition between more than two states, I'd still try to structure the game so we only need two for rendering at any one time: the old state and the next state. We'll let that transition play to completion before we let the player initiate a transition to a third state, at which point we can replace our previous "old" state since it's no longer visible)

This shader would cross-fade between the two textures, using a third single-channel texture as a mask for the effect (eg. black = 100% old state, grey = 50/50 blend, white = 100% new state). I'd map this mask texture in screenspace.

Then I'd set up a second camera to render to a RenderTexture, to generate this mask. This second camera would move with my main camera and match its FoV/orthographic size, so any animation in my view applies to both the world and reveal mask consistently. This camera would render before my main camera, and be set up to see only content on a specially-designated "reveal" layer. In the video example, it looks like they use a particle system to splat-out a collection of little cloud shapes into this reveal texture, which expand over time, giving the transition an organic-looking spreading edge.

---
Tags: unity, effect
---


# Question
Title: Combining varying vertex variable and vertex variable in OpenGL. How to?
Let's say I have 2 triangles sharing an edge defined by 4 vertices. Though the normals for these 2 triangles are unique for each triangle and are defined per vertex. So say I have 4 vertices, 6 normals (as shown in the figure below).

I would like to know how this can be dealt with in OpenGL? I have been using `glDrawElement` so far, but I understand that this would only work if I had 4 normals (1 normal per vertex) and this it wouldn't allow me to define 3 normals per triangle.

What's the best/common/most efficient of dealing with this case? Do I need to also duplicate the vertices (3 unique vertices per triangle or is there a more clever solution to this?) so that I have as many vertices than I have normals?

# Answer
Yes, you do need to duplicate vertices.

Oftentimes this is required by normals. Another often reason - UV maps, Surfaces.

I come to think of vertices not as points in 3D space, but as "unique set of properties" placed in 3D space. These "sets" often take the same space, but lines and triangles using them - each take their "sets".
> 2 votes

---
Tags: opengl, vertex-arrays, vertex-attribute
---


title: Unity: material has shiny white outline

text:
# Question
Title: Unity: material has shiny white outline
I have two different projects open in Unity. But my grass material appears different in each project, despite all the parameters being the same.

See this image:

On the left is the desired appearance. But on the right my material has a strange white-ish outline. How do I get rid of it?

I have tried copying the material between the projects, and the problem seems to be independent of the available lighting

# Answer
Try to re-import your assets and shaders. Like *DMGregory* mentioned in the comments, try deleting your Library.

Make sure the lighting effects are the same in both the projects.
> 1 votes

---
Tags: unity, materials
---


title: Unity. Draw mesh without a mesh class

text:
# Question
Title: Unity. Draw mesh without a mesh class
Is there a way to draw an array of vertices/traingles directly from code, above 65k verts? I looked at Graphics class but it can only render a Mesh object.

# Answer
> 5 votes
Yes. I'll go through different methods on drawing with unity to explain them a little bit.

Drawing meshes larger than 65k vertices requires you to split the mesh in multiple pieces. There is no way around that in Unity. The 65k limit comes from the hard coded index buffer being 16 bit unsigned integer type. The maximum 16 bit integer value is 65536 and Unity has hard limited the value to that.

If you want to dynamically draw shapes that change all the time, you have to modify the mesh data every frame. Also whenever you want to draw generated meshes, you need to use the mesh class. There are faster and slower ways to do that, but that's outside the scope of this question. The basic way to do that is to have some arrays of different vertex data and then set all that to the unity Mesh data. A basic example:

```
Mesh mesh; // Generated somewhere

public void UploadMesh(Vector3[] pos, Vector3[] norm, Vector2[] uv, int[] indices)
{
    mesh.vertices = pos;
    mesh.normals = norm;
    mesh.uv = uv;
    mesh.triangles = indices;
    // Now when the mesh is drawn the next time, the data gets uploaded to the GPU memory
    // If you want the data to be uploaded immediately, uncomment the next line:
    //Mesh.UploadMeshData(true); // True means the CPU-memory of the mesh data is cleared, making the mesh data not readable any more
}

```

In this case you first have the vertices stored in managed memory and transfer them to the unmanaged memory of Unity by assigning them to the properties of the mesh object. When the mesh is drawn or `UploadMeshData()` gets called the data is transferred from the unmanaged memory to GPU memory. This is how I have seen Unity to work previously and by design it seems the mesh data gets stored twice in the CPU memory if you are keeping it in managed memory for speed reasons.

You can also get a native GPU memory pointers for the mesh by calling Mesh.GetNativeIndexBufferPtr and Mesh.GetNativeVertexBufferPtr, and upload the vertices to the GPU by hand, but that is very advanced and generally not needed feature. Usually this is used for large and frequently (like, every frame) changing meshes, like Sprites or particles. Uploading the vertex data to the GPU memory this way skips the memory being transferred to unmanaged side of Unity. This does not help with the 65k vertex limit.

In older deprecated version of OpenGL (I'm not sure about DirectX, never used it that much) you could send vertices to the GPU one by one. This was very slow and horrible way to draw stuff on screen and is nowdays used mostly just for backwards compatibility and not used at all in "newer" (10+years old) engines. It was called immediate mode. This was replaced by vertex arrays; mesh data stored in GPU memory. A mesh object in unity and in multiple other engines is a wrapper for GPU memory block holding the vertex data used for drawing your meshes. That's why it exists.

To draw without the mesh class you need to use the low-level GL API of Unity to do that. Note that as the manual says, using meshes is in almost all cases more efficient than using the low-level immediate mode and thus not recommended. Also note that this old immediate mode behaviour is just emulated and it does not actually work as it used to work in the older OpenGL implementations. There is an example in the manual page of GL API I linked. I am not sure if this helps with the 65k vertex limit, but I would assume so. I have never used this method myself as it is the least performant way to draw things on screen.

In addition to that, you could always write your own plug-in to use the graphics context by yourself, but that's a lot more work. You are usually better off using Graphics class to draw commands or CommandBuffer.

---
Tags: unity, graphics, rendering
---


title: How do I fake 3d?

text:
# Question
Title: How do I fake 3d?
I'm trying to make a first person, pseudo-3D game similar to those of the '80s, where you walk around on a grid, and where all the walls can be the same height. Generally speaking, how would I create a 3D effect like this without actually making the game 3D?

Example: The original Might and Magic.

# Answer
One way to do this is to have each possible wall element drawn (offline, ie., at compile-time) in perspective and stored as an image. Your grid then needs to store for each cell which sides of the cell have which wall type (if any). Since you're presumably not handling any depth information, you can simply use the painter's algorithm to draw all walls from the furthest to the closest. Here, "drawing" means: selecting the correct image containing the wall element in perspective and blitting it to the screen.

For instance, in order to draw the following grid:

you would use the following wall images (here aggregated into a single texture sheet):

(Note that this sheet is not complete: for instance, the third wall element has no right-hand counterpart. In order to draw arbitrary scenes, you would have to have *all* possible wall elements available.)

Note that special items such as the torch would probably be separate images drawn on top of empty wall images at run time, unlike in the crude example I'm presenting here.
> 2 votes

# Answer
You're probably looking for raycasting. It can fake 3D with a 2D array of numbers and generate walls of all the same width/depth/height (giant blocks), but with different textures depending on what the number is. To actually do the raycasting, if you're using a game engine such as Unity, it might have built-in raycasting functions otherwise I would recommend using a library for it. At the player's 2D position you then send out a raycast from the player to where he's looking (think like this is a 2D top-down game, because it technically is) and then (usually) software render the wall bigger or smaller based on the distance.

See: http://lodev.org/cgtutor/raycasting.html
> 0 votes

---
Tags: 3d, grid
---


title: unity 5.x performance

text:
# Question
Title: unity 5.x performance
After I downloaded unity 5, it became very power consuming. For example, my pc becomes hotter and makes a lot of noise. Also building, compiling, baking of game takes a lot of time. I am making a multiplayer game and need to build the game almost on every change, but it takes hours or sometimes it doesn't even build the game. There are also bugs with directional light, it doesn't work. So yeah, any suggestions?

My internal PC specs: **Intel core i3-3130M, 8gb of ram, video card: Intel R4000**

I installed unity 5 after Windows 10 came out, maybe it's something with the OS? Also yesterday, I updated Unity but with the same problems.

*Also here are some screens:*

**Directional light is turned off but everything except models is dark, i mean terrain is black.**

**Also this baking process is more than one hour and stays on** *5/11 clustering | 41 jobs*

# Answer
Go to Lighting tab beside Inspector tab. Under Precomputed GI make the value of Realtime resolution to 0.02 (lower than default). It will reduce bake time. It won't look good but will work fine.

You can keep auto bake off after that baking done. Better CPU will help reducing time. Dedicated graphics card helps working Unity 5 better.
> 4 votes

# Answer
The issues reported describe the "infinite clustering" bug. We have a much better name for it, in my team, but it is not appropriate for this format.

The "infinite clustering" issue appears to be a common occurrence, in Unity. I have ran into the problem many times; in many cases, found online , this is resolved as being a bug. This problem can lead to severe performance issues, on lower-speced computers; it can also lead to difficulties, when building, as the "infinite clustering" may need to complete before your project will build.

---

I have found two general "fixes", neither of which require changing your lighting settings to have adverse impact on your scene:

### Clean the GI Cache

Cleaning the GI Cache *can* fix this problem. I find it far less reliable, but it is also far more accessible.

Go to *Edit \> Preferences* and select *"GI Cache"* from the left tabs. From this window, simply select *"Clear GI Cache"*. With any luck, this will solve your problem.

### Replace the "problem meshes"

At the end of the day, this problem appears to be caused by particular meshes, in your scene. The closest speculation I can give is that it relates to the way the `MeshFilter` object handles it's `mesh` and `sharedMesh` properties; the "problem meshes" have always been duplicates of "no-problem meshes", in my projects.

I resolve this problem by simply working out *which* meshes are causing Unity to cluster. The message tells you how many there are; it is the amount of *jobs*. In the above case, there are 41 jobs, so there would be 41 problem meshes. Finding the meshes *can* be tedious. The only method to reliably identify them, as I have found, is very procedural. You *might* prefer to reduce the lighting, such as in *SP's* answer; if you favor quality, the extra work is worth it.

Start by creating a new empty game object. This will be your "safe" folder, so to speak. Name it "safe", to help you organise your objects with greater ease. With your "safe" object created, select all of your other objects, and disable them. You should notice that Unity is no longer clustering. As you re-enable individual game objects, the "problem objects" will trigger the clustering, again. If the objects do not, move them to your safe folder. If they do, disable them, and leave them aside. You may even want to make an "unsafe" game object, to house these objects as you do the "safe" objects.

Eventually, you will be left with a select group of "unsafe" objects that all trigger clustering. Simply recreate these objects. The new objects should be free from clustering, allowing you to delete the "unsafe" objects, and carry on with greater ease.

Some final tips, in regards to this process:

1. Enable parent objects, first. If they do not trigger clustering, all game objects inside are safe, and you can freely move the parent object to the "safe" game object.
2. If a parent object triggers clustering, it may very well be the children. Complete the same process, moving further into the parent game object hierarchy. If the "problem objects" are few, it may be worth disabling them but moving the entire object into the safe folder. You will have to remember to come back and fix these objects, as without being in the "unsafe" game object, they will not be as easily listed as the other "problem objects".
3. If you identify a "problem object", look to see if you have any duplicates of that object, in your scene. It is very likely that any duplicates of your "problem object" will also cause this issue, so this may help you identify the other "problem objects" more quickly.
4. In regards to recreating duplicated objects, *try* duplicating the new object to replace the others. In my experience, this does not necessarily cause clustering, and you can tell straight away.
> 1 votes

---
Tags: unity, performance
---


# Question
Title: Effect version is unrecognized. This runtime supports fx_5_0 to fx_5_0
I'm reading the "Introduction to 3D game programming with DirectX11" (Frank Luna) and i'm having problems with lighting. I have this error: Effect version is unrecognized. This runtime supports fx\_5\_0 to fx\_5\_0. When i use the D3DX11CreateEffectFromMemory function i have that error and an exception (this-\>mFX was nullptr) Can you help me? Thanks EDIT: I have no D3DCompileFromFile

```
std::ifstream fin("Ligthing.fx", std::ios::binary);
        ///
        fin.seekg(0, std::ios_base::end);
        int size = (int)fin.tellg();
        fin.seekg(0, std::ios_base::beg);
        std::vector<char> compiledShader(size);

        fin.read(&compiledShader[0], size);
        fin.close();
        hr=D3DX11CreateEffectFromMemory(&compiledShader[0], size, //ERROR IS HERE
            0, device, &mFX);

        if (FAILED(hr)) {
            MessageBox(0, L"err", 0, 0);
        }

```

# Answer
> 1 votes
You should use the latest version of *Effects for Direct3D 11* which is available on GitHub. It includes `D3DX11CreateEffectFromFile` which is for creating an effect from a compiled effect file (aka `fxo`), and `D3DX11CompileEffectFromFile` which is for creating an effect from a shader that is first compiled at runtime (aka `fx`).

> See this post for some history of Effects for Direct3D 11

The older version of Effects for Direct3D 11 in the legacy DirectX SDK was a bit purist about forcing the developer to deal with the binary file loading and interop with D3DCompile. I just added the missing utility functions to the library instead when I moved it to GitHub.

> Be sure to read Is Effects 11 deprecated? and What's the difference between an .fx and .hlsl file anyhow? as well for the status of FX11.

# Answer
> -1 votes
So the problem was in the "Lighting.fx". Had to compile it, so it became "Lighting.fxo". I didn't compile it by myself, i used the one provided by the book i'm reading which is "Intruduction to 3d game porgramming with DirectX 11" (Frank Luna)

---
Tags: directx11, lighting, c++
---


# Question
Title: Unity : callbacks in component based design
I am trying to use component based design in Unity3d v5. If I have 2 separate C# scripts attached to enemy ships like below:

1. Script1.shipDead() - Remove game object and show explosion animation
2. Script2.showPoints() - Destroyed ship shows points ex: +100 (later this will fade away)

How can I perform showPoints() function after shipDead() function has been performed, as a callback?

I can't put both actions in the same function, as some enemies will not have points. Some enemies will leave power ups/ small enemies/ bombs after being destroyed.

And I don't want to duplicated the same code in 4 functions.

Like :

1. function 1: destroy ship (nothing more)
2. function 2: destroy ship + show points
3. function 3: destroy ship + spawn small enemies
4. function 4: destroy ship + show points + spawn bomb

(As you can see above, there are many different possibilities / combinations I can come up with)

I need to separate functions and isolate them to do individual tasks. As shipDead() will not do anything related to showPoints() or showPowerUp() functions.

My question is how can I perform functions sequentially? One after another, like a callback function?

Like this:

1. run Script1.DestroyShip() first;
2. after that run Script2.ShowPoints();
3. and finally run Script3.SpawnBomb();

Please provide a solution that will not violate the following:

1. Components needs to be reusable (I can drag and drop the scrip in to other enemies/ships)
2. Code shouldn't be duplicated
3. Loosely coupled (Lesser dependancies)

Please help me on this, Thanks in advance!

# Answer
I see two solutions to your questions.

1) Use the `SendMessage(string methodName)` function. It will call the given method on every components of the gameObject. (More info here: http://docs.unity3d.com/ScriptReference/Component.SendMessage.html).

Here is an example:

```
public class Script1 : MonoBehavior
{
    public void DestroyShip()
    {
        /* Destroy the ship here. */
        SendMessage("OnShipDestroyed");
    }
}

public class Script2 : MonoBehavior
{
    public void OnShipDestroyed()
    {
        this.ShowPoints();
    }

    public void ShowPoint()
    {
        /* Show points here. */
    }
}

```

2) Use .Net events. Receiver registers to an event triggered when the ship is destroyed. Here is an example as well:

```
public class Script1 : MonoBehavior
{
    public event System.EventHandler OnShipDestroyed;

    public void DestroyShip()
    {
        if (this.OnShipDestroyed != null)
        {
            this.OnShipDestroyed.Invoke(this, new System.EventArgs());
        }
    }
}

public class Script2 : MonoBehavior
{
    void Awake()
    {
        this.GetComponent<Script1>().OnShipDestroyed += OnShipDestroyed;
    }

    private void OnShipDestroyed
    {
        this.ShowPoint();
    }

    public void ShowPoint()
    {
        /* Show points here. */
    }
}

```

Note that this solution creates a dependency of Script2 to Script1.

Hope it helps.
> 1 votes

# Answer
I'm going to try and write some example code using delegates since I think they might do what you want. Code is mostly taken from the delegate section of MSDN

```
using UnityEngine;
using System.Collections;

namespace MyNamespace
{
    public class ShowPoints : MonoBehaviour
    {

        public void showPoitsn()
        {
            Debug.Log("ShowingPoints");
        }
    }
}

using UnityEngine;
using System.Collections;

namespace MyNamespace
{
    public class DestroyShip : MonoBehaviour
    {

        public void Destroy()
        {
            Debug.Log("ShipDestroyed");
        }
    }
}
using UnityEngine;
using System.Collections;

namespace MyNamespace
{
   public enum BehaviourType
    {
        JustDestroy,
        DestroyAndShowPoints,
        ShowPoints
    }
    public class DelegateHandler : MonoBehaviour
    {
        private DestroyShip dShip;
        private ShowPoints sPoints;
        public  BehaviourType type;
        delegate void MyDelegate();
        MyDelegate destroy, showPoints,c;
        void Start()
        {
            dShip = GetComponent<DestroyShip>();
            sPoints = GetComponent<ShowPoints>();

            destroy = new MyDelegate(dShip.Destroy);
            showPoints = new MyDelegate(sPoints.showPoitsn);

            ComposeDelegates();
        }
        //Now we need some logic to handle the composing of a new delegate that can invoke the functions depending on our cases

        void ComposeDelegates()
        {
           switch(type)
            {
                case BehaviourType.JustDestroy:
                    c = new MyDelegate(destroy);
                    break;
                case BehaviourType.DestroyAndShowPoints:
                    c = new MyDelegate(destroy + showPoints);
                    break;
                case BehaviourType.ShowPoints:
                    c = new MyDelegate(showPoints);
                    break;
            }

            c();

        }

    }
}

```

How this works is that you attach all the components to the gameObject and the select what type of behaviour you want from the DelegateHandler. In my opinion this covers your criteria and its easy to extend. Not sure about the dependancy criteria you have.
> 1 votes

# Answer
**Well here is the solution:** I'm not judging your approach, but it's not right obviously. You aren't following the SOLID principles of OOP. First one of them is S - Single Responsibility. Currently, your Script2 is doing operations that should not be there, he should not be responsible for giving any points to the player when something dies.

It's the responsibility of enemy to give you points for their death unless you collect these points like objects, but it's not the case right now. It always depends on the game. But in your case, it's easier to create a system when enemy gives you these points.

Now imagine this architecture - you have many types of enemies `Pirate`, `OrangePirate`, `BlackSailsPirate` \- every one of them has its own reward for being defeated. What you need to do is to create an `OnDeath`event. As I remember something like this `public Action OnDeath;` and also a method for every Enemy `Die()`, now that you have it just do in `Start()` `OnDeath += DeathReward;`. Call it in `Die() { if (health < 0) { OnDeath(); Destroy(gameobject);.......... } }`. - And do all this stuff in parent class `Enemy` (I hope you understand inheritance(OOP)). Also in `Enemy` create a `public virtual void DeathReward() { throw new NotImplementedException(); }` This will call an exception if you haven't implemented the method in your new enemy type.

Now when you create a new type of enemy - just inherit and implement this method by `public override void DeathReward() { "give 150 points and leave a bomb" }`. - It's the best approach I know. When you destroy an enemy - you, of course, have a method where you destroy it - just call `Die` there instead. I hope you have some kind of health system + `TakeDamage(uint quantity)` method where you check health.

Performance = much better than checking in switch or if. It's actually the best because everything computer does points to chunks of code in RAM.

Let me know if you didn't understand something, I will try to clarify it.
> 1 votes

---
Tags: unity, architecture, component-based
---


# Question
Title: More efficient way to implement Line of sight on a 2d grid with ray casting?
Consider a 2d grid of tiles, and an approximated sphere of coordinates - centered on the player - that represents line of sight. The goal is to block the line of sight beyond obstacles (ie walls).

It's relatively simple to determine if an individual cell in the sphere of sight is visible: cast a ray from the player to the target cell, using Bresenham's \- if one of the overlapping cells between the player and the target is an obstacle, the target cell is not visible.

Now, my first thought was to iterate through all grid cells in the line of sight - but this seems inefficient to me. For example, if the player is standing next to a wall, and you determine that the cell beyond the wall isn't visible, you can determine all cells on the ray after that won't be visible.

Also considered casting a ray to each cell along the perimeter of the sphere of sight, and iterating each cell along each ray - but then I'd be processing some cells more than once.

Is there a more efficient way to do this?

While iterating ~50 cells per turn is a relatively lightweight calculation, I'm going for speed - the goal is to be able to cycle a few turns per second on auto-play. So, the more efficient I can make this, the better.

# Answer
> 9 votes
Eric Lippert wrote a series of blog posts about using "shadow arcs" to only iterate over visible cells in linear time without having to search for obstacles in each cell's visibility check. The blog series is archived, but you can find some of it at Microsoft's MSDN blog archive or check the Internet Archive.

I've adapted the scanning logic and shown a simplified example below; see the function `scan_arc`. The core idea is to check all squares, starting from the close ones starting from `distance = 0` and ending at `distance >= SIGHT_RADIUS`.

Each time you encounter an open cell, you mark it as "visible". Whenever you encounter a block, you reduce the angle and recursively scan around the side of the block.

This function only increments the distance in one direction, so we can cover the entire 360 degrees by scanning 90 degrees in each of 4 cardinal directions. Click the Run Code Snippet button below to see it in action.

```
function scan_arc(distance, min, max, rotate) {
  // we're finished scanning either when the distance is too far
  // or when the angle between the two ends of the arc is 0
  if (distance >= SIGHT_RADIUS || min >= max) return;
  // iterate over all integers between min and max
  for (var i = Math.ceil(distance * min); i <= distance * max; i++) {
    // (distance, i) forms an offset from the player representing our current cell.
    // we rotate it by a multiple of 90 degrees so we can scan in 4 directions
    var x = player.x + rotate(distance, i)[0];
    var y = player.y + rotate(distance, i)[1];
    // if our line of sight is blocked,
    // recursively scan at depth + 1 to the side of the block.
    if (map.get(x, y) === BLOCK) {
      scan_arc(distance + 1, min, (i - 0.5) / distance, rotate);
      min = (i + 0.5) / distance;
    } else {
      // if the current cell is open, we mark it as visible
      map.set(x, y, VISIBLE);
    }
  }
  // when we finish scanning a row, continue by scanning the next row
  scan_arc(distance + 1, min, max, rotate);
}

class Map {
  constructor(N, pairs) {
    this.N = N;
    this.data = new Array(N).fill(0).map((x) => new Array(N).fill(0));
    for (var p of pairs)
      this.data[p[0]][p[1]] = 1;
    for(let i = 0; i < N; i++)
       for(let j = 0, tr = mapview.insertRow(); j < N; j++)
         tr.insertCell();
  }
  get(x, y) {
    if (x < 0 || y < 0 || x >= this.N || y >= this.N) return 0;
    return this.data[x][y];
  }
  set(x, y, val) {
    if (x < 0 || y < 0 || x >= this.N || y >= this.N) return;
    this.data[x][y] = val;
  }
  show() {
    for (let N = this.data.length, i = 0; i < N; i++)
      for (let j = 0; j < N; j++)
        mapview.rows[i].cells[j].className = "cell" + this.data[i][j];
  }
}
let SIGHT_RADIUS = 20,
  BLOCK = 1,
  VISIBLE = 2;
let map    = new Map(16, [[3, 3],[4, 3],[5, 3],[8, 7],[8, 5],[6, 9],[6, 10],[6, 11],[7, 11],[7, 10],[7, 9]])
let player = {x: 4, y: 5}
scan_arc(0, -1, 1, (x, y) => [x, y]);
scan_arc(0, -1, 1, (x, y) => [y, -x]);
scan_arc(0, -1, 1, (x, y) => [-x, -y]);
scan_arc(0, -1, 1, (x, y) => [-y, x]);
map.set(player.x, player.y, "player");
map.show()
```

```
td {
  width: 12px;
  height: 12px;
  border: 1px solid #999;
}

.cell0 {
  background: #999;
}

.cell1 {
  background: #66f;
}

.cellplayer {
  background: #fa6;
}
```

```
<table id=mapview></table>
```

# Answer
> 8 votes
I have implemented the algorithm suggested by Jimmy.

Video of the code in action here: https://youtu.be/lIlPfwlcbHo

```
/*
   What this code does:
      Rasterizes a single Field Of View octant on a grid, similar to the way
      FOV / shadowcasting is implemented in some roguelikes.
      Clips to bitmap
      Steps on pixel centers
      Optional attenuation
      Optional circle clip
      Optional lit blocking tiles

   To rasterize the entire FOV, call this in a loop with octant in range 0-7
   Inspired by http://blogs.msdn.com/b/ericlippert/archive/2011/12/12/shadowcasting-in-c-part-one.aspx
*/

static inline int Mini( int a, int b ) {
    return a < b ? a : b;
}

static inline int Maxi( int a, int b ) {
    return a > b ? a : b;
}

static inline int Clampi( int v, int min, int max ) {
    return Maxi( min, Mini( v, max ) );
}

typedef union c2_s {
    struct {
        int x, y;
    };
    int a[2];
} c2_t;

static const c2_t c2zero = { .a = { 0, 0 } };
static const c2_t c2one = { .a = { 1, 1 } };

static inline c2_t c2xy( int x, int y ) {
    c2_t c = { { x, y } };
    return c;
}

static inline c2_t c2Neg( c2_t c ) {
    return c2xy( -c.x, -c.y );
}

static inline c2_t c2Add( c2_t a, c2_t b ) {
    return c2xy( a.x + b.x, a.y + b.y );
}

static inline c2_t c2Sub( c2_t a, c2_t b ) {
    return c2xy( a.x - b.x, a.y - b.y );
}

static inline int c2Dot( c2_t a, c2_t b ) {
    return a.x * b.x + a.y * b.y;
}

static inline int c2CrossC( c2_t a, c2_t b ) {
    return a.x * b.y - a.y * b.x;
}

static inline c2_t c2Clamp( c2_t c, c2_t min, c2_t max ) {
    return c2xy( Clampi( c.x, min.x, max.x ), Clampi( c.y, min.y, max.y ) );
}

static inline c2_t c2Scale( c2_t a, int s ) {
    return c2xy( a.x * s, a.y * s );
}

void RasterizeFOVOctant( int originX, int originY,
                         int radius,
                         int bitmapWidth, int bitmapHeight,
                         int octant,
                         int skipAttenuation,
                         int skipClampToRadius,
                         int darkWalls,
                         const unsigned char *inBitmap,
                         unsigned char *outBitmap ) {
#define READ_PIXEL(c) inBitmap[(c).x+(c).y*bitmapWidth]
#define WRITE_PIXEL(c,color) outBitmap[(c).x+(c).y*bitmapWidth]=(color)
#define MAX_RAYS 64
#define ADD_RAY(c) {nextRays->rays[Mini(nextRays->numRays,MAX_RAYS-1)] = (c);nextRays->numRays++;}
#define IS_ON_MAP(c) ((c).x >= 0 && (c).x < bitmapWidth && (c).y >= 0 && (c).y < bitmapHeight)
    typedef struct {
        int numRays;
        c2_t rays[MAX_RAYS];
    } raysList_t;
    // keep these coupled like this
    static const const c2_t bases[] = {
        { { 1, 0  } }, { { 0, 1  } },
        { { 1, 0  } }, { { 0, -1 } },
        { { -1, 0 } }, { { 0, -1 } },
        { { -1, 0 } }, { { 0, 1  } },
        { { 0, 1  } }, { { -1, 0 } },
        { { 0, 1  } }, { { 1, 0  } },
        { { 0, -1 } }, { { 1, 0  } },
        { { 0, -1 } }, { { -1, 0 } },
    };
    c2_t e0 = bases[( octant * 2 + 0 ) & 15];
    c2_t e1 = bases[( octant * 2 + 1 ) & 15];
    raysList_t rayLists[2] = { {
        .numRays = 2,
        .rays = {
            c2xy( 1, 0 ),
            c2xy( 1, 1 ),
        },
    } };
    c2_t bitmapSize = c2xy( bitmapWidth, bitmapHeight );
    c2_t bitmapMax = c2Sub( bitmapSize, c2one );
    c2_t origin = c2Clamp( c2xy( originX, originY ), c2zero, bitmapMax );
    if ( READ_PIXEL( origin ) ) {
        WRITE_PIXEL( origin, 255 );
        return;
    }
    c2_t dmin = c2Neg( origin );
    c2_t dmax = c2Sub( bitmapMax, origin );
    int dmin0 = c2Dot( dmin, e0 );
    int dmax0 = c2Dot( dmax, e0 );
    int limit0 = Mini( radius, dmin0 > 0 ? dmin0 : dmax0 );
    int dmin1 = c2Dot( dmin, e1 );
    int dmax1 = c2Dot( dmax, e1 );
    int limit1 = Mini( radius, dmin1 > 0 ? dmin1 : dmax1 );
    c2_t ci = origin;
    for ( int i = 0; i <= limit0; i++ ) {
        int i2 = i * 2;
        raysList_t *currRays = &rayLists[( i + 0 ) & 1];
        raysList_t *nextRays = &rayLists[( i + 1 ) & 1];
        nextRays->numRays = 0;
        for ( int r = 0; r < currRays->numRays - 1; r += 2 ) {
            c2_t r0 = currRays->rays[r + 0];
            c2_t r1 = currRays->rays[r + 1];
            int inyr0 = ( i2 - 1 ) * r0.y / r0.x;
            int outyr0 = ( i2 + 1 ) * r0.y / r0.x;
            int inyr1 = ( i2 - 1 ) * r1.y / r1.x;
            int outyr1 = ( i2 + 1 ) * r1.y / r1.x;

            // every pixel with a center INSIDE the frustum is lit

            int starty = outyr0 + 1;
            if ( c2CrossC( r0, c2xy( i2, outyr0 ) ) < 0 ) {
                starty++;
            }
            starty /= 2;
            c2_t start = c2Add( ci, c2Scale( e1, starty ) );
            int endy = inyr1 + 1;
            if ( c2CrossC( r1, c2xy( i2, inyr1 + 1 ) ) > 0 ) {
                endy--;
            }
            endy /= 2;
            //c2_t end = c2Add( ci, c2Scale( e1, endy ) );
            {
                int y;
                c2_t p;
                int miny = starty;
                int maxy = Mini( endy, limit1 );
                for ( y = miny, p = start; y <= maxy; y++, p = c2Add( p, e1 ) ) {
                    WRITE_PIXEL( p, 255 );
                }
            }

            // push rays for the next column

            // correct the bounds first

            c2_t bounds0;
            c2_t bounds1;
            c2_t firstin = c2Add( ci, c2Scale( e1, ( inyr0 + 1 ) / 2 ) );
            c2_t firstout = c2Add( ci, c2Scale( e1, ( outyr0 + 1 ) / 2 ) );
            if ( ( IS_ON_MAP( firstin ) && ! READ_PIXEL( firstin ) )
                && ( IS_ON_MAP( firstout ) && ! READ_PIXEL( firstout ) ) ) {
                  bounds0 = r0;
            } else {
                int top = ( outyr0 + 1 ) / 2;
                int bottom = Mini( ( inyr1 + 1 ) / 2, limit1 );
                int y;
                c2_t p = c2Add( ci, c2Scale( e1, top ) );
                for ( y = top * 2; y <= bottom * 2; y += 2, p = c2Add( p, e1 ) ) {
                    if ( ! READ_PIXEL( p ) ) {
                        break;
                    }
                    // pixels that force ray corrections are lit too
                    WRITE_PIXEL( p, 255 );
                }
                bounds0 = c2xy( i2 - 1, y - 1 );
                inyr0 = ( i2 - 1 ) * bounds0.y / bounds0.x;
                outyr0 = ( i2 + 1 ) * bounds0.y / bounds0.x;
            }
            c2_t lastin = c2Add( ci, c2Scale( e1, ( inyr1 + 1 ) / 2 ) );
            c2_t lastout = c2Add( ci, c2Scale( e1, ( outyr1 + 1 ) / 2 ) );
            if ( ( IS_ON_MAP( lastin ) && ! READ_PIXEL( lastin ) )
                && ( IS_ON_MAP( lastout ) && ! READ_PIXEL( lastout ) ) ) {
                bounds1 = r1;
            } else {
                int top = ( outyr0 + 1 ) / 2;
                int bottom = Mini( ( inyr1 + 1 ) / 2, limit1 );
                int y;
                c2_t p = c2Add( ci, c2Scale( e1, bottom ) );
                for ( y = bottom * 2; y >= top * 2; y -= 2, p = c2Sub( p, e1 ) ) {
                    if ( ! READ_PIXEL( p ) ) {
                        break;
                    }
                    // pixels that force ray corrections are lit too
                    WRITE_PIXEL( p, 255 );
                }
                bounds1 = c2xy( i2 + 1, y + 1 );
                inyr1 = ( i2 - 1 ) * bounds1.y / bounds1.x;
                outyr1 = ( i2 + 1 ) * bounds1.y / bounds1.x;
            }

            // closed frustum - quit
            if ( c2CrossC( bounds0, bounds1 ) <= 0 ) {
                continue;
            }

            // push actual rays
            {
                ADD_RAY( bounds0 );
                int top = ( outyr0 + 1 ) / 2;
                int bottom = Mini( ( inyr1 + 1 ) / 2, limit1 );
                c2_t p = c2Add( ci, c2Scale( e1, top ) );
                int prevPixel = READ_PIXEL( p );
                for ( int y = top * 2; y <= bottom * 2; y += 2, p = c2Add( p, e1 ) ) {
                    int pixel = READ_PIXEL( p );
                    if ( prevPixel != pixel ) {
                        c2_t ray;
                        if ( pixel ) {
                            ray = c2xy( i2 + 1, y - 1 );
                        } else {
                            ray = c2xy( i2 - 1, y - 1 );
                        }
                        ADD_RAY( ray );
                    }
                    prevPixel = pixel;
                }
                ADD_RAY( bounds1 );
            }
        }
        ci = c2Add( ci, e0 );
    }

    if ( ! skipAttenuation ) {
        c2_t ci = origin;
        int rsq = radius * radius;
        for ( int i = 0; i <= limit0; i++ ) {
            c2_t p = ci;
            for ( int j = 0; j <= limit1; j++ ) {
                c2_t d = c2Sub( p, origin );
                int dsq = c2Dot( d, d );
                int mod = 255 - Mini( dsq * 255 / rsq, 255 );
                int lit = !! outBitmap[p.x + p.y * bitmapWidth];
                WRITE_PIXEL( p, mod * lit );
                p = c2Add( p, e1 );
            }
            ci = c2Add( ci, e0 );
        }
    } else if ( ! skipClampToRadius ) {
        c2_t ci = origin;
        int rsq = radius * radius;
        for ( int i = 0; i <= limit0; i++ ) {
            c2_t p = ci;
            for ( int j = 0; j <= limit1; j++ ) {
                c2_t d = c2Sub( p, origin );
                if ( c2Dot( d, d ) > rsq ) {
                    WRITE_PIXEL( p, 0 );
                }
                p = c2Add( p, e1 );
            }
            ci = c2Add( ci, e0 );
        }
    }

    if ( darkWalls ) {
        c2_t ci = origin;
        for ( int i = 0; i <= limit0; i++ ) {
            c2_t p = ci;
            for ( int j = 0; j <= limit1; j++ ) {
                if ( READ_PIXEL( p ) ) {
                    WRITE_PIXEL( p, 0 );
                }
                p = c2Add( p, e1 );
            }
            ci = c2Add( ci, e0 );
        }
    }
}

```

---
Tags: 2d, grid, raycasting, line-of-sight
---


title: Unity Diablo style Multiplayer

text:
# Question
Title: Unity Diablo style Multiplayer
Good time of the day to everyone who is reading this topic.

I've been enjoying playing Diablo 3 and decided to try myself in game development (to lure my friends into Diablo 3 and to, ofcourse, practice in game development).

I'd like to split the question in to following sections:

1. Lobby System (using Unet)
2. Game Server
3. Scene Loading

**So, lets start with the first part:**
As far as i know, when user decided to play the multiplayer part of the game, he is either creating new game for others to join, or joining an existing game. This process can be observed on the "Joining/Creating Game" screen.

What i'm actually can't figure out, is that if the game created on the users machine (lets name it local) or the Blizzard server (this will be remote). If it is created on the local machine, how then it is protects itself from cheating. If it is created on the remote machine, does that mean that for every 5 (just any number) players, i will have to start new copy of the game server (probably on the different port)

**Moving to the second question:**
This requires to run a "headless" version of the game on the server. Is there a possibility to create many different rooms for many players by using only one server instance, or will it require to run separate instance for every 5 players. Also, if player is playing in single-player mode, he seems to be also connected to the game server. Looks like the game server is performing all of the necessary calculations and player only sends in the commands for server to process (e.g, move me from 1,0 to 1,1) and after receiving the response, client interpolates the movement received from the server.

**And finally, the third question:**
Server may have many different scenes, but many players may be situated across many different scenes. There could also be dungeons and other player oriented stuff. So the question is, is it possible to achieve this goal using default Unity functionality.

# Answer
> 3 votes
I can give some comments on question 1 and 2. I am not able to answer question 3.

***Question 1***

**Remote server:** If you have a remote server, you only keep one copy of the game remotely, not a copy for each player. The server stores the state of each connected player (positions, health, items etc). Each player runs the game locally, and mouse clicks and keyboard actions will be sent to the server for validation, and broadcasted to all other machines. Each local game will then use the input actions from the server to animate the players on their own screen.

**Local server:** The same as a remote server, but all communication will be sent through the server hosted on the local machine. The same rules apply here as on the remote server. The user action validation is still processed by the server instance.

***EDIT:*** added some extra comments to the second question.

***Question 2***

I do not fully understand what you are asking about, but you do not need to have assigned servers for each room. The server can manage rooms in many different ways. I would suggest using a map with the roomId as key and containing an array of connected players (e.g. Java-style:`HashMap<String,Array<Player>>`. If you want to have each room playing their own game, you can assign a game instance (still on the same server) for the specific room with players. A server can run many game instances, still on the same server instance.

If you are playing single-player, you do not have to be connected online, because the server can be run on your local machine. The server will still receive the user actions (like moving attacking, picking up stuff and so on), but instead of passing all those actions over the network, pass them to the local instance of the server. I think it is common to still use an online server for authentication, but that server does not have to be the game server.

**Final Thoughts**

There are many different architectures for this specific problem, and I think you can find good resources if you try to search around on the internet. My answer is just some thoughts, and does not give THE correct answer, but hopefully it can be of help.

---
Tags: unity, networking, client-server, matchmaking
---


# Question
Title: Generate smaller quads from a large quad?
I have a big quad (100x100) and I was wondering how can I generate smaller quads from this big quad? Such that I will have multiple small quads and I can add a different texture to each quad.

# Answer
You can simply:

1. clone your big quad using Instantiate (using a prefab or your original Game Object).
2. change the scale of the clone using its transform.
> 1 votes

---
Tags: unity
---


title: How to prepare a game for localization?

text:
# Question
Title: How to prepare a game for localization?
Many projects don't think about localization until the game is done. Then localization is done as a hack, and it's obvious that it was added on later. Some specific areas of concern:

* Text strings (obviously)
* Audio clips such as music and/or narratives
* Text rendered on textures (e.g. a label on a crate)
* Text rendered in frames in pre-rendered movies
* Fonts/Character sets for different languages
* Etc.

What are some good ways to prepare for these challenges in the initial development stages, so you can make it easier without incurring too much cost up front?

# Answer
> 51 votes
I'm not an expert, but here's some basic stuff:

**Make sure your strings can handle more than just ASCII**

You're going to need some spécîål characters that don't fit in ASCII and your string class better not barf on them. UTF-8 is a common encoding because it's space-efficient. Whatever you do, test early and iron out the kinks.

It's a really good idea to use an actual string class and not just `char *` everywhere or you're going to be in a world of pain.

Don't forget your fonts. Make sure all of the fonts you're using have the characters you need.

**Pull your strings out of code**

This is the most important one. Make sure your text strings are all stored outside of code in some data file you can swap out. Getting a pipeline set up for this can be a chore up front, but will save you a ton of time later. You'll want some simple API so that any time you need a string in code, it's as simple as:

```
String text = Locale::getString("some unique identifier");

```

**Don't concatenate or build strings in code**

It's important not to make any assumptions about how a piece of text is built out of smaller words. Even something as innocuous as:

```
String currency = Locale::getCurrencyString() + money.toString();
// creates $123

```

is a problem because other languages may place the currency mark after the number. Instead, use format strings which are themselves localized like:

```
String format = Locale::get("currency format"); // returns "${0}" in English
String currency = String::Format(format, money.toString());

```

That way, localizers can rearrange words within the format string.

**Minimize the amount of text that appears in art, especially video**

Forking art assets is a chore. You'll likely need to do it at least a little for some UI elements, but it's a hassle. Forking FMV is a *huge* pain because now you have to render and store duplicate copies of your FMV.

**Test in different languages thoroughly**

In most codebases, it's all too easy to just say `printf("Hi there");` or `loadTexture("someTexture");` and forget that those need to go through your localization API. Someone will forget and you'll end up with something that's correct in your primary language but wrong in others. The only way to find these is to have your testers test in non-primary languages.

**Make missing localized text obvious**

You typically translate your text late in the cycle, so for much of the time, there will just be no data for some languages. That's fine because it lets you iterate on your content without having to constantly retranslate. The downside is it means it's easy for you to miss things and forget to translate some stuff.

One cheap thing you can do is make missing text show up very obviously like "!!!TRANSLATION NEEDED FOR ID #blah blah!!!" in the game when it's missing.

**Design your UI around the worst case language**

Different languages tend to have longer or shorter words. A UI that looks beautiful in English may have text that runs past its boundaries, gets cropped, or wraps incorrectly in a longer language. You'll have to make UI changes to accommodate the worst-case language (or fork your UI, but that's probably *not* what you want to do.)

Annoyingly, English is often the *shortest* language of the ones typically localized, so your designers are probably inadvertantly designing for the best case. Make them use extra long text for their placeholders when they design. Assume any given piece of text can be about 30% longer than it is in English. Google Translate can be good for getting an approximate piece of text for placeholder.

**Budget time for translation**

Translating text usually happens late when the team is tired and doesn't really care. Nonetheless, you'll get a *lot* of bugs when it happens. Words will run past boundaries, translators will make mistakes, etc. To make matters worse, the turnaround time for iterating on text can be long if you have to send text to people overseas and wait for their changes. Allocate time for this work.

# Answer
> 16 votes
In addition to other suggestions, one thing I've done in the past which helps greatly in finding translated text bleeding out of UI components is to have a special language mode for your game which, when displaying any string, looks at all the languages and picks the longest version of that string. That way, once you've made all the strings fit in that mode, you know that you've fixed all the text bleeds in every language.

# Answer
> 10 votes
Localizing a game **correctly** is *damn hard*.

You can browse the internet, read blog posts, or StackOverflow answers; you can learn the traditional i18n frameworks such as gettext; read Wikipedia pages on internationaliztaion and game localization; consult the excellent Microsoft language guide – but localizing games is actually harder than that. In fact, with games it's probably harder than with any other application or web-interface. This because the games are so much more dynamic, more vibrant, more alive (well, at least good games are).

More to the point, the following steps will probably need to be taken:

**Establish the boundaries.**

You want to make an all-important decision for which languages you want to support early. The wider your choice, the more assumptions about how a language can behave will be broken. Often these assumptions are so deeply imprinted in our brains, that we cannot even imagine that they may be incorrect without someone pointing them out. Which brings us to the next point:

**Find the experts for each language you want to support.**

Expert means someone who has sufficient analytic skill and knowledge of the language, that he would be able to point you which assumptions an English speaker does that do not hold in his own language. Then you'll need to come up with a strategy how to work around those assumptions.

As an example: in Western languages we justify text in a paragraph by inserting extra space between words. In Arabic language the text is justified by inserting kashida characters *inside* the words. It might look like this.

Another example: in Russian, there are 2 plural forms for the majority of words. Thus for example you would translate "1 coin" / "3 coins" / "5 coins" as "1 монета", "3 монеты", but "5 монет" . The actual procedure to decide the correct plural form looks like this:

```
function LocalRU::GetPlural(n, form0, form1, form2) {
    return (n%10) == 0 || (n%100) >= 5 && (n%100) <= 20? form0 :
           (n%10) == 1? form1 :
           (n%10) <= 4? form2 : form0;
}

```

**Create a context-aware translation module.**

You're probably aware that translation always depends on the context. And you know that the context within a game changes all the time. What happens if we put these two statements together? In general your translations should be as dynamic as your game.

For example, a simple phrase "I agree" translates into Russian as one of "Я согласен" / "Я согласна" / "Я согласно", depending on the gender of the speaker (male / female / transgender|queer|questioning). If this is one of your dialog lines, then the language module will have to pick one of the possible translations at run-time depending on the gender of your character (assuming you offer your players such a choice).

The same phrase when translated to Japanese will again have different translations, depending on the level of formality of the relationship between the speaker and the listener. Thus, if you introduce in your game the idea of reputation, or friendship, or varying level of superiority (say, your character may evolve from Rookie to General), then you'll have to take this into account when forming the translation. (Actually, this is not Japanese-specific. Even in English, in the army you never say "Sir, yes, sir!" to someone below you in rank.)

**Have a way to jump into the context.**

Your translators should have the ability to see the context where a particular phrase appears. Sometimes the context is obvious, sometimes you have to see / hear / experience it yourself in order to translate something correctly.

Even such simple sentence as "This book is blue." cannot be unambiguously translated without me *looking* at the book and seeing which particular shade of blue it is.

**Avoid word play, puns, and other language-specific elements.**

Or maybe don't avoid, but at least have a strategy in mind for what to do when the wordplay cannot be translated. Because probably it won't.

At the very least you shouldn't create any quests / puzzles / game objects which rely on certain words having double meaning, or being similar to some other words. Because once translated you'll break your own game. (For example, in an old game Fallout2 the main quest was to find the object called GECK; there also were numerous "Gecko" monsters (mutated lizards) around the game; naturally they created multiple references and quests around this similarity of names, which made good translations extremely hard).

**Cheer up!**

Localizing a game is hard. But it's hard for everyone. If you make an effort and do it correctly, it won't go unnoticed by game critics in your target country. A game with good translation will stand out, and earn higher profits. After all, text is just as important for creating atmosphere in the game, as the graphics (this is why old text-based RPGs were so immersive).

# Answer
> 3 votes
Wil Shipley has by far the best guide on localization I've ever read. Unfortunately it's iPhone specific, but one can still derive commonly useful information. Further, he addresses the localization of assets and the UI - two of the bigger challenges in game localization I can imagine.

# Answer
> 1 votes
Always, **ALWAYS** treat the source language as a localized language.

So if your source language is EN then keep all EN assets and strings in a separate EN folder and pull from there.

Pull EN assets through your intended localization pipeline.

By doing this one simple thing you'll catch maybe 80% of localization issues and be set for a ***much*** easier localization process.

I've localized *many* games and always lead with this nugget.

# Answer
> 1 votes
I see some really great tips here!

I'll try to make a list of the **most common mistakes** that can range from making your localization harder to completely ruining your game:

* Thinking of localization as the last step of game development
* Not isolating your text strings from the source code
* Concatenation/linebreaks in the middle of a sentence.
* Assuming times, dates and units don't need localization
* Not providing enough reference material to translators/Not answering their questions
* Assuming all text from your game will be in ASCII
* Having text in visuals
* Having rigid text/UI boxes
* Assuming all languages have the same length as English
* Using Google Translate/machine translation
* Ignoring cultural factors
* Not allocating enough budget for localization

Localization should be integrated to the development as early as possible and you should always keep it in mind when designing a game.

With the right planning and careful market research, you will save yourself a lot of trouble and expenses further down the line.

I happen to be the founder of a game localization company and we covered the preparation of a game for localization a couple of months ago in our blog.

Here's the infographic that sums up that post: https://magic.piktochart.com/output/18317297-9-steps-to-cheaper-game-development-with-localization

The link to the full post that covers those tips in more details is at the bottom of it.

---
Tags: localization
---