# Question
Title: Why can I only connect one client to my server?
I am currently working on a Udp server and client system, where I worked out a way to "verify" which user is sending the updates. Essentially, the very first package they send is "blank", which the server takes in, increments a list by 1, and then does a `Send()` to the port, which I believe should go to all connected Clients (please correct me if I'm wrong on this assumption). The client will ignore any new "ID's" that are coming in after theirs is assigned, and the ID part of the server will ignore any packages that don't start with a blank space.

**My current issue is:**

I can't seem to get more than one client connected, and I'm a little stumped on why.

**Server/Client Manager:**

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

public class ServerManager : MonoBehaviour
{
    private GameObject serverGO;
    private Thread serverThread;
    private Thread clientThread;
    private Server1 serverScript;
    private Client1 clientScript;
    private bool serverThreadRunning = false;
    private bool clientThreadRunning = false;

    // Start is called before the first frame update
    void Start()
    {
        serverGO = this.gameObject;
        serverScript = new Server1();
        clientScript = new Client1();
        serverThread = new Thread(serverScript.Listen);
        clientThread = new Thread(clientScript.SendData);
    }

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

        Debug.Log(serverScript.GetClientID().Count);
        Debug.Log(serverScript.GetContact());
    }

    private void OnApplicationQuit()
    {
        serverScript.done = true;
    }

    private void Control()
    {
        if (Input.GetKeyDown(KeyCode.P) && !(serverThreadRunning) && !(clientThreadRunning))
        {
            serverThreadRunning = true;
            serverThread.Start();
        }

        else if (Input.GetKeyDown(KeyCode.L) && !(serverThreadRunning) && !(clientThreadRunning))
        {
            clientThreadRunning = true;
            clientThread.Start();
        }

        if (Input.GetKeyDown(KeyCode.M) && clientThreadRunning)
        {
            clientScript.disconnect = true;
        }
    }
}

```

**Server:**

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class Server1 : MonoBehaviour
{
    private CancellationTokenSource cancellationSource = new CancellationTokenSource();
    Dictionary<int, IPEndPoint> clientID = new Dictionary<int, IPEndPoint>();
    private int done = 0;
    public string rds;

    public void Listen()
    {
        int port = 8080;
        Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint ep = new IPEndPoint(IPAddress.Any, port);
        UdpClient listener = new UdpClient(ep);
        byte[] rData;
        string rDataString;
        byte[] sendData;
        string sendDataString;
        var token = cancellationSource.Token;

        try
        {
            while (token.IsCancellationRequested)
            {
                var receiveTask = listener.ReceiveAsync();
                var result = receiveTask.Result;
                rData = result.Buffer;
                rDataString = Encoding.ASCII.GetString(rData);

                if (rDataString.Equals(" "))
                {
                    var clientAddress = ep.Address;
                    ep = new IPEndPoint(clientAddress, port);
                    var id = (clientID.Count + 1);
                    sendDataString = id.ToString();
                    sendData = Encoding.ASCII.GetBytes(sendDataString);
                    clientID.Add(id, ep);
                    var clientEP = result.RemoteEndPoint;
                    serverSocket.SendTo(sendData, ep);
                    //serverSocket.Close();
                }

                else
                {
                    rds = rDataString;
                }
            }
        }

        catch (Exception e)
        {
            Debug.Log("Server error: " + e.ToString());
        }

        listener.Close();
    }

    public Dictionary<int, IPEndPoint> GetClientID()
    {
        return clientID;
    }

    public string GetContact()
    {
        return rds;
    }

    public void Stop()
    {
        cancellationSource.Cancel();
    }
}

```

**Client:**

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System;
using System.Text;

public class Client1 : MonoBehaviour
{
    private GameObject player;
    private Transform playerPos;

    public bool disconnect = false;
    public bool requestClientId = false;

    public void SendData()
    {
        Move updatePlayer = new Move();
        GameObject player;
        Transform playerPos;
        Client1 parent = new Client1();
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        int port = 8080;
        IPAddress ip = IPAddress.Parse("10.10.33.24");
        IPEndPoint ipep = new IPEndPoint(ip, port);
        bool disconnect = false;
        byte[] sendData;
        int clientID = -1;
        byte[] rData;
        string rDataString;

        while (true)
        {
            if (parent.disconnect != disconnect)
            {
                disconnect = parent.disconnect;
            }

            try
            {
                if (clientID < 0)
                {
                    sendData = Encoding.ASCII.GetBytes(" ");
                    clientSocket.SendTo(sendData, ipep);

                    UdpClient listener = new UdpClient(ipep);
                    rData = listener.Receive(ref ipep);
                    rDataString = Encoding.ASCII.GetString(rData);

                    clientID = Int32.Parse(rDataString);

                    listener.Close();
                }

                else if (clientID > 0)
                {
                    sendData = Encoding.ASCII.GetBytes("didit");
                    clientSocket.SendTo(sendData, ipep);
                }
            }

            catch (Exception e)
            {

            }

            if (disconnect)
            {
                clientSocket.Close();
            }
        }
    }
}

```

This is clearly an unfinished product, I am aware I'm missing some key future pieces (removing players from list, having the designated time for the server to do a `listener.Close()`), but for now I'm just trying to get multiple clients connected at the same time, and am looking for a point in the right direction.

---

**Edit:**

Updated Server code

# Answer
---

## Update

*These are the lessons learned from fixing this problem:*

We found the following issues when reviewing the network code:

1. \[Client/Server\] `UdpClient.Receive` alters the `IPEndPoint` you pass to it by reference. So, do not use the same endpoint you use for sending.
2. \[Server\] We needed to use `ReceiveAsync` on the server to be able to interrupt it. Which we do with a `CancellationToken`. However, `ReceiveAsync` does not take a `CancellationToken`, thus we need to take the task it returns and call `Wait` with the token, then take the result of the task. *Which also makes it pointless to use async/await, since we should not `await` the task to be able to pass the `CancellationToken`*. which also means the server networking code must run on its own thread, we already knew that part.
3. \[Server\] Since we are using a `CancellationToken`, we will make a loop `while(!token.IsCancellationRequested)` on the server thread. *It was an easy mistake to make to forget that `!`, my bad.*
4. \[Client/Server\] Speaking of simple mistakes. Having `Debug.Log` calls helped indentify some problems. You should have it in your `catch`. `Debug.Log` also helped figure out...
5. \[Client\] We should not create an `UdpClient` using the server endpoint※, or any endpoint that specifies a port for that matter. That would make it listen on that port, and we cannot have multiple clients on the same machine listening on the same port at the same time. ※: With the server and the client running on the same server, this was preventing the client from receiving.
6. \[Client\] Instead we should create an `UdpClient` and set the socket, something like this: `var listener = new UdpClient { Client = clientSocket }`. And while we are at it, why not use a `using` statement?
7. \[Client\] Turns out that disposing the `UdpClient` closes the socket. *Thanks `Debug.Log`.* Thus, do not create an `UdpClient` every time you want to listen, just create the socket and the `UdpClient` once before the loop. In fact, put the loop inside the `using` statement.

**Bonus:**

* You can restrict from where the `UdpClient.Receive` will receive by setting the `IPEndPoint` you pass to it. Which it will modify. Thus, on the client, create a new `IPEndPoint` to pass to `Receive`, make it equal to the one used to send to the server. But do not use the same `IPEndPoint`, becase `Receive` modifies it, and then sending does not work. *Did I mention that `Receive` modifies the endpoint?* The server does not have that problem by virtue of using `RecieveAsync`, which arguebly isn't a bad idea to use on the client too.
* It could be a good idea to have a `Dictionary<int, IPEndPoint>` to store the `IPEndPoint` of each client on the server. So, when the server needs to send to a particular client, it look up there by id. Similarly, it could be a good idea to have a `Dictionary<IPEndPoint, int>` so the server can recognize the client by its endpoint, and thus know which one is sending.

**Note**: We are not setting the ip and port of the client (by not creating the `UdpClient` with the `IPEndPoint` but setting the socket instead). We are only setting the ip and port of the server. The ip of the client is whatever it is, and the port is whatever the system assigns to it. That means that when you have multiple clients on the same machine, they end up with different ports, and thus they can all listen at the same time.

---

## Addendum on what does Receive actually do

This the reference code for `UdpClient.Receive` (I replaced the comments with my own):

```
public byte[] Receive(ref IPEndPoint remoteEP) {
    if (m_CleanedUp){
        throw new ObjectDisposedException(this.GetType().FullName);
    }

    EndPoint tempRemoteEP;

    if ( m_Family == AddressFamily.InterNetwork ) {
        tempRemoteEP = IPEndPoint.Any;
    }
    else {
        tempRemoteEP = IPEndPoint.IPv6Any;
    }

    int received = Client.ReceiveFrom(m_Buffer, MaxUDPSize, 0 , ref tempRemoteEP);
    remoteEP = (IPEndPoint)tempRemoteEP; // <- removeEP is set, never read

    if (received < MaxUDPSize) {
        byte[] newBuffer = new byte[received];
        Buffer.BlockCopy(m_Buffer,0,newBuffer,0,received);
        return newBuffer;
    }
    return m_Buffer;
}

```

We can observe that from where the `UdpClient` will receive depends on how it was set up, not the passed `IPEndPoint`. In fact the passed `IPEndPoint` is set, never read. If we look at `UdpClient.Receive` in .NET Core we can see the same remains true. I have also confirmed with Telerik JustDecompile. Therefore `IPEndPoint remoteEP` should have been an `out` parameter, not `ref`.

---

## Old answer

1. `Receive` sets `ep` (passed as ref) to the end point at the other side, the one that sent the data.
2. `SendTo` sends to the endpoint provided:

```
serverSocket.SendTo(sendData, ep);

```

---

Your code does not multi-cast. And I would argue you should not be trying to multi-cast anyway.

The server can build a dictionary of client ids and end points. Then it can send to the right client.

Something like this:

```
Dictionary<int, IPEndPoint> clients = new Dictionary<int, IPEndPoint>();

