# Question
Title: Player light color he collects before checkpoint is getting reset when he restarts at checkpoint
I have a child object for my player called Light. The light color changes when the player touches balls of different colors.

When I respawn at a checkpoint, the light is getting reset to the default color instead of the most recent color.

Checkpoint script:

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

public class checkpoint : MonoBehaviour
{
    private GameMaster gm;
    private GameObject player;
    private CapsuleCollision coll;
    private Light playercolor;

    void Start()
    {
        gm = GameObject.FindGameObjectWithTag("GM").GetComponent<GameMaster>();
        player = GameObject.FindGameObjectWithTag("Player");
        coll = GameObject.FindGameObjectWithTag("Player").GetComponent<CapsuleCollision>();
        playercolor = player.transform.GetChild(1).GetComponent<Light>();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
            {
            gm.checkPoint = transform.position;
            playercolor.color = coll.lightcolor();
        }
    }
}

```

Player Collision Script

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

public class CapsuleCollision : MonoBehaviour
{
    public GameObject player;
    private new Light light;
    public GameObject enemy;
    private Light enemyLight;
    public GameObject door;
    public Renderer doorColor;
    public BoxCollider2D doorOff;
    public Material doorColor2;
    private bool doorON;
    public GameObject dieExplode;
    public GameObject LevelCompeteUI;
    public GameObject LevelRetryUI;
    public GameObject PauseButton;
    public GameObject WinExplode;
    public Transform timer;
    public GameObject TimerUI;
    public LevelSelector levelSelector;
    public int levelreached;
    public Light newplayercolor;

    Timer time;

    void Start()
    {
        levelreached = PlayerPrefs.GetInt("OneDoor");
        Debug.Log(levelreached);
        time = timer.GetComponent<Timer>();
        time.StartTimer();
    }

    private IEnumerator waitForSec2(float sec)
    {
        yield return new WaitForSeconds(sec);
        LevelCompeteUI.SetActive(true);
        PauseButton.SetActive(false);
    }

    private IEnumerator GameOver()
    {
        yield return new WaitForSeconds(2f);
        LevelRetryUI.SetActive(true);
        PauseButton.SetActive(false);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.tag == "Ball")
        {
            Debug.Log("Balls :"+collision.gameObject.name);
            light = gameObject.transform.GetChild(1).GetComponent<Light>();
            enemy = collision.gameObject.gameObject;
            enemyLight = enemy.transform.GetChild(0).GetComponent<Light>();
            light.color = enemyLight.color;
        }
        if (collision.gameObject.tag == "Door")
        {
            Debug.Log("Door :" + collision.gameObject.name);

            door = collision.gameObject.gameObject;
            doorColor = door.GetComponent<Renderer>();
            doorColor2 = doorColor.material;
            light = gameObject.transform.GetChild(1).GetComponent<Light>();
            doorOn();
            Debug.Log("Door :" + doorColor2.color);

        }
        if(collision.gameObject.tag == "Enemy")
        {
            gameObject.SetActive(false);
            Instantiate(dieExplode,transform.position,Quaternion.identity);
            Debug.Log("GAme Ober");
            LevelRetryUI.SetActive(true);
            PauseButton.SetActive(false);

            time.StopTimer();
            TimerUI.SetActive(false);
        }
        if(collision.gameObject.tag == "EndGame")
        {
            WinExplode.SetActive(true);
            Instantiate(WinExplode, WinExplode.transform.position, Quaternion.identity);
            StartCoroutine(waitForSec2(2f));
            levelreached = levelreached + 1;
            PlayerPrefs.SetInt("OneDoor",levelreached);
            Debug.Log(levelreached);
            time.StopTimer();
            TimerUI.SetActive(false);

        }
    }

    private IEnumerator waitForSec(float sec)
    {
        yield return new WaitForSeconds(sec);
        doorOff = door.GetComponent<BoxCollider2D>();
        doorOff.enabled = true;
    }
    void doorOn()
    {
        doorOff = door.GetComponent<BoxCollider2D>();
        doorOff.enabled = true;
        if (light.color != doorColor2.color)
        {
            doorOff.enabled = false;
            StartCoroutine(waitForSec(.1f));
        }
        else if(light.color == doorColor2.color)
        {
            doorOff.enabled = true;

        }
    }

    void Update()
    {
        Debug.Log(levelreached);
        newplayercolor.color = light.color;
        Debug.Log(newplayercolor.color);
    }

    public Color lightcolor()
    {
        Debug.Log(light.color);
        return light.color;
    }
}

```

Player Pos Script

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

public class PlayerPos : MonoBehaviour
{
    private GameMaster gm;
    private GameObject player;
    private CapsuleCollision coll;
    private Light playercolor;

    void Start()
    {
        gm = GameObject.FindGameObjectWithTag("GM").GetComponent<GameMaster>();
        transform.position = gm.checkPoint;
        player = GameObject.FindGameObjectWithTag("Player");
        coll = GameObject.FindGameObjectWithTag("Player").GetComponent<CapsuleCollision>();
        playercolor = player.transform.GetChild(1).GetComponent<Light>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            gameObject.SetActive(true);
        }
    }
}

```

Game Master Script

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

public class GameMaster : MonoBehaviour
{
    private static GameMaster instance;
    public Vector2 checkPoint;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(instance);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

```

its the code I am calling replay and restart from replay function \`using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;

public class PauseButton : MonoBehaviour { public GameObject PauseMenuUI;

```
public void Pause()
{
    PauseMenuUI.SetActive(true);
    Time.timeScale = 0f;
}

public void Resume()
{
    PauseMenuUI.SetActive(false);
    Time.timeScale = 1f;
}

public void Replay()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

public void MainMenu()
{
    SceneManager.LoadScene("MainMenu");
    Time.timeScale = 1f;
}
// Start is called before the first frame update
void Start()
{

}

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

}