```

---

Which remind me, **`Receive` blocks the thread**. Remember that when writing the code. I will also remind you that there is a `ReceiveAsync`, which despite the name was not created to work with `async/await` (hence the lack of `CancellationToken` on the call, you are supposed to call `Wait(cancellationToken)` on the task it returns).

---

## Addendum on threading and cancellation

Currently the server class has a field `public bool done = false;`. For encapsulation, let us make that private and add a `Stop` method.

```
private bool done = false;

public void Stop()
{
    done = true;
}

```

And, of course, on the server manager, we will change

```
serverScript.done = true;

```

to

```
serverScript.Stop();

```

This is *better*, bot not good. However, this change is necessary because we will start messing with it.

The problem is that the value of the `bool done` might never be visible to other thread. We can improve that situation by using a `volatile`.

```
private volatile bool done = false;

```

That *should* work, at least better. It does not work well in some old and buggy platforms. Hopefully none of those is out there, regardless I am paranoid on threading, so I recommend using `Thread.VolatileRead` and `Thread.VolatileWrite` or `Volatile.Read` and `Volatile.Write` depending on the platform.

Would look something like this:

```
private int done = 0;

public void Stop()
{
    Volatile.Write(ref done, 1);
}

```

And the check:

```
while (Volatile.Read(ref done) == 0)
{
    // ...
}

```

And we are not there yet. Why? **`Receive` blocks the thread** Which means that the thread would be waiting on the data from the client, and thus would not notice that `done` changed...

Alright, so we neeed a `CancellationToken`. The idea is that we will create a `CancellationTokenSource`:

```
private CancellationTokenSource cancellationSource = new CancellationTokenSource();

public void Stop()
{
    cancellationSource.Cancel();
}

```

Then the check looks like this:

```
var token = cancellationSource.Token;
while (!token.IsCancellationRequested)
{
    // ...
}

```

**Note**: We want to loop while the cancellation has not been requested.

We are taking the token, we are going to need it for `Receive`... or rather `ReceiveAsync`:

```
var receiveTask = listener.ReceiveAsync();

// The following call can be interrupted by the token
// It will throw `OperationCanceledException` if that happens, catch it
receiveTask.Wait(token);
var result = receiveTask.Result;

// This is the data from the client
rData = result.Buffer;

// ... you can check for " " here ...

// Store the following endpoint in the client dictionary
// and use it to send data to the client
var clientEP = result.RemoteEndPoint;

```

**Note**: This API was not designed to be used with `async/await`, so do not try to convert the code to use `async/await`.

---

I'd expect the code to look like this:

```
var id = (clientID.Count + 1);
sendDataString = id.ToString();
sendData = Encoding.ASCII.GetBytes(sendDataString);
var clientEP = result.RemoteEndPoint;
clientID.Add(id, clientEP);
serverSocket.SendTo(sendData, clientEP);

```

---

## Addendum on BeginReceive

If `ReceiveAsync` is not working, we have another option in `BeginReceive`. The following is adapted from the MSDN example:

```
private int done;
private Dictionary<int, IPEndPoint> clientID = new Dictionary<int, IPEndPoint>();
private Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// public string rds;

private void Handle(IPEndPoint clientEP, string receiveString)
{
    if (receiveString.Equals(" "))
    {
        var id = (clientID.Count + 1);
        sendDataString = id.ToString();
        sendData = Encoding.ASCII.GetBytes(sendDataString);
        clientID.Add(id, clientEP);
        serverSocket.SendTo(sendData, clientEP);
    }
    else
    {
        // rds = rDataString;
    }
}

private void ReceiveCallback(IAsyncResult ar)
{
    if (Thread.VolatileRead(ref done) == 1)
    {
        return;
    }

    var listener = ((UdpClient)(ar.AsyncState));
    IPEndPoint clientEP;

    byte[] receiveBytes = listener.EndReceive(ar, ref clientEP);
    string receiveString = Encoding.ASCII.GetString(receiveBytes);

    Handle(clientEP, receiveString);

    // When a message comes, it will call ReceiveCallback
    listener.BeginReceive(new AsyncCallback(ReceiveCallback), listener);
}

public void Listen()
{
    if (Thread.VolatileRead(ref done) == 1)
    {
        return;
    }

    int port = 8080;
    var serverEP = new IPEndPoint(IPAddress.Any, port);
    var listener = new UdpClient(serverEP);

    // When a message comes, it will call ReceiveCallback
    listener.BeginReceive(new AsyncCallback(ReceiveCallback), listener);
}

public void Stop()
{
    Volatile.Write(ref done, 1);
}

```

We should be able to incorporate the CancellationToken using `TaskFactory.FromAsync`, however I would prefer to use `ReceiveAsync` instead.
> 4 votes

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


# Question
Title: How can I fine-tune my movement values in a 2D block-based platformer?
I'm wondering how I can refine player movement/physics values, such as speed and jump height, to make it all work, while allowing the games to be fair and challenging. Is it simply trial and error, or is there a more standardized solution?

The levels in games like Super Mario or Geometry Dash are built on uniformly sized blocks, so the movement values need to work with these blocks. For example, if Mario can only jump 5 blocks high, the developers need to ensure that no obstacle is greater than 5 blocks tall (unless Mario has some special ability, but I'm not talking about that), or the player will be stuck.

Similarly, if the developers know that Mario can only jump 6.5 blocks horizontally, a blockless pit should be, at most, 6 blocks long. Knowing these relationships would allow one to create beatable levels, and even dynamically generate obstacles for the player to traverse.

I already have a character controller that can set my movement values easily, but I'm struggling to figure out a good way to make my movement and block sizes work together. Specifically, I'm concerned about making my game too easy or hard. How do I know when I've struck a proper balance?

# Answer
There is a lot you can do with a mathematical approach to game design, but in the end you won't get around systematic playtesting.

A good way to identify places in your game which are too hard are **automatically collected metrics**. Whenever the player dies, log when, where and exactly how they died. Put those events into a database, so you can analyze and visualize them. When you have the results of multiple playtesters, you can identify hotspots in your levels where players die a lot.

What's especially interesting are hotspots where the same players die repeatedly. What's even more interesting are hotspots where players die and then exit the game ("ragequits"). These might be parts of your game which are too difficult or even impossible to beat and cause frustration for the player.

See if you can make those sections easier by redesigning them or making sure players actually have the tools and knowledge required for beating that challenge at that point of the game.

Note that it should not be your goal to make the players not lose *at all*. If you try to disarm any difficult sections of your game, you might end up with a game which is so easy it's boring. Player death might even be a calculated part of your game experience, as long as proper anti-frustration features are in place. What you actually want to achieve is a game which is challenging, but has no sections which are so frustrating that they cause the player to quit or difficult spikes which require more skill from the player than what should be expected at that stage of the game.

---

And by the way: **First** nail down and polish the movement mechanics of your player-character in a couple test levels. **Then** start designing the *real* levels around those mechanics. If you keep tinkering with the movement while you already have levels in place, then you will break those levels and you will have to revise them over and over again.
> 3 votes

# Answer
### Jump height

The approach is: when Mario just has jumped, his kinetic energy is \\$ mv^2 \over 2 \\$ and potential energy is zero due to zero height, and in highest point of jump trajectory his potential energy is \\$ mgh \\$ and kinetic is zero due to zero speed. They are equal because of the law of energy conservation: \\$ v^2 = 2gh \\$ (I've already simplified this). Here is assumed that \\$ v\_x = 0 \\$.

So, if you have

* \\$ h = 3\mbox{ tiles} = 48 \mbox { px} \\$
* \\$ g = 0.5 \mbox{ px/tick}^2 \\$

Then \\$ v = \sqrt {2 \cdot 0.5 \cdot 48} \approx 7 \mbox { px/tick} \\$.

But a game engine may be not that accurate and jump speed will still require manual tuning, you may want to use 3.5 tiles instead of 3.

### Run speed

We calculate jump time based on height difference between start and finish, knowing jump velocity. Assuming that initial height is 0, we have this equation:

\\$ h = v\_yt - {g \over 2}t^2 \\$

You have to find *t*. Usually there will be two roots because Mario will reach height *h* twice. Choose the one which is greater - it corresponds to jump phase when he descends. If there are none, then *h* is too high for him.

When *t* is found, you can easily find horizontal velocity for required path *s*:

\\$ s = v\_xt \\$

\\$ v\_x = {s \over t} \\$
> 1 votes

# Answer
I think the OP is not looking for a solution to a kinematic problem, but rather he is looking for methods to properly balance the game. I don't think there is any method in particular, but once you decide the parameters of the jumps or speed, it's a matter of doing a lot testing.

If you want to make it more "scientific", you could involve a sample of people who will test your game, and give them a questionnaire. If the questions can be answered with numbers, you can then perform a statistical analysis of the data you collected. For example, for the question "grade the difficulty of level X between 1 and 10", you could compute the average of the answers, or better inspect the histogram (see https://en.m.wikipedia.org/wiki/Histogram ). This will allow to discriminate between "level X is easy/difficult for basically everyone" and "many people find it hard, but also many people find it easy" which will help you in deciding how to tweak your parameters.

See also my answer to this question grade How to compute the moves amount in a match-3 game?
> 1 votes

---
Tags: 2d, game-design, tiles, platformer
---


# Question
Title: How do I change the material of an object with Script in Unity?
I was making a game with Unity and I want to change an object's material using UnityScript when the player collects 5 collectables that I made. The collectables get stored in an int variable called Score.

# Answer
If you want to change a Material in Unity you have to retrieve it first.

If your GameObject uses a Material it means that it uses a Renderer.

You can retrieve your object renderer using the internal variable `renderer` or get it using the `GetComponent` function. On the renderer object you will find a material property containing the active `Material`.

For example:

```
MeshRenderer my_renderer = GetComponent<MeshRenderer>();
if ( my_renderer != null )
{
   Material my_material = my_renderer.material;
}

```

If you want to change the current material, you can use the same access. For example:

```
my_renderer.material = other_material;

```

I suggest to make `other_material` a `public Material` variable of your game object. However if you want to load it at runtime you should have a look at Resources.Load.

I hope it helps.
> 3 votes

# Answer
```
public Material[] mainMat;

Renderer rend;

public static int index;

public static int i;

public void Start()
{
    rend = GetComponent<Renderer> ();
    rend.enabled = true;
//  rend.sharedMaterial = mainMat [0];
}

public void changeMat()
{
    if (i == 0) {
        rend.sharedMaterial = mainMat [0];
        i++;
    }
    else if (i == 1)
    {
        rend.sharedMaterial = mainMat [1];
        i++;
    }

```
> 0 votes

---
Tags: unity, unityscript, materials
---


# Question
Title: Make a bullet move towards the mouse position
Before you give me a link to another post look first, just in case.

So I'm making a top down game where the person can shoot around, I want the bullets to move towards the mouse, I have tried this:

```
angle = (float) Math.atan2(pmx - x, pmy - y) * 180 / Math.PI;
x += this.getVelX() + (Math.cos(angle * Math.PI / 180) * 15);
y += this.getVelY() + (Math.sin(angle * Math.PI / 180) * 15);

```

The `pmx` means previous mouse position where I clicked, and the same for `pmy`. But this doesn't work properly look at this screenshot, the gun is pointed towards the mouse (the screenshot doesn't show the mouse) and the yellow squares are the bullets.

How it moves the bullets is the goes towards the mouse about 50 pixels then curls down to the left and inverted for the other side.

---

After looking at *Theraot*'s post *Section B*:

```
int speed = 15;
int velocityX = pmx - x;
int velocityY = pmy - y;
length = Math.sqrt(velocityX * velocityX + velocityY * velocityY);
velocityX *= speed / length;
velocityY *= speed / length;

x += velocityX;
y += velocityY;

```

This has worked to move it the direction of the mouse, but a new issue has occurred whether this is my issue or not I don't know, as I'm not that good at maths, what it does is moves in the correct direction and when it gets to the mouses old position where it was clicked it stop moving:

If there is a way to stop this from that method can someone tell me if not which Section should I use instead?

# Answer
First: you have your arguments to `atan2` backwards. If you check the docs, you'll see it takes `y` first, then `x`

But why go to all the work to take the angle, convert it from radians to degrees, convert it back to degrees, then convert it back to a vector? This is a pile of extra trig you don't need.

instead, when you spawn the bullet, calculate its velocity like so:

```
dx = mouseX - x;
dy = mouseY - y;

length = Math.sqrt(dx*dx + dy*dy);

dx /= length;
dy /= length;

this.setVelX(dx * speed);
this.setVelY(dy * speed);

```

Do not repeat the above on every tick unless you want a homing bullet that can change direction in flight.

Instead, each frame, all you need to do is continue moving the bullet along the straight line of its velocity, using the same stored velocity rather than re-calculating it:

```
x += this.getVelX() * deltaTime;
y += this.getVelY() * deltaTime;

```

I've changed your velocity integration here, assuming you want to move straight at the mouse at some fixed `speed`, and adding a `deltaTime` adjustment so your speed stays consistent regardless of framerate.
> 2 votes

# Answer
## Do you want bullets to be shot in the direction of the mouse?

**When the player clicks (Version A)**

1. Compute the angle from the avatar position

```
angle = Math.atan2(mouseY - avatarY, mouseX - avatarX);

```
2. Compute the velocity vector

```
speed = 15;
velocityX = speed * cos(angle);
velocityY = speed * sin(angle);

```
3. Create the bullet with that velocity

**When the player clicks (Version B)**

*DMGregory is right, we do not need trigonometry.*

1. Compute the velocity vector

```
speed = 15;
velocityX = mouseX - avatarX;
velocityY = mouseY - avatarY;
length = Math.sqrt(velocityX * velocityX + velocityY * velocityY);
velocityX *= speed / length;
velocityY *= speed / length;

```
2. Create the bullet with that velocity

**Addendum**:

The idea is to compute the velocity vector (`velocityX` and `velocityY`) **once** before you create the bullet (thet is, on click), then create the bullet, and store the velocity in the bullet.

---

**On update**

For each bullet, move it according to velocity:

```
x += this.getVelX() * delta;
y += this.getVelY() * delta;

```

Where `delta` is the time from the last frame.

---

## Do you want bullets to be chase the mouse?

On update, do it all

```
angle = Math.atan2(mouseY - y, mouseX - x); // x and y of the bullet
speed = 15;
velocityX = speed * cos(angle);
velocityY = speed * sin(angle);
x += velocityX * delta;
y += velocityY * delta;

```

```
speed = 15;
velocityX = mouseX - x; // x is of the bullet
velocityY = mouseY - y; // y is of the bullet
length = Math.sqrt(velocityX * velocityX + velocityY * velocityY);
velocityX *= speed / length;
velocityY *= speed / length;
x += velocityX * delta;
y += velocityY * delta;

```

**Note**: know that by changing velocity, technically the bullet has an acceleration. The code above ignores that fact.

---

## Do you want to rotate the weapon towards the mouse?

On update, set the orientation to this angle

```
angle = Math.atan2(mouseY - avatarY, mouseX - avatarX);

```

---

## Placing the bullets at the end of the gun

You might want to create the bullets at `(avatarX, avatarY)`, however, it could be better to create at `(avatarX + cos(angle) * r + offX, avatarY + sin(angle) * r + offY)` and adjust `r`, `offX` and `offY` to make the bullet come out of the point of the gun.
> 0 votes

---
Tags: java, mathematics, movement
---


# Question
Title: Material in particle system is not showing in dark area
I am working on a muzzle flash with particle system where when the user fires the gun the material in the particle system will appear. The problem is that is shows really well in light but when the user is in a dark area the material or the muzzle flash does not show well. Any ideas?

# Answer
> 0 votes
It seems like you are using "lit" particles which are shaded by light sources. When you have particles which fall into the "stuff that glows" category, you usually want to use "unlit" particles. "Unlit", in this context, means that they are always at full brightness and not affected by light sources.

If you are using the classic particle system, go to the "renderer" section and select a material with the shader "Particles/Standard Unlit" (like the "Default-ParticleSystem" material).

If you are already using the new Visual Effect Graph system, make sure you are **not** using an Output node with "Lit" in the name, like "Lit Quad Output" or "Lit Mesh Output". Use the regular "Quad Output" or "Mesh Output" instead.

---
Tags: unity, c#, lighting, particles, materials
---


# Question
Title: Unity UI - Value of text input (assigned with OnChange event) is always "one letter behind"
I am having a problem in unity setting up a search field. I will post pictures down reggarding my problem but first let me quickly explain what is going on.

I have input element in my ui and i have working search function ready to use. The problem is that the string i feed my search function with is assigned from the inputfield text element value, which appears to be always one step behind.

What i mean is when I type "Wooden door" inputfield value is "Wooden doo".

It is quite annoying and I have no idea what is going on. Please point me into right direction.

Let me post the pictures with quick descriptions.

My UI:

My problem (item I am looking for is named "Wooden door"):

Second image of my problem (door item should not be present):

Finaly my ui settings and code:

Assigning value here:

My search control script:

```
using UnityEngine;
using UnityEngine.UI;
public class SearchControl : MonoBehaviour
{
public InputField inputField;
public Text searchInput;

private void Start()
{
    inputField = GetComponent<InputField>();
    searchInput = inputField.textComponent;
}

public void Search()
{
    if (searchInput == null)
    {
        Debug.LogWarning("Can't find search field.");
        return;
    }
    //TODO: text value is always one letter behind.
    string searchVal = searchInput.text;
    Debug.Log("Searching value: " + searchVal);

    CraftingManager.instance.RenderSearchedRecipes(searchVal);
}
}

```

I think there is some kind of character "verification" going on there and the real value of that text field is really one letter behind (since i assign it befor it gets verified). But that is not acceptable and I have no idea what can i do to avoid it. Thank you for any help!

# Answer
Misleading variable names strike again.

`searchInput`, despite "input" in its name, isn't pointing to your input field that's receiving the new text. It's the display text object.

The display text field does not find out about the new string until *after* the change has been handled by your `onValueChanged` script, because your script might have changed the text that you want the user to see (say, deleting forbidden characters or adding formatting to a phone number)

You want to ask `inputField.text` for the user's latest input, instead of `searchInput.text`.

And I'd recommend renaming `searchInput` to something like `searchDisplayText` so you or another developer won't confuse it for an input source in future.

Also, note this was exactly the resolution to the existing Q&A thread I linked you to from two years ago, so don't underestimate your ability to find these answers for yourself by searching.
> 3 votes

# Answer
you do not need the extra searchInput you can remove that and switch out to get the text from inputField.text

```
private void Start()
{
inputField = GetComponent<InputField>();
searchInput = inputField.textComponent;//can remove this line
}
public void Search()
{
  if (searchInput == null)
  {
    Debug.LogWarning("Can't find search field.");
    return;
  }
//TODO: text value is always one letter behind.
string searchVal = inputField.text;//and change this to get value of inputField text instead of textComponent;
Debug.Log("Searching value: " + searchVal);

CraftingManager.instance.RenderSearchedRecipes(searchVal);
}

```
> 2 votes

# Answer
Another way to achieve this is to make use of dynamic parameters on UnityEvents.

Events that can provide parameters at runtime are marked with those parameters in the inspector (and detailed in the relevant doc pages). e.g. On Value Changed (String) in the inspector shows that this event can provide a string argument - in this case the provided argument is the new value.

An example of writing a handler which could process that:

```
public void Search(string searchString) {
    CraftingManager.instance.RenderSearchedRecipies(searchString);
}

```

This negates the need for referencing the input or display components directly, meaning less possibility for confusion. *Plus the bonus that it does not need to be part of the same GameObject, if that ever needs to change.*

You would assign this handler in the same way as any other - just make sure you select your function from the Dynamic section of the drop-down (otherwise Unity will expect you to provide a parameter in the inspector which will remain the same for each call).
> 1 votes

---
Tags: unity, gui, input, text
---


# Question
Title: What are these three different texture types I found in Pokémon sun?
I am currently trying to extract the Pokémon models/textures/animations of the Pokémon Sun game so i can use them as placeholders in Godot.

At the moment I have the model, the textures and the animations in separate files, and now i am trying to put them all together using blender.

Combining the smd model and animation into a dae file works perfectly. The problem that i have right now is that the texture mapping is completely wrong.

After a closer look at the textures it seems like there are two or three files for each texture. One is the texture itself, one is a grey scaled image and the third is a rainbow colored image.

I don't really know much about texture compositions so I was wondering how these files play together.

# Answer
While you should never use assets from someone else's game in your own game, there is a lot you can learn from reverse-engineering the games of other people and figuring out how they did things.

The first texture appears to be an albedo texture. This is a texture which tells you which parts of the object have which basic color. This texture is usually the most important one, and most 3d models should look at least recognizable with just this texture. So this is the one you should focus on first.

The last one (the one with the rainbow colors) seems to be a normal map (also known as "bump map"). A normal map tells you the direction in which each pixel faces. It is important for shading an object correctly. Note that it seems to use different UV coordinates than the other two textures (or it could be from an entirely different 3d model).

The second one (the black and white one) could fulfill various effect purposes.

* It could be an occlusion map. An occlusion map is used to add additional darkness to sections of the model. This is a relatively cheap way to add self-shadowing to parts of a 3d model which are virtually always in shade.
* It could be a height map, which makes some parts of a polygon render higher or lower without actually requiring any additional geometry.
* It could be a specular map. A specular map tells you which parts of the model are "shiny" and which are "dull". (considering that it matches the albedo texture very well, this seems to be the most likely)
> 2 votes

---
Tags: textures, graphics, blender, uv-mapping
---


title: Triangular Metric

text:
# Question
Title: Triangular Metric
Given a point inside a unit equilateral triangle, how does one rotate it across the triangle perimeter? I.e. the triangle outline serving the same purpose as circle's circumference. That is actually a question of practical importance - it is required for a seamless hue-shift inside spaces like CIE XYZ.

As I understand some distorted versions of sin and cos functions are required, so that they give points on a unit equilateral triangle, instead of a unit circle. But sin and cos themselves were inferred from the euclidean space metric X^2 + Y^2 = R^2. Obviously triangular sin and cos define non-euclidean space. But what is it's metric?

I've found an article speaking about this thing https://ncatlab.org/nlab/show/p-norm but I don't understand 95% of the terminology they use. They also refer to metric as "norm" for some reason. Guess "norm" is some specific subtype of metric. And they don't tell how to generate it from triangle either.

# Answer
> 1 votes
A simple linear interpolation should be enough here, since the sides are straight. For just one side, the equation is

$$p(t) = \vec a + (\vec b - \vec a)\cdot t$$

Where \\$t\\$ is a value between 0 and 1, \\$\vec a \\$ is one of the vertices of the side and \\$\vec b\\$ is the other. For \\$t = 0\\$ the returned position is \\$\vec a\\$, for \\$t = 1\\$ it's \\$\vec b\\$. Animation to make it clearer:

Now if you divide the \\$\[0,1\]\\$ interval into three equal parts, the first for the first side, second for the second part and the third for the third one, then you can create a function, that returns the positions of an equilateral triangle. If we have a triangle \\$ABC\\$ and the vectors pointing to the three vectors are \\$\vec a\\$, \\$\vec b\\$ and \\$\vec c\\$ respectively, then this function is

$$p(t) = \begin{cases} \vec a + (\vec b - \vec a) \cdot (t \cdot 3) &\quad\text{if } 0 \< t \< \frac{1}{3}\\ \vec b + (\vec c - \vec b) \cdot (t \cdot 3 - 1) &\quad\text{if } \frac{1}{3} \< t \< \frac{2}{3}\\ \vec c + (\vec a - \vec c) \cdot (t \cdot 3 - 2) &\quad\text{if } \frac{2}{3} \< t \< 1\\ \end{cases}$$

---
Tags: 2d, mathematics, color, trigonometry
---


# Question
Title: How can I improve performance when looping and comparing values on dictionaries?
On my quest to creating 0 garbage when procedurally generating points I've stumbled upon a performance issue when comparing values to another values stored inside Dictionaries.

Initially I used lists and arrays but I recently revisited the code in order to avoid any garbage generation. Also I decided to use Dictionaries instead of Arrays/Lists because it seems useful to access a certain Key in a Dictionary.

**I use Dictionaries in the following way:**

* Each key is a mesh in my game
* Each value is an array of vertices or triangles
* Every array contains hundreds of vertices or triangles

```
Dictionary<int, Vector3[]> exampleVerticesDictionary;
Dictionary<int, int[]> exampleTrianglesDictionary;

```

**My procedural system does the following:**

```
1. Takes an initial random value (int or float).
2. Loops through all the items in the arrays of the 1st Dictionary.
3. If the value matches any value on any of the arrays, continue on the next loop.*
4. Loops through all the items in the arrays of the 2nd Dictionary.
5. If the initial value matches again, continue on next loop.
6. Loops through all the items in the arrays of the 3rd Dictionary.
7. If the initial value matches again, create a 3D point.

```

**I access and compare items in Dictionaries in the following way:**

```
if (exampleVerticesDictionary[key][index] == 1)

```

---

**The problem:** It causes noticeable performance spikes. The profiler indicates it's caused by the numerous calls (*tens of thousands*) to these methods:

```
  Dictionary.get_Item()
      GenericEqualityComparer.Equals()
          Int32.Equals()
      GenericEqualityComparer.Equals()
          Int32.GetHashCode()

```

**The questions:**

* Why does the performance drop so much when using Dictionaries to make those comparisons?
* Am I just better off using Arrays of Arrays instead of Dictionaries of Arrays?
* Should I be using other way of accessing and comparing items in Dictionaries?

---

Thanks in advance! Coding is not my strong suit and I'm kinda lost with this issue...

# Answer
Dictionaries are great when you want random access to one element (that's identified by a non-integer key, or by integer keys that are sparsely distributed) without iterating over all/most of the elements in the collection.

Internally, they hash your key, and use that hash result to guide a probe/search of a (generally very small) portion of the collection. That means you're paying hashing and comparison costs for each individual lookup, but it's still cheaper per lookup than searching the whole collection with something like exhaustive iteration or binary search. In particular, in a well balanced dictionary application, the cost of the lookup doesn't grow with the size of the collection, unlike search methods.

But if you're planning to iterate over all values in the collection anyway, then this is just wasteful. You haven't cut down on the number of entries in the collection you're visiting - in fact you've increased your workload by visiting some entries multiple times in the event of collisions.

You could instead store your items in a list and iterate over all of them sequentially without any of those extra hashing and comparison steps for every probe in every lookup, and with no redundant probes.

So you're using the wrong structure for this particular application. It's fine to also keep a dictionary for fast random lookup, in addition to a list for fast exhaustive iteration, using the appropriate tool for whichever operation you need to perform at the time.

(Although I do note your keys are integers: if those keys are dense - say, you have an entry for most integers from 42 to 105 - then you might as well store the collection in a list anyway, which also gives you random access to numeric indices as long as they're in a contiguous range, and does so without the hashing/probing. You might just need to scale/shift the range into valid indices for the list.)

Something to keep in mind is that modern processors and their cache hierarchies absolutely *love* walking linearly through an array or list. They can reliably predict the next action, pre-fetch the data they need, and plow through at full speed without waiting on memory latency or rewinding mis-predicted branches. All of that can grind to a halt when they hit a dictionary lookup, which by its nature looks to the processor like a random leap, losing much of the acceleration of prediction & caching. So a naive iteration can often be faster if it lets the hardware do what it's good at and chew contiguous data in predictable patterns, and finding ways to make your access patterns more linear like this will frequently yield benefits.

---

That costly random leap can still be worthwhile if it saves you a long search though! So that suggests a different way you could use dictionaries productively here: instead of using many dictionary lookups to search through all your meshes, use *one* dictionary lookup *instead* of searching all your meshes.

Here you'd key our new dictionary on the value you're searching for. That way you can use it to pre-cache the answers to the question "does value X match any value in any of my meshes?", and return the result in one single lookup instead of iterating every mesh to find a match.

Each time you change your set of meshes, or change the contents of one of the meshes, you update this cache. This will be a speedup if your frequency of updates is less than your frequency of queries - accelerating the action you do often, and the cost of a little extra book-keeping for the action you do less often.
> 7 votes

# Answer
Have you guys thought about using multi-threaded LINQ for reading the dictionary faster? Something like

```
exampleDictionary.AsParallel()
.ForAll(kv =>
{
    // do something with kv.Key or kv.Value
    // if custom object, kv.YourProp
});

```

Hopefully this can be used! Good luck!
> 0 votes

---
Tags: unity, c#, performance, procedural-generation
---


title: How can I flip a coin?

text:
# Question
Title: How can I flip a coin?
I am working in unity and have flattened out a cylinder object to make a coin for a 3d coin flipping game, but I am not sure how to get the coin to flip when the player swipes across it and allow for a double flip if the player swipes over it a second time while in mid air.

here is what I have tried:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinFlip : MonoBehaviour {

    private Vector3 start;

    private void Start() {
        start = gameObject.transform.position;
    }

    void Update() {
        transform.position += transform.right * Mathf.Sin(Time.time * 0.45f) * -0.025f;
    }

    void OnEnable() {
        gameObject.transform.position = start;
    }
}

```

# Answer
If you want the coin to behave like a physical coin, then you might want to leave this to the physics engine.

Add a gravity-engabled Rigidbody to the coin and place the coin on top of a static Plane so it doesn't fall into oblivion.

Now, in order to catapult it into the air, write a script which calls `Rigidbody.AddForce` with an appropriate upward force when the user performs an action.

The effect should be that the coin is catapulted into the air but keeps its orientation. That's a start. But you wanted to *flip* the coin. That means it should rotate. The reason it doesn't rotate is because AddForce adds a force which acts exactly on the center of mass of the rigidbody. So it all goes into acceleration and nothing goes into rotation. In order to change that, you can use `Rigidbody.AddForceAtPosition` to apply the force with an offset to the center of mass. That should result in a rotation.

The next two problems you have to solve are:

* How do you prevent the player from launching the coin off-screen?
* How do you detect which side is up when the coin lands?

But these are material for new questions.
> 1 votes

---
Tags: unity
---


title: Pass data down to components

text:
# Question
Title: Pass data down to components
In the game I have, I'm using an architecture close to what I've seen of Unity components :

Basically, the universe implements the game loop, entities implement and `update` method, which always delegates to each entity's components.

Components are where the actual data and behaviors sit, quite like a `MonoBehavior` in Unity I guess.

And I use this architecture to model my whole game.

I use child classes of `Entity` as *prefabs*:

```
class Player extends Entity {
   constructor() {
      this.addComponent(new Transform())
      this.addComponent(new KeyboardControlledMovement(()
      this.addComponent(new PlayerCanvasRender())
      this.addComponent(new Gun())
   }
}

```

So, I get this kind of Universe - Entity - Component tree :

**Question time!**

Aside from the entities and the components, there exist Settings, such as ell the key bindings, the reference to the output canvas, the player buffs, ...

They all have to reach various components, and I don't know how to get them there.

---

So far, I've thought of several possible solutions:

* **Passing data in parameter of the entities' and components' constructor** would be a *KISS* way of cascading external values. It looks like — if it isn't actually — manual dependency injection. However, in order to — as an example — feed the `BulletCanvasRender` with a reference on the canvas it has to draw on, it has to be passed through the `Gun` component, which has nothing to do with rendering; I'm mainly afraid of code cluttering here.
* Until now, I've been **using the universe as a global crap-bag**. This is great since it eliminates the boilerplate associated with manual dependency injection, but it makes the universe initialization function quite large — plus, I have to come up with names for all those new settings properties...
* Another option would be to **switch to real ECS architecture** by completely separating the raw data, which would stay in the components, from the behavior, which would go into external *systems*, and make use of the external settings from only within the systems. I would still have to perform some kind of manual dependency injection, but it would be limited to a set of non-nested *systems*. I don't like this solution either since it would cause quite a big change in the code.
* **Using an DIC, or a service locator** to create all the components — or at least those that require injected data.

# Answer
> 2 votes
---

## Will you have networking?

I understand that you are probably making a single player game engine. However, thinking about how to deal with the network very, very, very early in the desgin will push you a better architecture... even if your game will not be networked anyway.

Think of a server-client architecture. If you were to build that, you would want to be able to send information about the enetities from the server to the client. To do this, it is convinient that components have value semantics. And for that, it is conveninient that they do not have behaviour and do not depend on external systems (eg. canvas).

The server would have systems that handle the behaviour, and the client would deal with IO (keybindings, rendering, etc...), but they need to work on the same data.

Thus, you implement a "real ECS architecture" plus client-server synchronization of components and you are good to go (well, netcode gets more complicated than that, but that is a great start).

---

## Passing data

To answer you question: All of the above.

1. "using the universe as a global crap-bag" sound like you should use a Blackboard pattern. Your knowledge sources would be the system that handle the configuration files for keybinding and other settings. You can also have knowledge sources for information generated in game, or even for user input. All the knowledge sources post into the blackboard. In the pattern the control is supposed to call the knowledge sources. The game loop will do that.
2. "Using an DIC, or a service locator", you can have it takes information from the blackboard.
3. "Passing data in (...) constructor"

You can start your by adding the constructors and passing data down the hierarchy.

You then change the creation of components to a call ot `Universe.Create` or something like that. Then universe looks at the blackboard, picks the data, passes it in the constructor... but there would still be things that needs to be passed from the parent object.

You can pass a resource locator as parameter in the constructor, so that components can take from it the data it wants, while the parant object can pass other data in other parameters of the contructor.

However, do not pass externals to components. Instead...
4. "switch to real ECS architecture". Did I say components above? Oh, no. That is how you create systems, not components. Your systems should create the entities and attach the components. Then your game loop calls the systems, the systems query the entities depending on the components, and they run some code.

Your knowledge sources are systems!

---

## Physics

*Let us pretend we do not want to use systems.*

Currently, you would have entities that has `Transform`, which I am guessing defines thier position. I suppose you would want to add colliders for physics. So, let us pretend you have those too...

Perhaps you want to add a physics component. Since you do not have systems. Perhaps the physics component has the colliders

Your physics simulation would update the transforms. No problem there. However, you also want to check for collisions. Hmm...

Somehow, you need the physics component to get a list of nearby objects to check collisions against. How?

Besides, that physics component would run per entity. If no information is shared among them, one entity A would find it collides with another entity B, and then entity B finds it collides with entity A. You find the collision twice.

Thus, you need to break encapsulation of the components. They need to know where each other is, and who collided with who. That is not a good design.

---

*Let us pretend we do want to use systems.*

The game loop calls the physics system. The physics system queries all the entities with physic components (remember that these physic components are only data). We want a spatial data structure, something where it is easy to get nearby objects.

Two ways to do this:

1. The Entity Component System allows you to subscribe to changes in components. So your physics system get a notification when a collider is attached, for example. Then the physics system can add the component to the data structure.
2. The physics system creates and handles all the data it needs, and the components are just references.

Then, the physics system can find candidate collision pairs, check for collisions, and do resolution,

---

## User input and scripted movement.

*Pretending there are no systems*

Let us say we want to be able to move some objects with user input, or we want them to move in a predefined path, or be handled by AI (path finding et.al.).

However, the physics component wants to handle movement too. That means that these components need to know of each other, and thus would be coupled.

To solve it, you a component for the position, and now the other components only need to know about that one.

Well, if you have components that just store the position, and other components that handle input or do physics simulations, or whatever with that component... you have components and systems, except you are not calling them that.

---

*Make it a system*

A system takes the bindings from configuration files, or whatever. There is an input system that needs them. You can choose if you want it to post to a blackboard or you want to pass them directly.

Either way, the input manager system takes external input. It will query for the entities with the control components. Yes, more than one. That way you can handle couch multiplayer.

Now you have a few options:

* You are making a game: implement the input manager to directly move the objects.
* You are making an engine:
    + Have the input manager update the control components. Then the game developer can choose to write an input system that takes the control components and moves the position components or whatver.
    + Just write an input manager and let the game developer call it from their systems and do whatever they want.

*I'm sure there are more ways to do this, these are just the ones that I have come up with.*

---

## Why entities as just an id

We can implement entities as dictionaries of components. And it works. In fact, somewhere in the ECS there is something equivalent to a dictionary of components per entity.

However, you want to do much more than store components in entities.

You want to query all the entities that have certain components. For example, you want a system that looks for entities that has a position and a model to render them, and another that looks for entities that has a position and a velocity to move them. *notice these overlap.*

Unless you are ok with each system iterating linearly over all the entities, then those queries means that you want to create some sort of indexes of entities. And you want to make sure that updating the dictionary of components updates the indexes. That means that the dictionay of components cannot be a plain old dictionary, it is a façade to update the internals of the ECS.

Alright, what else does the entity has? Nothing, really. The behaviour should be in the systems, and all the data in the components. If you really want to have multiple kinds of entities, you can add a `Tag` component. Thus, you do not want entity to be a base class (client code could extend it and use it improperly). *Also, composition over inheritance.*

Now, the entity needs to point to the indexes to be able to update them, and the indexes point to the entity to be able to return it. We want to decouple that. In order to do so, we move all the logic that handle the indexes and the stored components to another class (called "registry", "scope", something like that). So that the entity only has an id. Now, there is no need for the index to point to the entity, it just stores id.

The design of the "registry" (by any other name) is that of data tables. You can think of the id as the primary key, have a column for each component type and a row for each entity. There are, of course, other optimizations form that idea.

---
Tags: component-based, entity-component, dependency-injection
---


# Question
Title: Unity - Odd distortion on default material cube
Does anyone know what causes this strange effect that looks like ripples? This is simply the default material on a cube and should be perfectly smooth. (Clear example at top right of image)

Another example:

# Answer
> 1 votes
Looks pretty much like shadowing artifacts which are known as *shadow acne*. In your scene, select the light source in the Inspector. Try setting the **Bias** and **Normal Bias** properties for better results.

Depending on your scene you'll be able to find a sweet spot for those values. It really depends on many details like at which angle the light hits the surface or how big your meshes are, the camera distance etc.

There's no real 'golden rule', just figure out which values work best in your case.

Also, check out the official documentation. You'll find an in-depth explanation on shadows in general but also on this specific issue.

---
Tags: unity
---


# Question
Title: Why do my objects with colliders go through each other, and how do I fix it?
I am new to Unity and I am just experimenting with a player controller script (which I got off youtube) and another object which doesn't move. Both my player and the stand-alone object have colliders and rigidbodies but when I move the player it goes straight through the other object.

My player controller script is:

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

public class PlayController : MonoBehaviour
{
    public float speed;

    private Rigidbody2D rb;
    private Vector2 moveVelocity;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        moveVelocity = moveInput.normalized * speed;
    }

    private void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
    }
}