```

} \`

# Answer
I have to guess at what you're doing here because you still haven't shown us your code for failing/restarting.

From context, it looks like the way you're respawning is you're either destroying the old player object and spawning a new one, or re-loading the whole scene with a new player object in it. You're using the `PlayerPos` script's `Start` method to position it at the position of the last checkpoint, as rememebered by the GameMaster script which doesn't get destroyed on scene load.

```
void Start()
{
    gm = GameObject.FindGameObjectWithTag("GM").GetComponent<GameMaster>();
    transform.position = gm.checkPoint;
    ...

```

(Hint: you can write that first line shorter as `gm = GameObject.FindObjectOfType<GameMaster>()`, or since you're using a Singleton pattern, just use `GameMaster.instance` instead of keeping a local `gm` variable at all)

This would be a reasonable place to also restore a light colour remembered in the `GameMaster` the same way. First, add a color field:

```
public class GameMaster : MonoBehaviour
{
    private static GameMaster instance;
    public Vector2 checkPoint;
    public Color32 color;
    ...

```

Then restore it at the same time you restore the checkpoint position:

```
void Start()
{
    transform.position = GameMaster.instance.checkPoint;
    player = GameObject.FindGameObjectWithTag("Player");
    coll = player.GetComponent<CapsuleCollision>();
    playercolor = player.transform.GetChild(1).GetComponent<Light>();

    playercolor.color = GameMaster.instance.color;
}

```

Depending on your game logic, you might want to set `gm.instance.color` when the player touches a checkpoint, or just before they fail/restart - depending on whether you want the colour rewound to the most recent checkpoint or not.

If you want to go further you could create a `CheckpointPersistent` type to hold position, colour, and any other data that you want to restore at a checkpoint, then give it some `Record()` and `Restore()` methods to update its data from the player state or apply the saved data to the player's state respectively. This helps with encapsulation, so not every script in the chain needs to know the details of what gets restored at checkpoints - they can just ask the script with that job to do its thing when the need arises.
> 0 votes

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


# Question
Title: How to send object transform position coordinates over UDP from Unity 3D
I'm trying to send the x, y and z coordinates of an in-game object over UDP.

I found a script in a Unity forum which should send info over UDP and as I understand it it should send the information from the console. So I created another script to have the x, y and z coordinates to be printed in the console, that script worked but the information wasn't received over UDP.

The networking wasn't an issue, I'd tested the UDP connection by other means and it worked fine.

I then tried to edit the script to send the object coordinates rather than whatever was shown in the console, I tried doing this by editing the line `text = Console.ReadLine()` to say `text = GameObject.Find("Object").transform.position` and linked this to the object but this didn't work. I also changed the `byte[] data = Encoding.UTF8.GetBytes(text)` line to say `byte[] data = Encoding.UTF8.GetBytes(GameObject.Find("Object").transform.position)` but this didn't work either.

With the help of some more tutorials I then tried creating a new script taking the necessary elements from this script and making it as simple as possible and I couldn't get this to work either, that script would work if what was being sent was just simple text in quotation marks written straight into the script but whatever I tried I couldn't get the coordinates to be sent. And now I am completely out of ideas and have wasted much precious time and would be very grateful if someone could offer any help at all.

```
using UnityEngine;
using System.Collections;

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class UDPSend : MonoBehaviour
{
    private static int localPort;

    // prefs
    private string IP;  // define in init
    public int port;  // define in init

    // "connection" things
    IPEndPoint remoteEndPoint;
    UdpClient client;

    // gui
    string strMessage="";

    // call it from shell (as program)
    private static void Main()
    {
        UDPSend sendObj=new UDPSend();
        sendObj.init();

        // testing via console
        // sendObj.inputFromConsole();

        // as server sending endless
        sendObj.sendEndless(" endless infos \n");
    }
    // start from unity3d
    public void Start()
    {
        init();
    }

    // OnGUI
    void OnGUI()
    {
        Rect rectObj=new Rect(40,380,200,400);
        GUIStyle style = new GUIStyle();
        style.alignment = TextAnchor.UpperLeft;
        GUI.Box(rectObj,"# UDPSend-Data\n127.0.0.1 "+port+" #\n"
                + "shell> nc -lu 127.0.0.1  "+port+" \n"
                ,style);

        // send it
        strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
        if (GUI.Button(new Rect(190,420,40,20),"send"))
        {
            sendString(strMessage+"\n");
        }
    }

    // init
    public void init()
    {
        // Define end point , from which the messages are sent.
        print("UDPSend.init()");

        // define
        IP="127.0.0.1";
        port=8050;

        // Send
        remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
        client = new UdpClient();

        // status
        print("Sending to "+IP+" : "+port);
        print("Testing: nc -lu "+IP+" : "+port);
        sendString("jt");
    }

    // inputFromConsole
    private void inputFromConsole()
    {
        try
        {
            string text;
            do
            {
                text = Console.ReadLine();

                // Send the text to the remote client .
                if (text != "")
                {
                    // Encode data using the UTF8 encoding to binary format.
                    byte[] data = Encoding.UTF8.GetBytes(text);

                    // Send the text to the remote client.
                    client.Send(data, data.Length, remoteEndPoint);
                }
            } while (text != "");
        }
        catch (Exception err)
        {
            print(err.ToString());
        }
    }

    // sendData
    private void sendString(string message)
    {
        try
        {
            //if (message != "")
            //{

            // Encode data using the UTF8 encoding to binary format.
            byte[] data = Encoding.UTF8.GetBytes(message);

            // Send the message to the remote client.
            client.Send(data, data.Length, remoteEndPoint);
            //}
        }
        catch (Exception err)
        {
            print(err.ToString());
        }
    }

    // endless test
    private void sendEndless(string testStr)
    {
        do
        {
            sendString(testStr);
        }
        while(true);
    }
}

```

# Answer
Your xyz position isn't likely to be kept as text so what you don't want to do is try to encode it as UTF8. If you don't need to do anything with the coordinates then you should just turn it into a string before encoding, i.e:

```
string pos = GameObject.Find("Object").transform.position.toString();
byte[] data = Encoding.UTF8.GetBytes(pos);

```

Or if you need to manipulate the position on the other end you need to serialize and then deserialise your object position with something along these lines. If that proves to also be a pain to get working because of how the position is actually stored, you should be able to extract each floating point co-ord (x,y, and z) and just turn those into something sendable like:

```
union xyz{
    struct{
        float x;
        float y;
        float z;
    }
    byte[12] array;
}

```

You'd send xyz.array and on the other side assign it to xyz.array, then access each co-ord via xyz.x, etc.
> 0 votes

# Answer
Use the below code for sending data over UDP in unity

```
/*
    -----------------------
    UDP-Send
    -----------------------

    // [url]http://msdn.microsoft.com/de-de/library/bb979228.aspx#ID0E3BAC[/url]
*/

using UnityEngine;
using System.Collections;

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class UDPSend : MonoBehaviour
{
    private static int localPort;

    // prefs
    private string IP;  // define in init
    public int port;  // define in init

    // "connection" things
    IPEndPoint remoteEndPoint;
    UdpClient client;

    // gui
    string strMessage="";

    // call it from shell (as program)
    private static void Main()
    {
        UDPSend sendObj=new UDPSend();
        sendObj.init();

        // testing via console
        // sendObj.inputFromConsole();

        // as server sending endless
        sendObj.sendEndless(" endless infos \n");

    }
    // start from unity3d
    public void Start()
    {
        init();
    }

    // OnGUI
    void OnGUI()
    {
        Rect rectObj=new Rect(40,380,200,400);
            GUIStyle style = new GUIStyle();
                style.alignment = TextAnchor.UpperLeft;
        GUI.Box(rectObj,"# UDPSend-Data\n127.0.0.1 "+port+" #\n"
                    + "shell> nc -lu 127.0.0.1  "+port+" \n"
                ,style);

        // ------------------------
        // send it
        // ------------------------
        strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
        if (GUI.Button(new Rect(190,420,40,20),"send"))
        {
            sendString(strMessage+"\n");
        }
    }

    // init
    public void init()
    {
        // Endpunkt definieren, von dem die Nachrichten gesendet werden.
        print("UDPSend.init()");

        // define
        IP="127.0.0.1";
        port=8051;

        // ----------------------------
        // Send
        // ----------------------------
        remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
        client = new UdpClient();

        // status
        print("Sending to "+IP+" : "+port);
        print("Testing: nc -lu "+IP+" : "+port);

    }

    // inputFromConsole
    private void inputFromConsole()
    {
        try
        {
            string text;
            do
            {
                text = Console.ReadLine();

                // Den Text zum Remote-Client senden.
                if (text != "")
                {

                    // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
                    byte[] data = Encoding.UTF8.GetBytes(text);

                    // Den Text zum Remote-Client senden.
                    client.Send(data, data.Length, remoteEndPoint);
                }
            } while (text != "");
        }
        catch (Exception err)
        {
            print(err.ToString());
        }

    }

    // sendData
    private void sendString(string message)
    {
        try
        {
                //if (message != "")
                //{

                    // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
                    byte[] data = Encoding.UTF8.GetBytes(message);

                    // Den message zum Remote-Client senden.
                    client.Send(data, data.Length, remoteEndPoint);
                //}
        }
        catch (Exception err)
        {
            print(err.ToString());
        }
    }

    // endless test
    private void sendEndless(string testStr)
    {
        do
        {
            sendString(testStr);
        }
        while(true);

    }

}

```
> 0 votes

---
Tags: unity, networking, udp
---


title: Converting Javascript to C#

text:
# Question
Title: Converting Javascript to C#
I am trying to convert the following JavaScript code:

```
var Js_white = 0;
var Js_black = 1;

var Js_knightMvt = new Array();         //new int[2][64];
var Js_bishopMvt = new Array();         //new int[2][64];

function BoardCpy(a: Array, b: Array):void
    {
      for( var sq= 0; sq < 64; sq++ ) b[sq] = a[sq];
    }

  another function
  {
    BoardCpy(Js_knight_pos, Js_knightMvt[Js_white]);
      BoardCpy(Js_knight_pos, Js_knightMvt[Js_black]);
      BoardCpy(Js_bishop_pos, Js_bishopMvt[Js_white]);
      BoardCpy(Js_bishop_pos, Js_bishopMvt[Js_black]);
  }

```

to C# like this:

```
private static int Js_white = 0;
private static int Js_black = 1;

private int[] Js_knightMvt;               //new int[2][64];
private int[] Js_bishopMvt;               //new int[2][64];

private void BoardCpy(int[] a, int[] b)
    {
        for (int sq = 0; sq < 64; sq++)
        {
            b[sq] = a[sq];
        }
    }

Another function
{
  BoardCpy(Js_knight_pos, Js_knightMvt[Js_white]);
  BoardCpy(Js_knight_pos, Js_knightMvt[Js_black]);
  BoardCpy(Js_bishop_pos, Js_bishopMvt[Js_white]);
  BoardCpy(Js_bishop_pos, Js_bishopMvt[Js_black]);
}

```

The problem is I get

> error CS1503: Argument '#2' cannot convert 'int' expression to type 'int\[\]' and error CS1502: The best overloaded method match for 'JsJester.BoardCpy(int\[\], int\[\])' has some invalid arguments on the lines from another function.

# Answer
It looks like you want each of these two arrays to be a jagged array of arrays:

```
private int[] Js_knightMvt; //new int[2][64];
private int[] Js_bishopMvt; //new int[2][64];

```

But you've defined them as an array of `int`s.

That means when you select one index from one of these arrays, you get a single integer, rather than an array of integers.

If you want each entry of these `Mvt` arrays to contain its own array, then you need to specify that in the type:

```
 // Two sets of brackets for the two layers of arrays
 int[][] Js_knightMvt = new int[2][];

```

Remember to create each nested array inside this container before you try to use them, eg...

```
 for(int i = 0; i < 2; i++) {
      JS_knightMvt[i] = new int[64];
 }

```

Without this, all of the entries of the outer array will just contain `null` by default.
> 0 votes

---
Tags: c#, javascript
---


title: How do I apply collision to a turtle

text:
# Question
Title: How do I apply collision to a turtle
I cannot figure out how to apply collision to a turtle. I am in need of help for collision with pen lines and turtles. I want the two to hit and restart the game but I can't get collision on either.

```
import turtle
import pygame

wn = turtle.Screen()
wn.bgcolor("black")

#Draw border
mypen = turtle.Turtle()
mypen.penup()
mypen.pencolor('white')
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
for side in range (4):
    mypen.forward(600)
    mypen.left(90)
mypen.hideturtle()

#Create player 1
player = turtle.Turtle()
player.setposition(240,240)
player.setheading(180)
player.color("red")
player.shape("classic")

player.speed(0)

#Create player 2
player2 = turtle.Turtle()
player2.setposition(-240,-240)
player2.color("aqua")
player2.shape("triangle")

player2.speed(0)

#Set speed variable
speed = 3

#Define functions
def turnleft():
    player.left(30)

def turnright():
    player.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for p1ayer 1

turtle.listen()
turtle.onkey(turnleft,"Left")
turtle.onkey(turnright,"Right")

#Define player 2 functions

def turnleft():
    player2.left(30)

def turnright():
    player2.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for player 2
turtle.listen()
turtle.onkey(turnleft,"a")
turtle.onkey(turnright,"d")

#turtle.onkey(increasespeed,"Up")

while True:
    player.forward(speed)
    player2.forward(speed)

    #Bouandary
    if player.xcor() > 300 or player.xcor() < -300:
        player.right(100)
    #Boundary
    if player.ycor() > 300 or player.ycor() < -300:
        player.right(100)
    #Bouandary2
    if player2.xcor() > 300 or player2.xcor() < -300:
        player2.right(100)
    #Boundary2
    if player2.ycor() > 300 or player2.ycor() < -300:
        player2.right(100)

```

# Answer
You can put the coordinates of the two objects in a variable like:

```
PlayerPosX = 240
PlayerPosY = 240

Player2PosX = -240
Player2PosY = -240

```

Then do an `if` in a `while True:` that saying if the two PosX and the two PosY matches, the game restarts. Hope you serve.
> 0 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: d3d11 renderqueue multi pass rendering design best practice
The goal: issue least calls to d3d11 ImmediateContext and render advanced effects like toon / outline / anything that requires rendering the same vertex buffers with at least two different vertex shader and pixel shader programs efficiently by sorting opaque drawcalls front to back and transparent drawcalls back to front.

What I did: Abstract calls to d3d11 immediate context by a DrawCall struct that acts as a gpu command recorder. A call to DrawCall.SetIndexBuffer will create a c# Action that will issue a call on the ImmediateContext upon invoke call. The DrawCall internal gpu command list is sorted the following way: set shaders, set constantbuffers, set blendstate, set stencilstate, set vertexbuffers.... I am using sharpdx and c#.

My problem: I use a 64bit sortkey for my gpu commands. When rendering complex effects like outline or anything that requires state changes to outputmerger the whole idea with sorting doesn't seem right... example: I render opaque objects first and then transparent objects... I want to render an object opaque with a diffuse shader and it should have a red transparent outline. For this effect I have to modify stencil and blend states in between drawindexed calls. According to my sortkey those gpu commands are on different draw loops opaque\<\>transparent but the stencilstate requires both drawindexed calls to be one after another.

Should I implement a chained gpu command for multipass rendering or are there better ways to handle such effects?

# Answer
> 2 votes
I want to post an answer. I decided to go for a flexible solution to achieve the following features:

* Rendering to different layers (world, overlay text, gui, etc.)
* Multipass rendering (render same submesh with two different sets of vertex and fragment shaders, aka materials)
* Additive blending aka transparent rendering
* using stencilbuffer inside material passes as a special command
* shared vertex buffers, shaderresourceview (aka texture)
* dynamic buffer updates

Thats how I implemented my flexible render pipeline:

1. Traverse my scenegraph and look for objects that have a transform, material and mesh component
2. when all three components are found on an object I ask the renderqueue to create a drawcall for me. The creation must be inside the queue to prevent reusing the same drawcall multiple times.
3. a drawcall is basically a sorted collection of 'commands' (see command pattern) that run on the d3d11 ImmediateContext at some later point. I first collect the drawcalls (bundles of commands) and then later i sort the drawcalls according to renderlayer, blendstate and material pass Index
4. I ask every component (transform, material, mesh) to contribute to building the drawcall by populating the commands inside the sorted collection. every command has a unique key to prevent adding the same command twice inside a drawcall. I basically just ask the transform to give me a constantbuffer of world matrix, the material to set correct shaderprograms and textures AND decide the draw method (Indexed, instances, whatever), the mesh to set correct vertex buffer and indexbuffer. A mesh might consist of many submeshes. so for each submesh a corresponding material with atleast one material pass must exist in order to render the submesh.
5. now that i have a collection of drawcalls I start to sort the drawcalls. By sorting i mean put fractions of drawcalls into some collections. Thats the sorting order: sort by renderlayer (world, overlay, gui), sort by render order (first opaque, then transparent. both have a specific range of int, like in unity game engine), sort by pass index (an object can be drawn opaque with an transparent outline)
    6. invoke the commands. call ImmediateContext.Flush at the end to actually run all invoked commands, because I render to an offscreen rendertarget and not the backbuffer directly.

So far it works great and I can make quiet some effects with it. For my intended use I only use immediate rendering with basic lighting and no multithreaded drawcall collecting, because my scenes are well below 2k objects. Another bonus I do is sort my drawcalls also by distance. for opaque objects I use front to back sorting by camera distance to reduce overdraw aka running the fragment shader unneccessary for objects that will be overdrawn later. For transparent objects I sort back to front to achieve maximum overdraw, otherwise transparency with additive blending doesnt work. there is a good nvidia article on blending and in khronos group wiki also (tldr: transparency cant be achieved exact in realtime, thats why we do it approx by sorting objects back to front).

# Answer
> 0 votes
Background: There is no short answer here, but as someone who also codes in C# and Sharpdx, I can go over some of the learnings I have.

I sacrificed some of my flexibility for specific for fixed function draw actions. That being for example, draw my terrain, draw my models, text etc. But, what I do differently is that there is a pass specific to shadows, a pass specific to above water, below water, and transparency. I tag dynamic assets to render in these passes, so that I have the flexibility to select what rendering needs to be applied.

What I end up having is a fixed graphics pipeline with components within it that allow for flexibility, it also made the job of using deferred rendering much easier.

I, like yourself started out with a fully fledged flexible pipeline, but ended with a more fixed rendering pipeline wtih some flexibility. This is where I think you will end up, you have a need to control some elements/anchor points of your pipeline which allowing for your engine to take care of some of the finer details. As from your problem, you want to exert some specific control of the drawing at times.

On a performance note, you really don't want to be changing the state too often because you flush the GPU pipeline. On more modern GPUs, this isnt as bad (usually only affects a few cycles). So you may end up grouping your drawing commands differently, that is draw all relevant objects with your diffuse shader, then modify stencils states etc then draw all the objects again etc...

Chaining GPU commands (say through DrawIndirect) also will give you a performance improvement if your GPU is being starved by the CPU and you want to feed the pipeline quickly. I tested for example deferred rendering in my game engine which allowed for the draw commands to be recorded and buffered. This had significant performance improvement in Debug but literally no frame rate improvement in release.

Gl, hope you find your solution.

---
Tags: c#, directx11, graphics-programming
---


# Question
Title: How can I use Cocoa beans in Minecraft Forge custom crafting recipes?
I'm creating a Minecraft mod with Forge, and I need to create a custom crafting recipe that uses cocoa beans. However, when I try to create the recipe, it does not work (as in, I cannot craft items with the specified pattern).

When `src/main/resources/assets/mymod/recipes/myrecipe.json` looks like this, it works fine:

```
{
    "type": "minecraft:crafting_shaped",

    "pattern": [
        " X ",
        " X ",
        " X "
    ],

    "key": {
        "X": {
            "item": "minecraft:iron_ingot"
        }
    },

    "result": {
        "item": "minecraft:gold_ingot",
        "count": 1
    }
}

```

but when it looks like this, I can't craft items with the recipe:

```
{
    "type": "minecraft:crafting_shaped",

    "pattern": [
        " X ",
        " X ",
        " X "
    ],

    "key": {
        "X": {
            "item": "minecraft:cocoa_beans"
        }
    },

    "result": {
        "item": "minecraft:gold_ingot",
        "count": 1
    }
}

```

According to https://minecraft.gamepedia.com/Cocoa\_Beans#ID, the name ID for cocoa beans is `minecraft:cocoa_beans`, which is exactly what I entered. However, the crafting recipe does not seem to be loaded into the game.

Why isn't the second crafting recipe working and how can I fix it?

I'm using Forge version 1.12.2-14.23.5.2768 and Eclipse version 2018-09 (4.9.0), and I'm running Minecraft directly from Eclipse.

# Answer
> 1 votes
# Coco beans are brown dye.

Dye has metadata values that determine which specific item it is (until 1.13 and The Flattening). The data value you're looking for in this case, is 3.

```
"key": {
    "X": {
        "item": "minecraft:dye",
        "data": 3
    }
},

```

---
Tags: minecraft-modding
---


# Question
Title: Instantiate an object and translate it randomly
My goal through this code in C # is that each time the player presses the `Q` I create a cube at a fixed position given by another object, then begin translating it in a random direction. ie.

* first press: a cube is created at the spawn point and moves away in direction 1
* second press: a cube is created at the spawn point and moves away in direction 2
* third press: a cube is created at the spawn point and moves away in direction 3

I don't understand why the code below does not work:

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

public class spawn_random_trajet : MonoBehaviour {

    public GameObject Spawn, Spawn2;
    public Transform origineSpawn;
    public float moveSpeed=5f;

    void Update () {
        if (Input.GetKeyDown (KeyCode.Q)) {
            int random_trajet_x = Random.Range (-10,10);
            int random_trajet_y = Random.Range (-10,10);
            int random_trajet_z = Random.Range (-10,10);

            Spawn2 = Instantiate(
                 Spawn,
                 origineSpawn.position,
                 origineSpawn.rotation
            ) as GameObject;

            transform.Translate (
                 random_trajet_x*Time.deltaTime*moveSpeed,
                 random_trajet_y*Time.deltaTime*moveSpeed,
                 random_trajet_z*Time.deltaTime*moveSpeed
            );
        }
    }
}

```

# Answer
> 1 votes
`transform.Translate` says "move **me** by this offset **now**"

It does **not** say "take *the object I just spawned*, and start moving it at this velocity, *every frame* from now into the indefinite future"

Really, you should put the movement behaviour on the object you've spawned, not on the object that spawns it, as I described to you in a previous answer.

```
public class TranslateOverTime : MonoBehaviour {

    public Vector3 velocity = new Vector3(1, 0, -1);

    void Update() {
        transform.Translate(velocity * Time.deltaTime, Space.Self);
    }
}

```

Place an instance of this TranslateOverTime script on the prefab object you wish to instantiate.

```
public class CreateMovingObject : MonoBehaviour {

    public TranslateOverTime prefab;
    public Transform origin;
    public float moveSpeed = 5f;

    void Update () {
        if (Input.GetKeyDown (KeyCode.Q)) {
            // Create the new object where we want it to be.
            TranslateOverTime mover = Instantiate(prefab, origin.position, origin.rotation);

            // Assign it a random velocity. Its script will move it from now on.
            mover.velocity = Random.onUnitSphere * moveSpeed;
        }
    }
}

```

---
Tags: unity, c#, transformation, debugging
---


# Question
Title: Accesing child GameObjects of GameObject
I have already tried really much with all "GetChildren" and similar functions, but I haven't found out how to do it yet.

I have a GameObject named "koffer". I have added several other GameObjects as children to it.

I have added a script to "koffer" in which I try to retrieve the children. In this script I have stated this line:

```
    string sThis = this.name; //just for testing. "sThis" becomes "koffer", so it looks perfectly fine.
    foreach (GameObject g in this.GetComponentsInChildren<GameObject>()) // doesn't retrieve anything. So obviously I'm not doing it correctly.

```

However this doesn't retrieve anything. Is this not the correct function for such a case?

Is there any built-in function to retrieve theses game obects?

I have found several custom made functions from some years ago, and I don't know if they are still needed or if Unity has integrated some functions for that.

What really bothers me is that there are so many custom-made functions that deal with "Transform" instead of "GameObject". Why would somebody need Transform instead of GameObject?

Thank you.

# Answer
`GameObjects` do not have children per-se. When we talk about children to a `GameObject` we are actually referring to the *children of the `Transform` component* (that all `GameObjects` have). This means that you have to use the `Transform` component to access the children:

```
void Start() {
    // All GameObjects have a transform component built-in
    foreach(Transform child in this.transform) {
        GameObject obj = child.gameObject;

        // Do things with obj
    }
}

```

---

The reason you can't use `GetComponentsInChildren<T>()` to get the children is simply because that is not the functionality of that function. That function (like the name says) is used to get components from children (not the children themselves). For example (taken from Unity documentation):

```
void Start()
{
    var hingeJoints = GetComponentsInChildren<HingeJoint>();
    foreach (HingeJoint joint in hingeJoints)
        joint.useSpring = false;
}

```

However I guess you can *technically* use this function to get all children:

```
void Start()
{
    // This only works because GameObjects always have the Transform component,
    // and there can only be 1 transform component per GameObject
    var transforms = GetComponentsInChildren<Transform>();
    foreach (Transform transform in transforms) {
        GameObject obj = transform.gameObject;

        // Do something with obj
    }
}

```
> 5 votes

# Answer
you can use `transform.GetChild(0)` you can also get children of children `transform.GetChild(0).GetChild(0)`

or you can pull a array of each child and work with that also

```
    for (int i = 0; i < transform.childCount; i++)
    {
        //do stuff

    }

```

or

```
    foreach (Transform child in transform)
    {
        // do stuff
    }

```
> 1 votes

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


# Question
Title: How can I set decimal values to a Pygame rect position?
I'm trying to make the gravity a bit slower, like

```
Dog.rect.y += 0.5
print (Dog.rect.y)
screen.blit(background, (0, 0))
screen.blit(spikeUp0.image, (0, 0))
screen.blit(spikeDown0.image, (0, 436))
screen.blit(Dog.image, (Dog.rect.topleft))
pygame.display.update()

```

But the dog floats. The minimum I get set to `y` 1 with `rect` methods. How can I make it slower?

Here is the complete code in GitHub Gist

# Answer
> 0 votes
Ok, I did not remember that it was so easy only I had to increase the delay and done.
Sorry for inconvenience.

# Answer
> 1 votes
I'm not sure if it would work well, as I'm not familiar with pygame, but you could stick the value that you want in your `Dog` object as a `float`, and do calculations on this value, then use this value converted to `int` to update the `rect.y` variable.

```
Dog.computation_y += 0.5
Dog.rect.y = math.floor(Dog.computation_y)

```

You'll be able to control a bit more the rate at which the `y` will change. This also means that the object will not move every frame.

---
Tags: python, pygame, coordinates
---


# Question
Title: Predicted trajectory becomes less accurate in a side-on collision
In my 2D billiards game, I have it so that when the user clicks and drags with their mouse, a Physics2D.CircleCast is projected from the cueball to wherever the mouse is. If the circle happens to hit the red ball, a line is rendered from the red ball's position to the direction of the normal of the collision. So it's supposed to predict where the red ball will go when it gets hit by the cueball.

If you look at the first gif below, you'll see that it works if the red ball gets hit at its center (or close to it). The red ball ends up moving more or less along the predicted line.

However, if you look at this second gif, you'll see that if the red ball gets hit closer to its edge, the predicted line is much less accurate.

Why is this and how can I fix it?

This is the prediction code I use:

```
 if (Input.GetMouseButton(0) && cueBall)
 {
        Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        var direction = (mousePos - (Vector2)cueBall.position).normalized;
        var hit = Physics2D.CircleCast(cueBall.position, _radius, direction, Mathf.Infinity);

        if (hit)
        {
            _lineMain.Draw(cueBall.position, hit.point);
            _ghostBall.SetPosition(hit.point - (direction * _radius));
            _lineTarget.Draw(hit.point, hit.point - hit.normal); //This is the predicted trajectory.
        }
 }

```

# Answer
> 4 votes
The issue was that the radius that I inputted into the CircleCast was not accurate. Initially, I set the radius to that of the cueball's circlecollider2D, which would be .09f. But since I lowered the transform scale of the ball from 1 to .8f, that radius was no longer accurate. To get the accurate radius in code, you get either the the x or y value of its extents, which in this case would be .07200003f (.8f * .09f). So simply setting the radius to `_cueBall.GetComponent<CircleCollider2D>().bounds.extents.x` solved the problem.

---
Tags: unity, 2d, physics, box2d, billiards
---


# Question
Title: Can't Access the float value of another script. Getting Annoying Messages?
There is a float value in my scriptA. And, I'd like to access this float value and change it in scriptB. But, I am getting message that " static member ScripA.float cannot be accessed with instance reference, qualify with type instead. "

My Script A:

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

public class Rectangel : MonoBehaviour {

    public static float speed = 2;
    void Start () {

    }

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

    }
}

```

My script 2:

```
public class script2 : Monobehaviour {
public Rectangel rectangle;
void Start () {
rectangle = GetComponent <Rectangel> ();
}
void onCollisionEnter2D (Collision2D col) {
if (col.gameobject.tag == "Whatever"){
rectangle.speed = 3f;
}

}

}

```

# Answer
> 0 votes
Why do you need the speed variable to be static? When you use static it meas you are declaring a member that belongs to the Type itself and not a specific object of that type. So you can go either :

```
void onCollisionEnter2D(Collision2D col)
{
    if (col.gameobject.tag == "Whatever")
    {
        Rectangel.speed = 3f;
    }
}

```

Note this will change speed for all objects of type Rectangle. Or you can simply remove the static modifier from the definition of speed and then you will be able to change the speed on a per object basis.

---
Tags: unity
---


title: Flipped camera with Google VR

text:
# Question
Title: Flipped camera with Google VR
I just imported latest Google VR SDK into Unity and made a simple scene that has only Main Camera, plane, and single zombie just standing there with T-Pose.

In Main Camera, I added GvrPointerPhysicsRayer component, and it has GvrReticlePointer as child object.

Running in Unity Editor seems fine but when I build and run, whole world is just flipped.

I can't find any related issues about this anywhere, and struggle with this almost a day.

Why camera flipped and how do I fix it? What am I missing?

Using Unity 2019.1.0f2 and gvr-unity-sdk@1.200. Any advice will very appreciate it.

P.S. I saw the warning message in project settings - default orientation:

> Virtual Reality Support is enabled. Upon entering VR mode, landscape left orientation will be the default orientation unless only landscape right is available.

This message never disappear whatever default orientation selected.

# Answer
> 1 votes
Solved this issue by downgrading Unity to 2018.3.

---
Tags: unity, google-cardboard
---


# Question
Title: what is the difference between the regular camera and the first person camera?
I'm asked to implement first person camera but all I know is the regular camera that moves when I hit specific keys and could anyone tell me the steps to implement it?

# Answer
> 3 votes
A first-person camera is one that is always situated where a playable character's head/eyes would be, and thus always perceives the world from the perspective that that character would. This is in contrast to a third-person camera, for example, which is typically situated somewhere else in the world and sees a playable character from an external perspective.

Both kinds of camera can be programmed to move when specific keys are hit, so your definition of "regular camera" in this context is somewhat nonsensical.

First-person camera's are, however, typically controlled by having some kind of axis-based device (like a mouse or gamepad stick) yaw the view with X-axis motion and pitch the view with Y-axis motion. Another set of inputs, typically from a keyboard or the *other* gamepad joystick) move the character around the world (and thus, since the camera is tied to the character's head, move the camera as well).

Hopefully that gives you the context you need to implement your camera. Good luck!

---
Tags: c#, opengl, graphics
---


# Question
Title: Should I generate 2 array map or use tilemap?
So, I'm trying to build a 2d multiplayer bobmerman game. Right now I have whole map as 2d integer array. I'm thinking if I should change it to tilemap. In the future, I will want to be able to generate map from code, so keep that in mind.
Is it worth changing array to tilemap? What are the pros and cons of it? My server side is responsible for all the actions (movement, collision, placement), is it possible to connect with tilemap?

# Answer
A "tile map" is generally just a term for an array of some form where the elements in the array represent tiles, so generally speaking what you're presenting here is a choice between nomenclature more than anything else. It's like the difference between:

```
Array2D<int> map;

```

and

```
struct TileMap {
  Array2D<int> tiles;
};

TileMap map;

```

That said, encapsulating the underlying array in a more-specific type also lets you build some more advanced features (such as having separate, sparse arrays for item placements for example).

You can of course also change `int` to `Tile` to store more information per cell of the map.

Whether or not you *need* to make these changes or *should* make these changes is up to you: if what you have now works for you, it's probably fine. If it doesn't work for you, you should make the changes that lead you to solve whatever specific issues you have.
> 0 votes

---
Tags: java, libgdx, tilemap
---


# Question
Title: Storing Users Character in MySQL Database
Just asking a quick question about storing Characters in a database.

I am currently implementing a MySQL Database to store character data, using this current structure

Character Table:

```
playerUsername: VARCHAR(255)
characterName: VARCHAR(255)
idCharacter: INT(11)

```

Which is working fine to get all the characters that a certain person has.

While implementing this I was wondering how I would go about storing the character model data, like in WoW or other MMO's. Do they store all the models you create locally? or is that somehow stored in the database.

I have found a few structures online but they mainly contain character names and id not how the individual models are stored.

Any help on this would be greatly appreciated

# Answer
> While implementing this I was wondering how I would go about storing the character model data, like in WoW or other MMO's. Do they store all the models you create locally? or is that somehow stored in the database.

In almost all circumstances, model data itself isn't something you'd want in a database. You might store (directly or indirectly) a *reference* to some model... for example, your table might have a column for `modelId: INT`. In cases where the model can be derived 100% from existing data like the character's race and/or gender, you don't even need that.

The actual geometry data for the model, and it's textures and other rendering-related stuff should generally not be anywhere near the database. It is typically stored with the client data in a simpler file-based form, either as loose model data in a "Data" folder next to the game's executable, or stuff into a single-file archive or pack file.

---

The *reasons* you don't want model data in the database include (but are not limited to):

* you don't need it there; the database itself will never render anything, and a reference is sufficient information to allow you to distinguish characters based on model via queries (and is a much faster way to do so as well)
* it probably complicates your schema; unless each player is allowed to free-form model their avatar, most of the actual model data will be shared across many characters, so you'd want to break it into its own table to save space, but this means you now need to join against that table in some queries, making them less efficient
* it isn't where you *want* it; you want the model data on the client, where you can render. If it's on the server, you can't render anything until you log in, request that data, and wait for it to come back. This means certain features (like character previews before playing) are harder to implement because you have to deal with logging in and latency. They're impossible to implement if the connection can't be established.
* it's not actually solving a security issue; one argument for storing the data server-side is that user's can't tamper with it. Except you have to send it to them to render, so they could tamper with it then. And in any event you don't need the server-side storage to be a *database* for all the above reasons. You can achieve largely the same effect with less overhead by employing some kind of content verification hash instead.
> 1 votes

---
Tags: unity, mmo, databases, character
---


title: Can't get Instantiate working

text:
# Question
Title: Can't get Instantiate working
I am building a 2D game and I want to fire a bullet from my player whenever the player press certain button. But, When I use instantiate and add force to my rigidbody it won't work. The code is: -

```
    public bool hit;
    public Rigidbody2D gun;
    public float count;
    public Transform pos;
    public Collision2D col;
    // Use this for initialization
    void Start () {
        hit = false;
    }

    // Update is called once per frame
    void OnCollisionEnter2D(Collision2D col) {
        if (col.gameObject.tag == "firePotion") {
            hit = true;
        }
    }
    void Update () {
        if (hit = true && Input.GetButtonDown ("Fire1")) {
            Rigidbody2D gunPrefab;
            gunPrefab = Instantiate (gun, transform.position, transform.rotation) as Rigidbody2D;
            gunPrefab.AddForce (-pos.forward * 5000);
        }
        OnCollisionEnter2D (col);
    }
}