```

Nothing has been changed on the colliders (nothing ticked), and the rigidbody2D has been changed to kinematic.

# Answer
> 1 votes
In physics engines, "kinematic" means "I'll handle steering this object around collisions myself — so engine, don't do any collision resolution on my behalf"

It's often useful for things like moving platforms, which should absolutely never stray from their assigned path — even if it goes through a solid floor — or get jostled when something lands on them. We'll also use it for animated characters, where in the event of a collision we want to play a dedicated contact or reaction animation, and ensure the animated foot positions stay accurately planted on the ground, without physics bouncing and sliding our character around.

But if you want the engine to handle collisions for you, you should uncheck the kinematic box and treat the object as dynamic instead. That tells the physic engine it's allowed to bounce it around in the event of collisions.

One other thing: I notice you're calculating a velocity. Rather than integrate that velocity yourself and use `MovePosition` to teleport to the next location, you might as well just give the velocity to your `Rigidbody2D` so the physics engine can do the integration for you. It can also use that velocity information to get more accurate collision responses, since it knows how everything was moving before the impact.

I wouldn't do it in `Update` as trollingchar recommended though. This runs after our physics step, so this adds an unnecessary frame of input latency. Instead I'd do it like this:

```
void FixedUpdate() {
    var input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
    input = Vector2.ClampMagnitude(input, 1f);
    rb.velocity = input * speed;
}