```

Here, I am trying to make the player able to shoot whenever he takes a potion. But, Neither the onCollision2D is working nor the AddForce. Why?

# Answer
Looking at your code I noticed a few things:

```
if (hit = true && Input.GetButtonDown ("Fire1"))

```

this will actually set `hit` *to* true every time! If you want to check if `hit` *is* true use `hit == true` or even better just `hit` (because `hit` is already a true/false value).

When you instantiate your `gunPrefab` you don't set the tag on the gameobject as "firePotion" so when you go into the `OnCollision2D` the thing you're supposedly colliding with doesn't have the tag and therefore doesn't make it though your if statement.

`col` is never initialised. If your going to call `OnCollision2D` explicitly as you are now you need to make sure that the `col` object actually exists, otherwise when you reach `col.gameObject.tag` in the collision method you can't actually get the gameobject because `col` is null and doesn't actually have any data and will just create a `NullReferenceException`!

---

I'd recommend attaching a debugger and just stepping though the code line by line to see what it actually does. If you can see the data changing it makes it a lot easier to understand what is going wrong. All IDEs worth your time will be able to do this.

Hope this helped
> 0 votes

---
Tags: unity, instancing
---


title: 2D isometric pixel art technique

text:
# Question
Title: 2D isometric pixel art technique
I recently started to work on a project which consists in developing a game similar to the Urbz on Gameboy Advance (the Handheld version of the game developed by Griptonite Games). This is mainly a project to learn how to make a video game from scratch, especially one in 2D (isometric in this case). I'm planning to use C++ with SFML for this project. I already have some skill in programming, but since I would also like to draw the art by myself and have no experience in that I was wondering how I could do that.

Especially, I was wondering how did the the team behind the Urbz draw their art and what kind of technique was being used? It doesn't seem to me a 'handcrafted' kind of pixel art :

I also made some research about developing a 2D isometric game engine. It seems that a popular technique is to draw the map from an isometric tileset (as shown here by eishiya for instance). However the team from Griptonite Games seems to have used several big maps, such as this :

Or am I getting things wrong ? What kind of engine/technique might have they been using ?

Many thanks for reading this post (and maybe for answering too) !

# Answer
> 2 votes
(Disclaimer: this is a subjective response to a subjective question. That's art for ya!!)

All isometric game art is composed from tiles that look like this, can be broken down into tiles that look like this, or at the very least follows the principles that can be inferred from looking at these tiles and building off a foundation of 101-tier perspective construction knowledge:

*Image description: A set of parallelograms composed of pixel lines with a slope of 0.5 or -0.5*

"Isometric art" is literally just forms built primarily of lines that either run straight up and down, or have a slope of 0.5 or -0.5. There are exceptions to this rule in construction of forms, and this is illustrated by things like: the puddle, the flowers, and the curvy portions of the bus in one of the screenshots you shared in your question.

When you consider a 3D form that'd fit inside a cube-shaped bounding box, I want you to try and imagine that cube being distorted into a (when viewed in 2D) hexagonal shape built primarily from (you may have guessed it!) straight up and down lines and lines that follow the slope rule. The resulting perspective is what defines isometric art (imo).

Now, about achieving the exact aesthetic that Griptonite Games did, here's my best guess at their workflow:

* The character art (Kris Thistle!!!) is literally just a low poly 3D model at a low resolution. If you want to recreate this, the method I would use (I'm not confident with texturing, which sorta requires knowledge of UV unwrapping, etc.) is to:

`1.) create a low poly 3D model that I'd like to work with. it doesn't have to be perfect, but it should be as close as possible to reduce work down the pipeline
2.) create a new camera and angle it until it shows the way i would like the character to be seen
3.) keeping my 3D modeling software's default lighting setup, i would then assign flat color materials to different polygon sets on the mesh. the colors should be as close as possible to the most dominant hue/shade/tint/tone that'd be in that given region
4.) look through the camera created and positioned in step 2, take a screenshot, and do a final pixel art polishing pass in an external 2D art program`

* "Big maps" like the one you screenshot and shared with us are undoubtedly (imo) made from an isometric tileset, but if you want to spare yourself the woes of logistics there is a method you can use to achieve similar results by initially creating one big image:

`1.) in a 2D art program, create or import an isometric grid (looks like cheesy wallpaper made of rhombus). layer this grid on top of whatever layer(s) you plan to create the art in, and optionally lower its opacity so you can see underneath
2.) draw, paint, or pixel your Big Map artwork on the lower layer(s), respecting or ignoring the iso grid as much as you'd like, but making sure to consider/follow the general guideline of vertical or +-0.5 slope lines during your construction of rigid forms such as buildings, vehicles, and other hard surface objects. for organic forms like people or trees, simply decide how many iso tiles they "stand" in (1x1, 1x2, 2x2, etc.), place their feet or whatever connects them to the ground strictly within that defined grid space, and then build them up to be the height that you'd like. The height of (organic) objects does not necessarily have to adhere to the iso grid, but you may want to consider defining a sub-grid that applies only to height so that you can define each object as being x units tall for a consistent feel, if that's something you're after
3a.) after completing your artwork, if you are comfortable with the asset just being one big image, feel free to stop here or to cut the whole thing into iso tiles to reuse for other artwork (works best if you strictly respect the grid)
3b.) if you want individual objects to be animated or move, I'd omit them from the big background, create them separately, and follow step 3a instead. otherwise just make sure to create each new object on a separate document layer to make it very easy to isolate them and export them as a transparent .png or what have you`