```

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


# Question
Title: Do I need a rendering system in my engine?
I am planning to create a cRPG game engine that would allow to *easily* create games like Baldur's Gate. I already tried to do that once, but my knowledge was vastly insufficient at the time. I settled for C++, SFML and TGUI (a GUI library), as this is what I have most experience with. I've read this article on game engine architecture, and I have decided to follow that system's architecture (event/message driven), because I know how much of a *unworkable hairball* my previous attempt was.

I am mindmapping the concept and its architecture for the past few days now (something I didn't do at all previously); and I came up to the point of how I want to divide (or do I?) the gameplay and rendering. The rendering part is actually very simple, as SFML does bulk of the job. I concluded that I don't even know what I could place in the rendering system apart from drawing sprites. I also can't seem to find more resources about game engine systems, because every time I search for that I get system requirements for unity and unreal.

If I decide to go with the rendering system, what would be the best way to store and send sprites? I suppose that I need to make a sprite resource manager. If so, how is the best way to send them to the render system without coupling things too much? Or perhaps the sprite resource manager should reside in the render system itself?

EDIT: As of current, the planned architecture is divided into 6 systems (Input, Audio, Logging, GUI, Gameplay, Render). I will use Events for decoupling. The problem with this design is that i will have at least 3 direct connections between GUI, Gameplay and Render. Those are:

1. Between GUI and Render. The TGUI library introduces a TGUI Window class that inherits from SFML one, and can be used as one. In my case, it will be a part of the Render system. Hovewer, the GUI system will need to have a pointer to the Window to register GUI widgets.
2. Between Gameplay and Render. Where applicable, Actor class will have a AnimatedSprite, which i will implement on my own. It will be a part of the Gameplay system, and will have a pointer to the sprite in resource manager (in the Render system); it will just cut it depending on animation/frame. In some cases, when animations are not required, the Actor class will just have pointer to a normal sprite. To get those pointers a function in resource manager will be called from the Gameplay system.

The latter of two is the major problem; as the function could be called at any time. But, it would be a simple function like sf::Sprite * getResource(std::string name) so i think it wont present all those *big bad problems* of coupling.

# Answer
> 1 votes
---

## Sprites

> If I decide to go with the rendering system, what would be the best way to store and send sprites? I suppose that I need to make a sprite resource manager. If so, how is the best way to send them to the render system without coupling things too much? Or perhaps the sprite resource manager should reside in the render system itself?

I faced this problem recently. Look, there are three things:

* Bitmaps
* Textures
* Sprites/Tiles

First, you will have a resource manager, and it is concerned with loading bitmaps. You then need to get texture objects (which belong to the rendering system):

* Sometimes you want to copy bitmap to a texture directly. That is the common case.
* Then, sometimes, you want to create bitmaps in memory instead of loading them from the resource manager, and then copy those to textures. Although, you probably will not need to do that (it can be useful when you are rolling your own GUI).
* Occasionally you want to copy only parts of the bitmap to textures. That is the rare case, in fact, I do think you will be doing it at all.

Finally, a texture could have multiple sprites/tiles that you can render separately by using texture coordinates. That all happens inside the rendering system, completely hidden from the rest of the solution.

**Note**: You can decide to have a fixed size for all sprites set at the start of the rendering system. Having all the sprites be of that size will save passing the size of the sprites each time. On the other hand, it is not a bad idea to have a similar solution to display overlays of custom size. Although, I guess the GUI can do that.

---

Now, your game object will have to tell the rendering system what sprite from what texture they use when you create it or when it changes (for animation). Yet, they are not responsible for loading those sprites/tiles. The convention is that there is an error texture (usually a magenta and black checkers pattern) used when the requested texture is not available.

Usually you want to have only a handful of textures loaded and you want to load them when initializing the scene/map/scenario/room. Bitmaps are there to facilitate that. If you need to build an atlas at run time, you can do that with bitmaps. Hopefully you do not need that and you can just load a few bitmaps from the resource manager that has all the sprites/tiles you need.

---

## GUI

> Between GUI and Render. The TGUI library introduces a TGUI Window class that inherits from SFML one, and can be used as one. In my case, it will be a part of the rendering system. Hovewer, the GUI system will need to have a pointer to the Window to register GUI widgets.

The initialization of the window is neither.

Just because the rendering system does a lot of SFML calls does not mean that every SFML call belongs in the rendering system.

Instead, handling the window is its own thing. Mold the event loop into the game loop, and it will call both the rending and the GUI system, and also all other systems.

---

## Animation

> Between Gameplay and Render. Where applicable, Actor class will have a AnimatedSprite, which i will implement on my own. It will be a part of the Gameplay system, and will have a pointer to the sprite in resource manager (in the rendering system); it will just cut it depending on animation/frame. In some cases, when animations are not required, the Actor class will just have pointer to a normal sprite. To get those pointers a function in resource manager will be called from the Gameplay system.

As I was saying the game object needs to tell the rendering system about its sprite. However, I would avoid pointers across systems. Instead of a pointer, use an id that serves as index in a table.

You will have multiple sprites in the same texture, and you can change which one is the current sprite of a game object. That is one way to do animation. There is no cutting for that, the rendering system will be rendering a different part of the texture, that is all.

No resource manager is involved either. You load the textures before hand. Remember that multiple game objects could use the same textures. You do not want each game object loading the same texture, that is wasted effort.

Also, I was saying sprites/tiles, because it is very similar to a way to do the terrain of the map. In fact, that can be animated too (water animation, for example). However, the map will give an array of sprite ids to render instead of the single sprite id from the game object. Perhaps not what you want... you can always have a custom painted map.

---

Which brings me to: the camera. Yes, camera. It will be exposed by the rendering system for control, however figuring what is in view is responsability of the rendering system. You might want to send to the GPU only things that are nearby the camera.

In fact, having a way to query things that are nearby a position is a good idea for physics. Will you have physics? I guess for collisions with terrain obstacles. Oh, another use is for AI. You might want enemies to react when the player is nearby.

Now, the camera is not exactly a game object, and it is not exactly a system. However, having some sort of system or module dedicated to handle the camera is a good idea. You may want to move it in predefined paths for cinematics, also there are planty of ways to handle the camera in a 2D game, and none of that logic belongs in any particular visible object nor in the rendering system. It would be a camera manager or something like that (camera operator? cinematographer?).

---

I am assuming you will be writing shaders, and loading textures to the GPU. That is why rendering parts of a texture is completely hidden from the rest of the system (it is shader logic). Again, no cuttig required.

I said above that changing which one is the current sprite is a way to the animation. I am implying that there is another way. You can have the game object tell the rendering system about all the sprites of the current animation, and the rendering system can loop them. In fact, the shader code can loop them. Just remember to pass the time as a uniform and in the shader compute which one is the current sprite for the time. *That way, animating a screen full of water tiles does not require to pass a bunch of sprite ids each frame.*

---
Tags: c++, 2d, architecture, sfml, resource-management
---


# Question
Title: How to handle dynamic hierarchical entities in ECS
Here's the analogy: I have an organism which is composed of cells which can be further composed of a medley of attachments.

What I have currently is a sort of event chain between child/parents to handle attaching and detaching components (which could affect anything along the chain) which doesn't involve ecs at all, they are functions in the entities.

Now I've used event components already (for mouse events on objects). If I wanted the system to be pure, would I create an attach component when I attach components etc? Even then how would I get all the necessary recipients to the system that consumes the component? Is it even worth it to handle it this way instead of a chain of functions? Is there a better way?

# Answer
> 0 votes
First of all, you dont have to go ECS all the way if you have something that works just as well. AAs you desribe it, your method works. As you have not given any examples on how it really works, i cant say what Problems your way might have: to strong dependencies or slow code or whatever.

If you want to do it the ECS way, i would suggest to have an own attached component, maybe with corresponding attachable component. The attached component could hold the information for the the attachment. Something like current depth of the entity or id of the attachment and the id of the attachment it is attached to.

Now every component that has an attachment or is attached gets this component. The root cell would have depth 0 with id 0. Everything attached to that would get depth 1, everything gets its own id and the connect-to-id would be 0 in this case.

This way, you have basically a tree with an indefinit amount of branches per leaf. This would be easily exandable or made more simple if your restrictions allow that (only one depth, ...)

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


# Question
Title: What is the purpose of the Allocation Callstacks button in Unity's Profile window?
I have an idea of what this button does, but I cannot find any specific information in the documentation.

What information does this button add to the profiling data? How can I see this extra information?

# Answer
Consulting the Unity documentation on the CPU Profiling tools:

> The recorded memory allocation samples appear in the Profiler window in bright red.
>
> ...If the callstack was recorded for the selected allocation sample, the associated callstack symbols are resolved and displayed as well:

So: when you have "Allocation Callstacks" enabled, you can click on the red boxes representing managed memory allocations to see what code caused memory to be allocated, and where it was called from.
> 1 votes

# Answer
These call stacks are also visible in Hierarchy view, albeit admittedly a bit more hidden. The Nice thing here is that they can be selected and copied out:

1. Find the drop-down that reads "no Details" by default and switch to "Show Related Objects"
2. Select one of the "N/A" Objects (yes, awkward name\*)
3. Find the call stack in the pane underneath that opens once you select an object

(\* The name usually would be something like "MainCamera" for e.g. a render sample and clicking one of these while profiling in the Editor highlights the corresponding object in the Hierarchy view, if it is still around.)
> 1 votes

---
Tags: unity, profiling
---


# Question
Title: How can I provide a csv file to a player on mobile?
It seems many people do this with regards to game data so they recommend userprefs, but I just want the user to have the file in the end, whether this is the Files app on iOS or choosing a folder to save in on Android or even just attaching the file as an attachment to an email that they can send using their preferred mail app or something.

# Answer
I used native share since Unity doesn't really provide this feature.

Saving the csv was also very straightforward:

```
public string save()
{
    string fileName = Application.persistentDataPath + "/saveDefault.csv";
    using (StreamWriter w = new StreamWriter(fileName, false))
    {
        foreach (TrafficRecord tr in data)
        {
            string line = string.Format(
                "{0},{1},{2}",
                tr.entryTime.ToString("MM/dd/yyyy hh:mm:ss tt"),
                tr.vehicleType.ToString(),
                tr.direction.ToString()
            );
            w.WriteLine(line);
            w.Flush();
        }
    }
    Debug.Log("Savefile saved to: " + fileName);
    return fileName;
}