* Textures like the side of the brick building in the first screenshot you shared can be achieved by taking some image of bricks, potentially even an orthographic photograph you take out in the world (wide web), scaling them down to fit the game resolution, then skewing them with an image transform operation until they adhere to the 0.5 or -0.5 slope guideline.
* If you want to duplicate the style of their UI: you could make the buttons at a higher resolution in a 2D art program, scale them down to game resolution (consider using the Nearest Neighbour resampling algorithm for a more pixel-arty look and feel), and then optionally perform a final pixel art pass on top to make sure they look the way you want them to.
* To duplicate the general aesthetic: a LOT of the art from these screenshots you've shared gives me the vibe that they were made at a much higher resolution in an external program, scaled down to game art resolution, and then polished with a final pixel art pass.

You are right in feeling it doesn't look like 'handcrafted' pixel art! Hopefully this process will give you the results you need. If you'd like an example of how something made with this process would look in a game screen mockup, let me know in the comments! I can whip something up for you to help completely answer your question.

---

The following P.S. content is not relevant to the immediate answer of the question. All of that can be found above. I'm new to Stack Exchange, let me know if the post-scriptums should be removed completely. I'd like to be civil and avoid getting bombed by thumbs downs and/or administrative action if possible. thx \<3

---

**POST SCRIPTUM**

You state you're new to art, which is totally cool! My answer involves knowledge of external programs such as Adobe Photoshop or Autodesk Maya. If those/their alternatives are too intimidating for you to use on this project that is rather immediately happening (or is it in pre-dev?), I'd consider looking into other ways to achieve a similar effect, perhaps even just making hand made pixel art that emulates this style!

---

---
Tags: c++, 2d, isometric, art, pixel
---


title: Game Art: Martial Art Move Symbols

text:
# Question
Title: Game Art: Martial Art Move Symbols
I am still in the conceptualisation and early prototyping phase of a game that revolves around RPG/Bullet-time hybrid game where players compete in vs. style executing attack/defence moves per turn.

I am in search for art material/guidance to have symbols representing moves. For example a stick figure or a silhouette resembling a kick to represent a kick move. I am not really set on one specific style but would rather have something that covers a broad range of moves and be on the easy side to draw in not many strokes (yes player would draw the symbol).

Any guidance to get me started?

# Answer
My recommendation would be to put on some light clothes, take some martial arts classes and try to perform the moves the player-character is performing in real-life. Figure out how it *feels* to perform these moves. (or if that sounds too exhausting, at least watch some instructional YouTube videos)

What primary and secondary actions do you perform? How do you balance the momentum of your body?

Then try to translate those actions into simple gestures. A straight punch might be a straight line. A kick might be a more curved movement. An uppercut might be an up-down movement representing pulling back your fist and striking in an upward motion. A throw might be to reach for your enemy (forward-motion) grab them (draw a small circle) and pull them over (large arch).