```
> 1 votes

---
Tags: unity, android, ios
---


# Question
Title: Same scroll speed across devices with different DPI
I am creating a simple game in JS, something like the flappy bird :) For pipe scroll, I am using a linear tween.

I noticed that the speed of the pipes are different across different smartphone screens, so the game has different difficulty.

I observed that this has to do with different screen sizes and different pixels densities.

What I did is I defined a duration per pixel, which is multiplied by the number of pixels the screen has. The duration per pixel, `pixel_duration` is constant.

So basically:

```
tween_duration = number_of_horizontal_pixels * pixel_duration

```

But this gives same speed in different sized browser windows on the (same) computer screen. If I use this approach on some device that has higher pixel density, the pipes will move slower, because there are more pixels, so this `tween_duration` value gets larger, so tween gets slower.

Then I learned of the `devicePixel` ratio value which can be used. So I try to factor this in the equation:

```
tween_duration = number_of_horizontal_pixels * pixel_duration / devicePixelRatio

```

This `devicePixelRatio` is higher as screen DPI's goes higher and should solve my problem according to the docs, right? https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio

However, this only helps a bit. There is still a noticable speed difference.

Why is this not working, and how can I get the same scroll speed across devices in JS (in browser window) - perhaps some other approach would do?

# Answer
> 1 votes
Are you sure you need to go as deep as to device pixel ratio?

If it's a browser-based game, then you

1. have access to the viewport-percentage units like `vmin`, `vmax`, `vw`, `vh`. Why not use them?
2. If you are using canvas to render output, why not stylize it to fit entire viewport while maintaining the same pixel dimension?
3. Why not use `meta` tag to adjust the size of your page in logical pixels for mobile devices?

---
Tags: javascript, mobile, browser-based-games, side-scroller
---


# Question
Title: How can I get the player coordinates in Minecraft
I am currently working on a client for Minecraft Java edition and I'm having an issue finding out how I can get my Minecraft character's current coordinates, client side coordinates.

I would just like to know where I can find the file that contains the coordinates, or a way to get the coordinates, without using forge, or anything like that. Just vanilla Minecraft. The Minecraft version I am working with is 1.8.9, but I would like this to work for any version of the game.

# Answer
> -1 votes
The only thing that I found to work was to use the debug menu. When you hit f3 it opens the debug menu. From there I was able to take a screen shot of the coordinates, and use the Tesseract API to translate the image into text, and then log it to a file.

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


# Question
Title: How can I create a custom List-of-GameObject inspector which works like the default one in Unity?
I need to

1. drag and drop GameObject to ObjectField.
2. drag and drop a group of GameObjects to list name.

The main problem is either do 1 or 2 work. I need the function same as unity List Inspector for future devolvement. Code as follow.

```
static SerializedProperty ThisList;
public override void OnInspectorGUI()
{
    ThisList = serializedObject.FindProperty("G");//List name call G
    serializedObject.Update();
    Show(ThisList);
    serializedObject.ApplyModifiedProperties();
}