I am looking forward to playing your game and showing my enemies the true strength of my kung-fu.
> 2 votes

# Answer
Think about the associated object(s) that best represent(s) those moves, or a clever wordplay that can succinctly convey the information (keep in mind that word play will likely not translate into other languages, and this'll add extra work if you want your game to be localized for some other country(or countries)). Some suggestions:

* **Shoe/foot for kicks**, rotated and presented at an angle to convey the motion of the action
* **Circular suburban residence for "roundhouse" kicks**, note this is likely an english-only functional symbol
* **Fist for punches**, simplified and cartoony as deemed necessary (think pacman gloves, for example)
* **Open hand for chops**, think a "paper" move from rock, paper, scissors. Rotate and angle as necessary to convey action, much like the shoe

I am not sure how broad of a range of moves you'd like to represent, which is why I included suggestions for both kicks (general) and roundhouse kicks (specific), for example. Also! My suggested symbol for roundhouse kicks serves as an example of the visual pun technique that you may be interested in using, just remember again to keep in mind that this method is NOT language-agnostic.

Hope this helps! If my suggestions seem too complicated for the player to draw, you absolutely could do something incredibly abstract, like lines or basic shapes. If you choose to go down this route please reference Lost Magic, a 2006 game for the Nintendo DS; and Magic Cat Academy, a 2006 (COINCIDENCE????) game that's playable in web browsers. There is also, as I recall, a similar "draw things to do things" game made and published by Nitrome you can search for if you feel like the first two references I suggested are not enough for you to make a decision. :- )
> 2 votes

---
Tags: ui-design
---


# Question
Title: What are the ways to deal with elevated tile blocking the view of the tile behind it?
I'm trying to make an isometric tactical rpg type of game. One issue I encountered is that if I elevate an tile, then it starts to block the view behind it. The game is 2D, so there is no freely rotating cameras.

Example:

Flat ground with a person on the top tile

Elevated ground blocking the person

Some of the options that I've thought about include:

1. When the character is blocked by a tile, display the outline of the character. But I don't like this option because it kind of breaks immersion, and makes it difficult to do "surprise" kind of factor where an enemy character jumps out from behind a blocked tile.
2. Have the option to rotate the camera by 90 degrees, 180 degrees, and 270 degrees, so you can have see all around it. However, this still doesn't solve the issue where if you have a 4 really tall tiles blocking a single tile in between since no matter how you rotate it, it's still being blocked.
3. Bigger character and smaller elevation so that even when there's elevation, you can still see part of the character behind it. This only mitigates small elevation differences like hills, but not when you are trying to make a cliff type of terrain.
4. Have only higher tiles near top of the map, and lower tiles near the bottom. This avoids blocked tile completely, but sets constraints on map making.
5. Have the option to toggle flattening the map. Such that when turned off, you can see the elevation but blocks the tile behind, and when it is turned on, you don't see elevation, but you can see all tiles.
6. Combination of the above

So the question is, is there any other ways to solve this issue?

# Answer
Yes; I have seen games that have a dithered transparency effect to show both the character and the blocking object in an (opinion) elegant way. Here's an example:

Here is one example of how you could implement this, presented in pseudocode:

1. draw objects that are "closer to the camera" first, then those that are further away
2. \[if no overlap is found, proceed to step 3\] during the exact moment a foreground object is found to be overlapping a background object that's been tagged as important (such as the player), proceed to the following substeps:
3. There are two steps:
    1. define the overlapping area, pixel by pixel, until all overlapping pixels have been found
    2. apply a dithered mask effect only to the {background element that has been drawn on top of the foreground element} as defined by the overlapping region found in substep 'a' \[you can have an option in the settings to alter the amount of dithering used, but i'd suggest a 50% checkerboard style as a default\]
4. proceed to step 1, drawing the next row of further background elements until there are no more rows to draw. if complete, end this loop
> 1 votes

---
Tags: game-design, game-mechanics, isometric
---


title: Dodge different type of obstacles

text:
# Question
Title: Dodge different type of obstacles
I'm writing a 2D game where the player has to kill a Ninja. This Ninja is coming closer with a constant speed chasing the player. The Map has some static obstacles like stones no one can pass. The player can move too and has different types of weapons to damage the Ninja in different ways:

* Laser: instantly on whole range
* Gun: projectile (circular) following a fixed path
* Trap: circular floor ability which detonates after time

I want the Ninja to dodge those Weapons the best he can, he is allowed to take some damage, the least is preferred.

I now have different ideas how to achieve that:

* A\* with 3rd dimension (time): This is working but the paths are ugly and post processing is not my favorite. Also the Graph's size is about 1000x1000, making it inefficient (on creating neighbors), i try to reduce node count by scaling the nodes to unit.hitbox (40px), which drastically improves the calcs, but the paths look even more ugly..
* Theta\*: won't work even tho I love it, but line-of-sight on moving obstacles is...
* Visibility Graph: same as Theta\*, moving obstacles...
* Steering: haven't tried this one yet how it performs with constant speed and moving (, delayed) obstacles
* Local Avoidance: won't work as the weapon speed is bigger than Ninja movement speed
* Geometry: tangents, vector projection etc.... could work well if there aren't much obstacles to dodge

Do you have any other ideas how to achieve some good doing for the poor Ninja?

(NINJAS USUALLY DODGE EVERYTHING... That's why I also plan to give the Ninja a Ninja-Roll feature he can use every 10s to dash on some position if he can't dodge something)

Representation of the raw map (little dots are 40px)

A\* Pathfinding with time dimension and a 5px-Grid

Edit: I'll check out D\*-Lite and RRT\*-Smart

Edit #2: Both are not what im looking for, i will try to optimize A\*

# Answer
I made it :D

Using A\* with time dimension. Creating the obstacle paths just one time, on cast. Then i simply do A\* and on neighbor check i check for the time the spot would have as well, if a spot is blocked, ignore it.

Result:
> 1 votes

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


# Question
Title: Do complementary shadows make sense for games?
According to color theory, shadows work better if they don't use pure blacks or grays, but instead use a color that's complementary to the color of the object casting that shadow.

That is, if you have a red apple, you should use a dark green shadow; for a yellow banana, a dark violet shadow.

But in many games, you cannot always predict what kind of background or environment the shadow will appear in, and you may not have the luxury of having dynamic shadow colors. In such cases, does it still make sense to use complementary shadows, or is a neutral black or gray acceptable?

# Answer
To me it makes no sense at all. This theory is probably just an artist sense of white balance compensation that the eye does, and wrongly gives us the feeling of shifted hues in the shadows. A shadow is just the absence of light from the considered light source. There are other light sources often in a realistic world, this is their color that comes in place. E.g. blue, often, under clear sky conditions. Which is what the theory you link to is wrongly stating as an absolute truth, without understanding why and in what conditions. Shadows in interior lighting are not blue obviously.

While the **"local color"** of the theory you link to, is no more no less than local GI, and color bleeding. The one covered typically by RSM and the likes. (LPV to a better extent).

My answer is definite, it makes no sense for games. If you have a realistic renderer it will be enough by itself. Especially if it features, either real time GI (SVO cone tracing, LPV, RSM..) or lightmapped colored GI (physically based is preferred, and of course the whole pipeline gamma correct), or/and IBL.

Now for artistic considerations, the latest point **"complementary colors"**, could be of significance in games if you want what we call a "stylized renderer", or non-photorealistic-rendering. To increase the "drama" or tend to cartoon style, or aquarel style; this would allow you to give a special touch to your game. But I repeat, from a physical perspective it makes no sense appart from what I said in my first sentence: this must be some natural feeling of artists in their position of nature-observer, that results from white balance compensation.
> 42 votes

# Answer
For drop-shadows it doesn't work very well for the reasons you already stated. You never know how many drop-shadows you will have in the scene and differently colored shadows from different objects can look strange. However, it can work nice for self-shadows, especially in a 2d game. This screenshot is from Seiken Densetsu 3 (Squaresoft 1995):

Notice how the shaded parts of the tree use violet as a complementary color to the yellow highlights in the lighted parts and how well it works. But also notice that the artist decided to not color the drop-shadow of the tree.
> 14 votes

# Answer
If you use **alpha blending** you can lay down a complimentary shadow that will work against any background.

It may or may not be any better or faster though. This is something that is likely to change depending on your specific game.

I don't have enough rep to comment on @v.oddou's answer, but I want to say that while purposefully making shadows complimentary might not make sense in a reality simulation rendering, in games there's many cases where it might make sense. Such as his example of it being done for artistic effect.
> 9 votes

# Answer
Objects are rarely lit entirely by a single point light source. In most cases, objects will receive much of their illumination from a dominant point source, but receive additional illumination from other point or sources, including some diffuse light which has been scattered by either by other objects or (for outdoor scenes) by the atmosphere. If an object is lit by a bright white point source, but is lit by a bluish ambient light that is only 2% as bright, the color of the ambient light won't noticeably affect the portions of the object which are lit by the primary point source, but will be very visible in those portions which are primarily lit by the bluish ambient.

In some contexts, it may make sense to keep track of the color of ambient light, and have shadows be tinted slightly as a consequence of it, but I don't see a reason for having objects cast shadows whose colors are the complements of the object colors.
> 5 votes

# Answer
The complementary colour thing is actually illusory. Set up a lemon on some white paper and photograph it. The shadow will have yellow in it, not purple, due to the yellow light being scattered off the lemon.

Now, to the matter of whether to use it in your game. If you're going for a painterly art style, then you could certainly include it, though it will require some additional coding of shaders to implement it (which you could well end up doing, anyway, depending on how sophisticated you're making your non-photorealistic rendering system).

If, on the other hand, you're aiming for a realistic style, just don't worry about it.
> 3 votes

# Answer
Wouldn't it seem a bit strange to see things in a row of different colour, with different coloured shadows ?

To me, the picture of the various fruit doens't look like 3 pieces of fruit on a white background; it looks like 3 different pictures of fruit, probably because the different colour shadow hints at them being in a different context.

I daresay this is subjective, but I find it a bit questionable - I'd also agree with what v.oddou says, although this assumes you're trying to get things to look 'realistic'.

Ofcourse the other jiob of shadows is to give a hint at how high off a surface an object is. No shadow = you can't tell whether it's 1 for above or 40 ft (or whatever the units are). If there's a shadow of any sort, your brain does the calculation for you and yo have a stab at guessing when an object will bounce, or whether it's possible to run under it etc. For that function, I'd think just a greyscale shadow mixed in with background colour, if possible, would do the trick.

There's also the odd natural effect when there's more than one source of light, of different colours. If you had a few coloured lights giving basically a white light mix, un-shadowed background would give a mixture of all colours but if there's a shadow blocking say blue light, the shadow may look relatively reddish.

Even in reality this looks a bit strange! So my answer would be : while it's an interesting notion and possibly worth experimenting with in some still images (or finding examples), I'd expect to find it's not worth putting the effort in to calculate the shadow colour.
> 1 votes

# Answer
I have considered doing this before for an NPR renderer since I have a visual arts background and always loved the look of certain types of popular sci-fi and fantasy artwork that exaggerated this effect, but as others noted, it makes no sense from a physics standpoint. There's no way you're going to have blue light in a shadow unless something is actually reflecting blue light into it.

But if you are going for a non-photorealistic renderer, the effect might be very beautiful with the contrasting hues (though in a painterly way, not a realistic way). That said, I would suggest using the color of the light source(s) being excluded to tint the shadow, not the material of the object occluding the light. That should simplify the computation and still ties all the elements of the composition together. For example, a warm light from a fire place might cast a cool blue shadow when the light source is occluded, even if there's no blue objects to reflect light into that shadow let alone much blue light in the first place.

The second thing to note is that the artist's color wheel is based on the subtractive nature of mixing pigments. It's not based on complementary light colors. As a result, the artist's color wheel considers, say, green to be a complementary color to red:

... not cyan, and mixing those two pigments would result in an ugly brownish/grey color, not white as we'd get with additive mixing of light. Likewise the complement of blue would be orange instead of yellow, and so forth. To emulate the look effectively would probably require using this type of color wheel.
> 1 votes

# Answer
This question is very old, and has many answers, but I went to art college. Here is my answer:

The theory as you have stated it, according to my knowledge, is only partially correct. In reality, the color of shadows are the complement of the **color of the light source**. If you think about it, it makes sense: a cast shadow can be defined as blocked light, and if you have for instance a yellow light (the sun) you will be left with a bluish cast shadow. To illustrate this point, please consider "The Green Stripe" by Matisse (someone who may be referred to as 'one of the old masters' or whatever):

link to google image search results for "The Green Stripe".

Please note how the red light, which is being cast from the right side of the frame, leaves a dark greenish core shadow and a yellowish reflected highlight. Green is the complement of magenta, and yellow is the sum or green and red (additive color theory).

Recall that the theory as you state it is partially correct! In close-up cases of brightly colored and reflective objects on a white surface, such as the image you linked with the apple, the ambient light in the room is hitting the dark side of the apple and reflecting the apple's color onto the surface on which it rests. The core color of the shadow is still the complement of the color of the light source!! In a studio environment (the kind of place where you find lone apples on white void-like surfaces), your light source is likely artificial and as close to pure white as possible so that people working with color and pigments in that environment do not have their understandings of color skewed due to a colorful light (try painting the same thing twice under sunlight and then in a photographic dark room (red)! compare those results lol).

Now! to answer your question: dynamic shadows, or even just statically colored shadows are extremely doable. Do they fall within the scope of your project with consideration to time, money, and labor required? Well that's a completely different question that you need to answer for yourself!! Gray/black shadows are a SIN (imo) and you should avoid them if you want your game to generally be considered aesthetically pleasing. You do not need to predict the background, environment, or take into account the object color. The only piece of info you need for easy and natural shadows is the color of the light source. Consider this screenshot from attack on titan: LINK

Shadows in my game are always a dark and desaturated complement of the color of my game's light source(s): RELATIVELY EASY, several games already do this

Shadows in my game take into account ambient occlusion, bounce light, the color of multiple light sources and types, etc. etc.? That's already a lot of gosh darn work. If you're an indie developer whose primary focus is making games rather than graphics programming or tools dev, this is absolutely not worth your time (opinion).

Thanks for reading, hope this helps whoever visits this ancient problem in the future!!! :- )
> 0 votes

---
Tags: color, graphics-design
---


# Question
Title: How can I find an optimum set of colors for 10 players?
I want to give each of 10 players a unique identifying color. Is there an optimum set of colors for this? How do I create one?

Every set I've come up with contains colors that are too similar.

Update: I was asked below what this is for (fair question). Now I can tell you - Windwardopolis and the colors worked great.

# Answer
> 357 votes
You could generate equidistant hue values in the HSV space:

```
for (int i = 0; i < 10; i++)
    colors[i] = HSV(0.1 * i, 0.5, 1.0);

```

However, it’s possible that you will not always have 10 players. In that case, the palette would not be very efficient unless you re-generated a different palette for another number of players. Instead, some authors recommend generating a palette using the golden ratio, taking advantage of a property resulting from the equidistribution theorem:

```
for (int i = 0; i < 10; i++)
    colors[i] = HSV(fmod(i * 0.618033988749895, 1.0), 0.5, 1.0);

```

That way, even if you stop at 3 or 4 or 7 players, you get a very good hue spread.

Many irrational numbers will do, but the golden ratio will work best (it has been proven).

Finally, you can use two different generating sequences in order to tweak `S` or `V`, too. For instance (**edit**: I added the `sqrt` call for better equidistribution):

```
for (int i = 0; i < 10; i++)
    colors[i] = HSV(fmod(i * 0.618033988749895, 1.0),
                    0.5,
                    sqrt(1.0 - fmod(i * 0.618033988749895, 0.5)));

```

**Update**: the above results can be improved by using a correction curve for `H` (similar to the gamma curve for RGB components) that takes the human visual system into account. This is the hue correction curve that I computed using the CIEDE2000 metric:

The results for equidistant hue values are as follows:

And for the golden ratio generation sequences (with and without tweaks on `V`):

I will publish an approximation of the curve formula for use in programs as soon as I find a reasonably good one.

# Answer
> 179 votes
The 8 StarCraft colors are:

> Red, Blue, Teal, Purple, Orange, Brown (green in desert maps), White (green on ice maps), Yellow

Obv. Blizzard are UI geniuses and have studied the problem.

They left Green out as a swap-in for Brown on desert maps, so technically there are 9 listed there.

The **12** Warcraft 3 colors are:

> Red, Blue, Teal, Purple, Yellow, Orange, Green, Pink, Grey, Light Blue, Dark Green, Brown

Here's how this looks:

As you can see, they are quite distinct and easily distinguishable. Dark green is actually easy to distinguish from teal, possibly because the human eye can most easily distinguish shades of green. If you're sure your players will be female tetrachromats you probably could pick any colors though.

# Answer
> 81 votes
A few people here recommend dividing up HSV color space at 10 equidistant positions on hue. In my opinion, this is actually not a good solution. The human eye does not perceive differences in color equally across the HSV spectrum. For example, what we'd call orange occupies a tiny slice of the band, whereas a good 25% chunk might qualify as green. So it starts with a bad premise. Look at the first row of colors in this answer. The two greens are almost indistinguishable.

Remember your users will need to communicate about and refer to the colors. In light of this, the Starcraft/Warcraft theme is a great lead to follow. Choosing based on a list of plain English Crayola colors is not a bad idea at all, because you'll end up with familiar named colors. Then just tweak those colors to be bold, muted, whatever matches your aesthetic, as long as they're still recognizable as i.e. Red, Orange, Yellow, Green, Blue, Purple, Brown, Gray, White, Black.

Edit: the connection between language and color perception is so interesting, I just wanted to share this awesome link:

*The crayola-fication of the world: How we gave colors names, and it messed with our brains* on Empirical Zeal

# Answer
> 31 votes
I thought I needed to break this "symbols" approach out into a separate answer.

Back in the day, I assume people needed flags and stuff to easily identify armies way off in the distance so that they'd know whether to attack or defend (in case of foes) or be relieved (in the case of allies).

So, incidentally, that's exactly what you're trying to do: to easily identify something off in the distance.

You can do that with just color, but possibly a better way to do that is with *color and symbols*. Using a combination of colors *and symbols* **will help colorblind people** identify things, as many people mentioned above.

If the units are big enough, you could also go with 2-4 color coats of arms.

The **pattern** is easily recognizable, not just a color. Good texturing could brand the coat of arms quite large on the chest or upper arm of each unit.

In the image above, the helmets for different units **have different geometry**, as well as the shield insignia.

You may find also interesting the idea of Japanese Mon, which are very simple looking "logos"

Now you're basically branding your units with modern "brands". StarCraft II did this a little bit with "decals",

but these are barely visible in-game

and aren't used for identifying units so much as colors are.

I'd look at flags as well for inspiration, particularly the ones that don't use a 3-stripe brand pattern (those become a little confusing). These countries all have some very simple-looking, yet distinctive flags:

| Switzerland | Somalia | South Korea |
| --- | --- | --- |
|  |  |  |

Also check out symbols that the American government uses to identify defense staff. These are **monochrome images** (can be done completely in black and white), so this might actually be a great solution that will not exclude colorblind people (basically use **symbols** to identify teams, instead of colors)

# Answer
> 25 votes
Why reinvent the wheel? There even is a standard for a set of sixteen colors, of which you could pick ten. This is the ANSI set http://en.wikipedia.org/wiki/ANSI\_escape\_code#Colors

The ANSI colors are **equally distributed on the RGB cube**, which is, I think, better suited for this problem than the HSV space.

When taking the extremes of the RGB cube, you get familiar colors, like red, blue, cyan, etc. After the eight corner points, you get all the points in between, on the edges.

# Answer
> 21 votes
Making 10 colors that can be distinguished is going to be really difficult. This is a pretty common issue in creating graphs or charts for many values, which is why they often use color and shape or color and hash pattern combinations.

If you need to display markers, you can use 4 basic colors (red, blue, orange, black for example) and four basic shape (square, circle, triangle, diamond) and get 16 very easy to distinguish markers.