public static void Show(SerializedProperty list)
{
    EditorGUILayout.PropertyField(list);
    EditorGUI.indentLevel += 1;
    if (list.isExpanded)
    {         EditorGUILayout.PropertyField(list.FindPropertyRelative("Array.size"));
        ShowElements(list);
    }
    EditorGUI.indentLevel -= 1;
}

private static GameObject[] a =new GameObject[50000];
private static void ShowElements(SerializedProperty list)
{
    //This code can drag and drop GameObject to ObjectField.
    for (int i = 0; i < list.arraySize; i++)
    {
        list.GetArrayElementAtIndex(i).objectReferenceValue = EditorGUILayout.ObjectField("OBj", list.GetArrayElementAtIndex(i).objectReferenceValue, typeof(GameObject));
    }

    //This code can drag and drop a group of GameObjects to list name.
    if (Event.current.type == EventType.DragUpdated)
    {
        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
        Event.current.Use();
    }
    else if (Event.current.type == EventType.DragPerform)
    {
        for (int j = 0; j < DragAndDrop.objectReferences.Length; j++)
        {
            a[j] = (DragAndDrop.objectReferences[j] as GameObject);
        }
        Event.current.Use();
    }
}

```

However, it not work when both codes together.

If -\> EditorGUILayout.PropertyField(list, true); I can get the same result as the unity function. but I cant Custom the List. (such as add name, change position, add button...)

# Answer
One solution is to use a object field and cast to a gameobject to drag and drop

```
GameObject G;//gameobject

G = (GameObject)EditorGUILayout.ObjectField("Drag GameObject here :", G, typeof(GameObject), true);

```

for the list you can create a normal list

`editableElements = new List<GameObject>();
 SerializedObject classOBJ;
 SerializedProperty groupofProps;`

then add somewhere along the way

`editableElements.Add(go);`

you can edit the list however you normally do

then re-draw to window

```
 classOBJ = new SerializedObject(this);
 groupofProps = classOBJ.FindProperty("editableElements");
 var size = groupofProps.arraySize;
 for (int index = 0; index < size; index++)
 {
      var property = groupofProps.GetArrayElementAtIndex(index);
      EditorGUILayout.PropertyField(property);
 }

```
> 1 votes

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


# Question
Title: Where is the “Test Login Needed” in App review in Google Play?
I recently uploaded a new app in the google play console to review, then I was receive an email that say:

> Please provide login credentials to the support team before you submit any updated version for another review (select “Test Login Needed” and include the test login account and password details in the open box field).

I can´t find the “Test Login Needed” to select it.

Can anybody tell where is this option?

# Answer
* Sign in to your Play Console.
* At the bottom of the navigation bar, find the section "Policy" and click on "App Content".
* Start the "Target audience and content" questionnaire, or select "Start Again" if you already submitted.
* In step 2 "App Details" choose "All or some functionality is restricted" under "Instructions for app access".
* Enter the test login credentials there for app review team to access.
> 2 votes

---
Tags: google-play
---


# Question
Title: How to implment the database for event conditions and item bonuses for a browser based game?
I am currently creating a browser based game, and was wondering what was the standard approach in making diverse conditions and status bonuses database wise. Currently considering two cases.

* Event Conditions
    1. Needs min 1000 gold
    2. Needs min Lv 10
    3. Needs certain item.
    4. Needs fulfillment of another event
* Status Bonus
    1. Reduces damage by 20%
    2. +100 attack points
    3. Deflects certain type of attack

I wish to be able to continually change these parameters during the process of production and operation, so having them hard-coded isn't the best way.

All I could come up with are the following two methods:

1. Create a table that contains each conditions with needed attributes

Have a model named conditions with all the attributes it would need to set them:

```
conditions
  condition_type (level, money_min, money_max item, event_aquired)
  condition_amount
  prerequisite_condition_id
  prerequisite_item_id

```
2. Write it in a DSL form that could be interpreted later in the code

Perhaps something like yaml, have a text area in the setting form and have the code interpret it.

```
condition_foo:
  condition_type :level
    min_level: 10
  condition_type :item
    item_id: 2

```

Method 2 looks to be more practical and flexible for future changes, trade off being that all the flex must be done on the code side.

Not to sure how this is supposed to be done, is it supposed to be hard coded? separate config file? Any help would be appreciated.

This will be implemented with Ruby on Rails.

# Answer
You won't be able to store the conditions (logic-wise) in the database (unless you decide to store scripting code directly in the database). Instead you could establish a construction where each condition and bonus is associated with a unique key. You can then in turn store these keys in the database.

For example to describe the event conditions required to unlock status bonus 1 you would have tables resembling the following:

```
   [StatusBonusTable]
 StatusID StatusBonusKey ParameterN
   1     "reduceDamage"      20

[Event Conditions Table]
 StatusBonusId EventConditionKey ParameterN
     1           "goldRequired"      1000
     1           "levelRequired"      10

```

I would then suggest using a factory to load this data from the database and creating instances of the event condition classes passing that parameters stored in the database and likewise with the status bonuses:

```
if (eventConditionKey == "goldRequired")
 goldRequired = parameter[0]
 return new GoldRequiredCondition(goldRequired);

```

The advantages of using this approach is that it will not require changes to the database when you need new conditions and status bonuses. When you want a new condition or bonus the only place you will need to make changes is in your code. The disadvantage is the lack of automatic verification of the data you insert into the database. You will be able to insert keys that have no match in code, and set it's parameters to values that make no sense.
> 1 votes

# Answer
I think this is one case that would benefit from a document-database solution (i.e a "NoSql" database).

If you're set on using a SQL database then @Qua's answer is probably best.

The 2nd method you mentioned would fit perfectly with the document model. I'm currently looking at implementing something similar with MongoDb, which from what I've seen essentially stores and allows easy querying of JSON objects. See this answer for some more info.

Also keep in mind, that you can have more than one type of database. I'm using SQL for stuff that fits nicely into a relational model and Mongo for stuff that doesn't.
> 1 votes

# Answer
Method 2 is not bad, it is versatile, but hard to manage the logic and more importantly, not platform independent unless you use something like XML or JSON. The data still stays application dependent - that might be a problem when you want to create another (non-web based) interface for your game.

Method 1 would work for an SQL database, but if you want to keep it fast when your app is under a heavy load, you might want to think again about having to join tables or do 3 consecutive queries for a single item.

If you knew that you were not going to have more than 64 statuses and 64 conditions and not have any single item have more than x number of statuses and y number of conditions, then you could solve this with the bitwise comparison of two 64 bit integers and x + y numeric fields in the same record where values would be given in the order appearance as a set bit.

It might not be the most beautiful solution and somewhat limited, but it's very fast if you expect the db to be hit hard. I used to operate a web based browser game with a 50k+ user base, and it taught me the usefulness of this approach.
> 1 votes

# Answer
I'd prefer Method 2. It's flexible and can be implemented fairly easy.

The idea is to split the complex condition into a tree of simple ones. Each node of the tree is a comparison function and the leaves are either references to the user data or threshold values.

So your "Need min 100 gold" are going to look like

```
  greater
  +-gold
  +-999