If you are coloring in areas, use the same idea but combine colors with hatch patterns in black or white lines instead of shapes.

Another thing to consider is to not use color as the only way to tell the side. Mousing over an area could highlight it and give a tool tip with the player name explicitly stated. Or maybe a list of the 10 players can be moused over, and as one hovers over a player name, all areas on the map for that player are shown.

Also, while choosing colors, keep in mind color blindness. Green and Red for example may not be distinguishable. Take a look at http://jfly.iam.u-tokyo.ac.jp/color/#select for a set of suggested colors that will not be an issue for colorblind individuals. An additional resource is http://www.usability.gov/articles/newsletter/pubs/022010new.html#ColorsthatWorktheBest

# Answer
> 7 votes
Even if you can get 10 unique colors that are distinguishable easily by one person, another person may still find this set harder to distinguish.

Consider limiting yourself to a **smaller set of colors, and adding a distinguishable feature**, like a **black stripe**. For the set of colors, it's probably best not to stray too far from what most people can distinguish easily: **ROYGBIV**. A simple stripe/no-stripe on ROYGBIV gets you 14 identifying game pieces.

You don't have to limit yourself to a black stripe, either. Consider the following solution for wiring 25 pairs (which could just as easily be stripes instead of pairs): http://en.wikipedia.org/wiki/25-pair\_color\_code

# Answer
> 4 votes
Brent Berlin and Paul Kay showed that colour space can be divided up into just a few basic colours, but it depends on your culture in that giving a name to a colour makes it more distinguishable.

In English, there are 11 basic colours: white, black, red, green, yellow, blue, brown, purple, pink, orange and grey.

I don't like the idea of choosing hues around a wheel for much the same reasons as Matt Montag stated

# Answer
> 4 votes
Just wanted to throw in a reference to the Tableau-10 palette that was developed for high distinctiveness and which is described in this paper:

http://vis.stanford.edu/files/2012-ColorNameModels-CHI.pdf

"The Tableau-10 palette provides the best color salience and minimal name overlap."

# Answer
> 3 votes
Try this color mixer: w3schools.com HTML Color Mixer.

Here's what I'd do: select a color for the first option. Then, select one for the 2nd option so that the 2nd color is at the exact opposite position with regards to the first one. So the color at position: Row 1, Cell 1 would have the opposite: Last Row, Last Cell.

That way you end up with 2 very different colors at the mix's extremities every time. Repeat this 5 times, always selecting colors that are far apart from the last selection.

# Answer
> 3 votes
Do more than just colors- have visual representations that add to both the lore, the art style, and representation of color.

For example Legend of the Five Rings uses an incredible way to differentiate between "set of colors".

One of the most beautiful examples to take a lesson from. Take note the hundreds of ways they differentiate between the Clans. It's not just primary colors, but secondary and even tertiary colors as well. The colors are even included in hair style, type of wear, type of character, a symbol attached, flags, banners, mini-flags on the back, personalities.

The biggest thing I would take from this is the combination of multiple colors. It is not a simple : Blue, Red, Purple, Brown, Yellow, Green, Teal.

It is a combination of two colors, with both being very pronounced. This can allow for a significant amount of additional number of players.

Each clan would have both a primary color, and a set of secondary colors.

"The Crab was mostly identified with blue-gray, plus black, red, and brown colors."

It is beautiful, because no matter what the person looked like (large, frail, samurai, wizard, peasant) you could always tell which clan they were from. It wasn't just "Red" for Scorpion, it was a dark Blood Red and BLACK. While Phoenix had sunburst colors: red, orange, yellow.

You would never confuse a Scorpion with a Phoenix, even if their colors were similar and they both used a lot of red.

# Answer
> 2 votes
This question has many answers, but I wanted to touch more on accessibility.

If I were in your scenario (needing to choose colors for an amount of things in a game that need to be perceived as distinct by all players involved), my primary concern would be accommodating not only players who are colorblind, but also players who have low vision.

The only solution to this issue as far as I am aware is **VALUE CONTRAST**. Some people can only see in black and white (source: a friend from art college's stories about taking a color theory class whilst being unable to perceive any color at all due to a failed laser eye surgery). Some people are low vision or partially/legally blind. You need *distinct shades of gray* as a starting point so that the colors you **DO** choose are viewable and distinct for **EVERYONE**.

In order to accomplish all this and have colors that look good, please consider this image, obtained by layering a horizontal rainbow gradient in color blending mode on top of a vertical black-to-white gradient (try it yourself, perhaps with a custom color gradient other than rainbow!):

**From darkest to lightest: black, blue, red, magenta, green, cyan, yellow, white.**

Can you see the faint zigzag of "pure color"? THAT is the natural value of colors illustrated. Even when using pure colors, blue is darkest and yellow is lightest. Utilize this information to choose colors that both fit the value requirements for gamers whom colorblind and/or low vision **AND** are aesthetically pleasing to people who can perceive the full majesty of your selected hues.

Hope this helps! :- )

---

---

P.S. I want to make sure you've seen this comment as well!

> The best answer to color blindness it simple not rely on color. Every player should ideally have a unique silhouette to any actors he controls. And I do mean silhouette, not some kind of symbol; too many of the Match 3 kinds of games get this totally wrong, and even for someone without color blindness, they're just hard to play and cause too much eye strain. – Sean Middleditch Dec 30 '12 at 5:08

# Answer
> 1 votes
A way to ensure the optimum set in terms of distinguishable colors for a variable number of players (without taking color blindness into account) would be to choose from the HSL (Hue, Saturation and Lightness) color model.

You pick a constant lightness and saturation, depending on your choice. Then you shift the hue of the color by `360 / playerCount`, like in the following pseudo code:

```
saturation = 200;
lightness = 128;
hueDelta = 360 / PLAYER_COUNT;

for (int i = 0; i < PLAYER_COUNT; i++)
    color[i] = Color.FromHSL(hueDelta * i, saturation, lightness);

```

# Answer
> 1 votes
I want to present an alternative color scheme:

These are the RGB colors (same order) with suggested names:

```
#eeeeee - white
#efef00 - yellow
#00e1da - cyan
#bfbf00 - olive
#12c055 - light green
#e21e80 - pink
#777777 - gray
#c10008 - red
#8900ae - light purple
#7c3900 - light brown
#0029b9 - blue
#400086 - dark purple
#4b1c00 - dark brown
#003004 - dark green
#07004b - dark blue
#111111 - black

```

Note: I did not use pure black and white, thinking that perhaps they are used as background or outlines.

Metodology: picked 12 colors on the saturated face of the color cube (thinking I would be happy with 12), eyeballing their separation, and then - using a tool to simulate color blindness - started tweeking. Afterwards, I added a near white, a near black, and sneaked a gray, because I could. That gave me 15 colors. I wanted 16 colors because it is a power of 2, and I though it could make things easier for developers. Eventually I found a way to add a 16th color, I had to move the others around for that. Then... check again with the color blindness simulation tool, fix and repeat.

Here are the different color blindness cases:

Normal:

Protanopia:

Deuteranopia:

Tritanopia:

Protanomaly:

Deuteranomaly:

Tritanomaly:

Achromatopsia:

Achromatomaly:

---

After playing with the color blindness simulation tool for a while, I have to say, contrast is paramount.

Consider for example, consider the 5th (light green), 7th (gray), and 9th (light purple) colors. They look similar on some cases, in particular in small size and separated by another color. However, put them side by side and you can tell them apart. Increase the area covered in the color and you can tell them apart much more easily. So... designing for color blindness is not only picking colors.

On that note... if you pick a combination of two colors instead of one to represent a faction, this goes a long way.

These color were picked by a very empirical method. I notice that a very important point is to make sure they are all of different brightness. I also notice that most "colors" appear twice (there are two greens, two purples, two browns, etc...). In fact, the 4th color (olive) is the last I added, and I decide it would be a yellow-like color, because there was nothing like yellow. I suppose that can be the basis for a more systemic way to pick colors.

*In retrospective, I probably should make the second yellow-like color (olive) darker, and use that brightness spot for a pink (see 7th color). ¿Why? Because it would give you more shades to play with. Ern... this is good enough, and getting all the pictures is a hassle.*

**Addendum**: Something I didn't consider is how LCD screen distord colors if you look out of the prefered angle range.

---
Tags: multiplayer, color, visualization, usability
---


# Question
Title: How do I wait until the player has reached the gameObject to perform the interaction?
If the player clicks an object to move the player sprite to the object and interact with it, how do I wait until the player has reached the gameObject to perform the interaction?

I have the interaction hooked up okay, but it is executing as soon as the click occurs. I would like the order instead to be (player clicks on object) (player walks to object) (once player is close enough to object the interaction occurs). But if the player moves away before reaching the object then the interaction is cancelled.

I'm not sure if I should use the object's onTrigger? But my question is if I use onTriggerEnter for the gameObject, and then the player cancels the interaction before reaching it, how do I cancel the ontrigger? Is there a better way? Also, I cannot always use an onTriggerEnter because sometimes it is clicking on an empty tile and I want to wait until the player has reached the tile.

Thanks!

# Answer
Okay, fixed this with

```
/*
 * Postpones the ineraction with the clicked on object until the player
 * has arrived.
 */
void WaitUntilArrivalToInteract(Vector3 clickedWorldPosition,
                                TileBase clickedGroundTile) {
    atDestinationCoroutine = WaitAndHandleClickInteraction(clickedWorldPosition,
                                                           clickedGroundTile);
    StartCoroutine(atDestinationCoroutine);
}

/*
 * Waits until the player is within a specific distance to interact with
 * the target object.
 */
public IEnumerator WaitAndHandleClickInteraction(Vector3 clickedWorldPosition,
                                                 TileBase clickedGroundTile) {
    yield return new WaitUntil(() => {
        float remainingDistance = (transform.position - targetPoint).sqrMagnitude;
        return remainingDistance < Constants.DISTANCE_UNTIL_AT_DEST;
    });
    HandleClick(clickedGroundTile, clickedWorldPosition);
}

```

And I think I should be able to interrupt this by stopping the coroutine.
> 1 votes

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