```

or in JSON

```
"greater":{"attribute":"gold", "value":999}

```

but, using keys as function references have it's downsides: for example, you can't make an array of conditions. Therefore it would be better to make a condition object, like this:

```
{
  "type": "greater",
  "arguments": {
    "attr":"gold"
    "value":999
  }
}

```

using structures like this, you can build complex conditions just by introducing functions "every" and "some", which will return true when every or some conditions are true accordingly (and that is where we need an array of conditions).

So your initial condition may be rewritten as

```
const enough_gold = {
  "type": "greater",
  "args": {"attr": "gold","value": 999}
}
const lvl_ten_plus = {
  "type": "greater",
  "args": {"attr": "level","value": 9}
}
const have_item = {
  "type": "have",
  "args": {"attr": "item","value": "item_name"}
}
const compl_event = {
  "type": "have",
  "args": {"attr": "event","value": "event_name"}
}

const new_event = {
  "type": "all",
  "args": [
    enough_gold,
    lvl_ten_plus,
    have_item,
    compl_event
  ]
}

```

the data for testing this condition may look like

```
{
  "gold": 8350,
  "level": 11,
  "item": ["item1", "item3"],
  "event": ["some_event", "another_event"]
}

```

I switched to js to make it more readable and to show how you can nest conditions. I also introduced "have" function - this will iterate an array-attribute and return true if it includes provided value.

You can store those condition sets in file or database. In the latter case, it would be better to store each condition as a separate record and reference from complex ones to the simple ones. This will allow you to reuse some conditions and make balancing and patching easier.

I have no experience with MongoDB, but from what I read it will be perfect for this job.

Oh, and once you've extracted condition tree, you will know exactly which player attributes you'll need for the test, so you won't have to extract everything. Just in case.

Not that long ago I wrote a small condition-solver lib just for fun and maybe cases like this. It allows for creating nested conditions and testing them against some data set. Solver class is about 50 lines long (indents, comments and debug method included) and pretty simple, so I guess, there would be no problems porting it to ruby or PHP or any other language as long as there are hash tables and function pointers. The idea is simple as well: it will recursively call specified function for the specified arguments. And it's realy simple to use, here's an example

```
// Creating a solver with some initial data
const sol = new Solver({
  money: 30,
  fame: 25
})

// Creating some conditions
// have more than 50 money
const rich = cnd(
  'gt',
  arg(
    'money',
    50
  )
)

// have more than 15 fame
const good = cnd(
  'gt',
  arg(
    'fame',
    15
  )
)

// have at least something
const well = cnd(
  'any',
  [
    rich,
    good
  ]
)

// let's try it
sol.is(rich) // false: "money" is not > 50 (30)
sol.is(good) // true: "fame" is > 15 (25)
sol.is(well) // true: he's not rich, but he's good at least

```

Here's the source code link if it's relevant.

As for status bonuses, try looking at this answer it shows how you can implement them with MongoDB (and likes), and this one uses more traditional RMDBS approach.
> 1 votes

---
Tags: design-patterns, databases, browser-based-games
---


title: Tools for creating an item database

text:
# Question
Title: Tools for creating an item database
I'm working on a project for which I will need to create a large item database, with plenty of different types of items which will all have different data structures and attributes. I'm hoping to either find or implement a tool which will help my collaborators and I create item data collaboratively, something like a database frontend, basically. I've considered setting up an instance of a rails backend like railsAdmin and creating models for each type of item we'll need (e.g. weapon, vehicle, etc) and allowing team members to simply create new database records and populate data fields, then pull the data out of the DB and convert it to whatever format we need down the road.

My question is whether anyone has any experience with another tool, preferably something web-based, which would allow users to edit records in a database while easily adding or removing fields for specific tables? How did you and your team catalog all the items for your last project?

Thanks in advance and apologies for my poorly worded query.

# Answer
Do you have some kind-of development tool (eg. for making maps)? If so, (and this is how I do it) build an item editor into that. That way, all of your development tools are in one single spot. So, a user editing a map through your map editor, doesn't have to go to the website to set up items they want to use on that map (or the creatures on the map, or whatever). They can just pull down a menu, open the item editor, add the item and go right back to their map.

This works even better for me since my game is multiplayer so I can control access to the different editors based on user logins (to the development tool).
> 2 votes

# Answer
> tool, preferably something web-based, which would allow users to edit records in a database while easily adding or removing fields for specific tables

Google Spreadsheets

* you can create tables
* share them with other users
* leave comments or propositions on individual cells
* have a chat
* reference to other tables
* run data analytics
* add or remove fields
* And then you just download CSV-file, parse it and feed it to your database. Neat.
> 1 votes

---
Tags: tools, databases
---


# Question
Title: How to make a ball move with constant velocity after a collision?
In my scene there is a player and a ball a few units above the ground. The ball has a rigidbody2D attached with zero gravity.

I built a "cage" with square sprites to simulate the edges.

I would like that after the player has hit the ball, the ball moves with a constant speed (no matter how strong the collision with the player is).

I want to recreate something like this after the collision:
https://www.youtube.com/watch?v=zsdPYFPTdw0

I wrote this code:

```
{
    private Rigidbody2D rb;
    private Vector2 lastVelocity;

    private ConstantForce2D cf;

    private Vector2 direction;
    private Vector2 surfaceNormal;
    [HideInInspector]
    public float speed = 5;

    [HideInInspector]
    public float setTime = 5;

    [HideInInspector]
    public float smooth = 6;
    private bool timeEnded = false;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        cf = GetComponent<ConstantForce2D>();
    }

    private void Update()
    {
        Debug.Log(rb.velocity.magnitude);

        if (timeEnded)
            rb.velocity = Vector2.Lerp(rb.velocity, Vector2.zero, smooth * Time.deltaTime);
    }

    private void FixedUpdate()
    {
        lastVelocity = rb.velocity;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        // QUANDO VIENE COLPITO
        if (collision.collider.tag == "Player")
        {
            surfaceNormal = collision.contacts[0].normal;
            direction = surfaceNormal.normalized;

            //cf.force = direction * speed;
            rb.AddForce(cf.force = direction * speed * Time.fixedDeltaTime);

            StartCoroutine(StopBall());
        }

        // QUANDO COLPISCE IL MURO
        if (collision.collider.tag == "Wall")
        {
            Vector2 surfaceNormal = collision.contacts[0].normal;
            rb.velocity = Vector2.Reflect(lastVelocity, surfaceNormal);
        }
    }

    IEnumerator StopBall()
    {
        yield return new WaitForSeconds(setTime);

        timeEnded = true;
    }
}

```

I still don't understand why the speed doesn't remain constant, why sometimes it's zero and why it depends on the force with which I hit it.

# Answer
If the floor is smooth i.e. there is no drag from the surface, just use AddForce setting the ForceMode to Impulse, something like this:

```
    void FixedUpdate()
{
    rb.AddForce(dirX, dirY, dirZ, ForceMode.Impulse);
}

```

It is important that you use `Impulse` as force mode, since otherwise the force is continuously applied on your rigidbody, therefore constantly increasing the acceleration; impulse will apply it once and then, if there is no drag, the rigidbody will keep moving with the same velocity. To stop after a set time, well there are multiple ways. One could be that as soon as you hit the ball you start a **Coroutine** that will set the rigidbody velocity to zero, for instance:

private IEnumerator StopBall() { yield return new WaitForSeconds(setTime); rb.velocity = Vector3.zero; }

and you call this in your script by using `StartCoroutine(StopBall()); from your update method`. Hope it helps!
> 1 votes

---
Tags: unity, c#, 2d, physics, collision-resolution
---


# Question
Title: Command Shell text adventure - input methods for scrolling through text (lua)
I'm writing a simple text-based adventure in lua. The intent is the user clicks on the game.exe and it loads up the command prompt or whatever command shell they have and they play the game there.

A problem I'm having is I often want to display a small amount of text at a time so the ui isn't overflowing with chunks of words. So I'm requiring the user to input something, preferably enter, to scroll through to the next bit of text.

i.e.

```
print("I want you to go to the park for a bit to start out.")
io.read()
print("After a few minutes I'll contact you, can you do that? (yes/no)")
confirm=io.read()

```

I've been using a blank io.read() which will ask for user input and allow them to type characters and require them to hit enter, but not save what they wrote if anything. The intent is for the user not to write anything though and just hit enter, and only to write when they are given choices in brackets as seen in the second half. I feel like this is confusing and unintuitive, I was wondering if there was a simple better method. I see there are better languages for writing text based adventures, but I want to just stick to lua atm. If there is advice from another language, I can try and translate it over although you'd probably have a better idea of how. Examples are appreciated if there is a lua solution. Ideally I'd want to prevent input outside of pressing enter to scroll through text, or a timer so the next bit of text displays with some delay if that's possible for a simple windows shell like command prompt.

# Answer
This is not a super complete answer, but here goes:

When you expect your player to hit any key to continue, the classic way to tell them is end the prompt with *"Hit any key to continue"*.

Now to get only one character, it seems Lua allows to specify the amount of characters to read with read funcion, so just read one character:

```
print("I want you to go to the park for a bit to start out. (Hit any key to continue.)")
io.read(1)
print("After a few minutes I'll contact you, can you do that? (yes/no)")
confirm=io.read()

```

---

I'm not familiar with Lua and this is untested code. This post helped.
> 1 votes

---
Tags: lua, text-based
---