# Question
Title: How to create characters randomly with a given skill and weighted abilites
I am trying to create random characters in my game. Each character has 33 abilities and one of 6 jobs. For each job you need to skill/increase other abilities. I am calculating an overall skill (from 1 to 99) by using only the important abilities for this job. For example one of the jobs is a healer. Here you need to skill ability1 to ability6, which have also different weights.

Example:

```
 - Healer
 - Ability1 has weight 10 (skill 70)
 - Ability2 has weight 5 (skill 60)
 - Ability3 has weight 4 (skill 50)
 - Ability4 has weight 10 (skill 80)
 - Ability5 has weight 5 (skill 40)
 - Ability6 has weight 8 (skill 50)

 Example calculation:
(70 * 10) + (60 * 5) + (50 * 4) + (80 * 10) + (40 * 5) + (50 * 8) = 2600 /  (10 + 5 +  4+10+ 5+ 8) = 62

```

Problem:

I want to create random characters with random skills WITH a specific overall skill in HIS job. Example: CreateHealer(skill: 70). It doesn’t matter which values all the other abilities have. For example if ability7 is 1 or 99 the overall skill of the healer is always 70, but I want them to be random because the user has the opportunity to change the job, if he can see that this char would be a better warrior.

My idea:

Create all 33 abilities randomly and calculate the overall skill in this job.

* If skill is on the right level —\> stop.
* If skill is too low increase one of the weighted abilities and calculate again.
* If skill is too high decrease one of the weighted abilities and calculate again.

**Is there a better way/algorithm to do this?**

# Answer
Let's start simple and forget the constraint that skill values should be integers for a moment.

If we look at the equation for your job skill:

$$\begin{align} \frac{w\_1 s\_1 + w\_2 s\_2 + w\_3 s\_3 + w\_4 s\_4 + w\_5 s\_5 + w\_6 s\_6} {w\_1 + w\_2 + w\_3 + w\_4 + w\_5 + w\_6} &= j\\ w\_1 s\_1 + w\_2 s\_2 + w\_3 s\_3 + w\_4 s\_4 + w\_5 s\_5 + w\_6 s\_6 &= j \left( w\_1 + w\_2 + w\_3 + w\_4 + w\_5 + w\_6 \right) \end{align}$$

We can think of this as the equation of a 5-dimensional hyperplane in 6-dimensional skill space. Here the plane has a normal vector \\$\vec n = \left(w\_1,w\_2,w\_3,w\_4,w\_5,w\_6 \right)\\$, so we're looking for points in skill space \\$\vec s = \left(s\_1, s\_2, s\_3, s\_4, s\_5, s\_6 \right)\\$ such that...

$$\vec s \cdot \vec n = \left(j,j,j,j,j,j \right) \cdot \vec n$$

From this we can see one obvious solution \\$\vec s = \left(j,j,j,j,j,j \right)\\$ \- ie. if you want a job skill of 70, set all the component skills to 70, then any weighted average of them will still give the desired output of 70.

But since it's a plane, once we have one solution, we can slide that solution along the plane to get other solutions. Since we're in 6-dimensional space, and we've locked down one degree of freedom by fixing the value of our weighted average, we still have 5 different directions we can slide the solution while staying on the plane.

We can use the Gram-Schmidt process to take our normal vector and augment it with a set of mutually-perpendicular tangent vectors in the plane, to form a new basis for our skill space:

```
Vector6[] basisVector = new Vector6[6];

basisVector[0] = Normalize(
    new Vector6(weight[0], weight[1], weight[2], weight[3], weight[4], weight[5])
);

for (int i = 1; i < 6; i++) {
    basisVector[i] = Vector6.Zero;
    basisVectot[i][i] = 1f;

    for(int j = 0; j < i; i++)
       basisVector[i] -= Dot(basisVector[i], basisVector[j]) * basisVector[j];

    basisVector[i] = Normalize(basisVector[i]);
}

```

At the end of this process, `basisVector[0]` is your unit normal direction, and `basisVector[1]` to `[5]` are unit tangent directions along the solution plane in skill space.

With these in hand, you can pick a range of variation and then generate skill combinations with your desired sum like so:

```
Vector6 skills = new Vector6(jobValue, jobValue, jobValue, jobValue, jobValue, jobValue);

for(int i = 1; i < 6; i++) {
    float deviation = Random.Range(-variation, variation);
    skills += deviation * basisVectors[i];
}

```

Here we slide ± `variation` along each of our tangent directions, mixing up the skill values while preserving their weighted sum.

The trouble is, this can give us fractional skill values! And when we round them to integers, we might no longer have exactly the job skill value we want.

You could take this and apply a fix-up step, where you choose a skill to raise or lower to restore the desired sum.

---

Or we can solve the equation for integer solutions in the first place, which makes this a Linear Diophantine Equation in six unknowns.

I had to teach myself how to solve these to answer this question, and the math's still a little unfamiliar so I might not be doing it in the most elegant/rigorous way. But here's the outline of the solution:

* If we have a linear Diophantine equation in two unknowns, \\$a x + b y = r\\$...

+ We can use Euclid's algorithm to find the greatest common divisor of \\$a\\$ and \\$b\\$, \\$d\\$
    + The equation has a solution if and only if \\$d | r\\$ (ie. `r % d == 0`)
    + We can backtrack through the steps of Euclid's algorithm to find a solution \\$(x\_\*, y\_\*)\\$ to the equation \\$a x + b y = d\\$
    + We can use this to find a solution to our original equation, \\$a x + b y = d\\$ by just scaling the whole thing up by \\$\frac r d\\$: \\$\left(x\_\* \frac r d, y\_\* \frac r d\right)\\$
    + Once we have one solution, we can navigate to any other by adding a multiple of \\$\left(\frac b d, \frac a d \right)\\$ to our \\$(x, y)\\$ pair, without changing the value of the right-hand side

    (we'll use this to apply randomization to our stats without changing the total job value)
* If we have an equation with more unknowns, we can lump all but the last term together into one (so now we're back to just two unknowns), solve for the last term, then chip it off and repeat:

$$a\_0 x\_0 + a\_1 x\_1 + a\_2 x\_2 + ... + a\_n x\_n = r$$

Is equivalent to...

$$gcd(a\_0 ... a\_{n - 1}) y\_{n-1} + a\_n x\_n = r$$

Once we solve this for \\$x\_n\\$, we can subtract \\$a\_n x\_n\\$ from both sides and continue with the remaining \\$n - 1\\$ unknowns...

$$gcd(a\_0 ... a\_{n - 2}) y\_{n-2} + a\_{n - 1} x\_{n - 1} = r - a\_n x\_n\\ ...\\ gcd(a\_0, a\_1) y\_1 + a\_2 x\_2 = r - \sum\_{i = 3}^n a\_i x\_i\\ a\_0 x\_0 + a\_1 x\_1 = r - \sum\_{i = 2}^n a\_i x\_i$$

(Note we never really solve for the \\$y\_i\\$ terms, they're just standing-in for the rest of the equations we haven't solved yet)

So, what that can look like in code: first, let's make a workhorse to handle solving the two-unknown case, giving us the triplet \\$\left(x\_\*, y\_\*, d\right)\\$

```
public struct DiophantineSolution {
    public readonly int x;
    public readonly int y;
    public readonly int gcd;

    DiophantineSolution(int x, int y, int gcd) {
        this.x = x;
        this.y = y;
        this.gcd = gcd;
    }

    public static implicit operator bool(DiophantineSolution s) {
        return s.gcd > 0;
    }
    public static DiophantineSolution invalid {
        get { return new DiophantineSolution(-1, -1, -1); }
    }

    static Stack<int> quotients = new Stack<int>();
    public static DiophantineSolution Solve(int a, int b) {

        // Assume a > b - if not, flip it, solve it, then flip back.
        if (a < b) {
            var flip = Solve(b, a);
            return new DiophantineSolution(flip.y, flip.x, flip.gcd);
        }

        // For now, we'll handle only cases with non-negative coefficients.
        if (a <= 0 || b < 0)
            return invalid;

        // Trivial solution if we have only one unknown with a nonzero coefficient:
        if (b == 0)
            return new DiophantineSolution(1, 0, a);

        // Euclidean Algorithm to find the greatest common divisor:
        int x = a, y = b;
        int remainder = -1;
        do {
            int quotient = System.Math.DivRem(x, y, out remainder);
            // Save the quotients along the way to use in building the initial solution.
            quotients.Push(quotient);

            x = y;
            y = remainder;
        } while (remainder > 0);

        // If b exactly divides a, we have a trivial solution.
        if (quotients.Count == 1)
            return new DiophantineSolution(1, 1 - quotients.Pop(), b);

        // Otherwise, rewind to the last step with a non-zero remainder.
        remainder = x;
        quotients.Pop();

        // Form the equation   remainder = dividend * (1) + divisor * (- quotient)
        // Where x & y are coefficients:               x                   y
        x = 1;
        y = -quotients.Pop();

        // Reverse the steps of the Euclidean algorithm to get a solution to
        // remainder = a * x + b * y
        while (quotients.Count > 0) {
            x -= y * quotients.Pop();     // 1 + 4 * 1
            Swap(ref x, ref y);
        }

        // Now we have our initial solution.
        return new DiophantineSolution(x, y, remainder);
    }
}

```

Now we're ready to use this to randomize our stats:

```
Stack<int> sums = new Stack<int>();
Stack<DiophantineSolution> intermediates = new Stack<DiophantineSolution>();

void GenerateSkills(int[] weights, int targetValue, int randomnessRange) {
    // Build up our table of greatest common divisors of the first i weights,
    // storing the solution information for re-use later.
    // We'll also store the sum of the first i weights for evening-out the stats.
    intermediates.Push(DiophantineSolution.Solve(weights[0], 0));
    sums.Push(weights[0]);
    for (int i = 1; i < weights.Length; i++) {
        intermediates.Push(DiophantineSolution.Solve(intermediates.Peek().gcd, weights[i]));
        sums.Push(sums.Peek() + weights[i]);
    }

    // Compute the right-hand side of our equation.
    int rhs = sums.Peek() * goalValue;

    // Solve the stats one at a time, from the last down to the second...
    for(int i = weights.Length - 1; i > 0; --i) {

        var solution = intermediates.Pop;
        var precedent = intermediates.Peek();

        // Initial solution to (... + a_i x_i = rhs)
        int baseline = solution.y * rhs / solution.gcd;

        // Spacing between possible solution values.
        int step = precedent.gcd / solution.gcd;

        // Which solution comes closest to giving all remaining stats an equal value?
        int closest = Mathf.RoundToInt((myShare - baseline) / (float)step);

        // How far can we stray from this evenly-distributed solution?
        int range = randomnessRange / step;

        // Apply random deviation within this range.
        int deviation = Random.Range(-range, range + 1);

        // Shift our baseline solution by our chosen multiple of the solution spacing.
        skills[i] = baseline + step * (closest + deviation);

        // Deduct the value we've accounted for from the right side of the equation.
        int contribution = skills[i] * weights[i];
        rhs -= contribution;
    }

    // The first skill handles whatever is left over.
    skills[0] = rhs / weights[0];

    // Clean up after ourselves.
    intermediates.Pop();
    sums.Pop();
}

```
> 10 votes

---
Tags: game-design, algorithm, random, character
---


# Question
Title: Clarifications about usage of delegates, events and coroutine in a Unity script
So, the question is a bit broad, but I need to clarify my ideas about how to use proficiently such tools.

Background: I am writing a simple demo that basically does what simcity does: it start a game, create a player entity, a city entity, set up the various electricity/gas/water services and generic bozo that will be part of the population of the city. On top of that, the game spawn X competitors, each with a city on their own, so there is a sense of urgency in having the city up and running, and have it running properly.

This is by no mean a sim city clone; I am just using it to learn further the various aspects of a game, and since I know sim city in and out, and there is virtually no specific material for such games (because all love to do either 2d games, FPS, RPG or RTS, even in training material), it seems the best way to learn something related to the real world.

Now, done with the background and back to the question.

The demo start when you create a new game, spawn all the needed entity, and tehn goes on by cycles; where one cycle can be either 1 min, 5 min, 1 hour...whatever time you deem correct. When a cycle pass. I need to be sure that

* The player expenses are deducted by the bank account
* UI is updated
* AI players has their expenses subtracted and cash updated
* AI entities behave coherently, either driving around the city or going back home (imagine a night-day cycle).

In the beginning I just told myself that I could use a coroutine; where I loop into it, until each entity (AI, Player, AI citizens), are done with their workload, and when all 3 are done, I change a bool to set the coroutine bool to false, so a new cycle can start.

```
public class EntityCitizen()
{
    public bool runCitizenloop()
    {
        //do your things here
        return true;
    }
}

public class EntityPlayer()
{
    public bool runPlayerloop()
    {
        //do your things here
        return true;
    }
}

public class EntityAIPlayer()
{
    public bool runAIloop()
    {
        //do your things here
        return true;
    }
}

public class GameManager()
{

    private cycle = 0;

    public Awake()
    {
         StartCoroutine("cycleloop", 10f);
    }

    IEnumerator cycleloop(float cyclelenght)
    {
        while (!EntityAIPlayer.runAILoop() && !EntityPlayer.runPlayerLoop() && !EntityCitizen.runCitizenLoop())
        {
            // wait until all is done
            yield return void;

        }
        Debug.Log("A cycle has passed");
        cycle += 1;
    }
}

```

This feel somehow off to me, so before code a mess, I thought that it is better to think further about it. I realized that C# has delegates and events; which I could use to trigger the other way around, activities and updates on the various agents; every time that a cycle in the coroutine is done.

But even in this way, I see that something is off; the whole game cycle revolve around each entity completing their actions, and this means that somehow, they have to execute at the same time in parallel (so use coroutines), and also they have to happen in sequence (since an AI mayor can't have more turns than a player, just because he is faster).

What would be the correct way to lay down the overall architecture, to guarantee that each entity is finishing their workload, before that a new cycle may start?

I thought of coroutine for each entity, with events that fire once they are done, which trigger the new cycle in the main coroutine. Would that be correct or am I missing something?

# Answer
Your basic structure of calling an AI loop each frame is a bit strange. That would lead to the AI loops having convoluted, messy code, to determine the state change since last frame.

Here's one alternate approach:

```
IEnumerator cycleLoop(float cycleLength)
{
    EntityAI.StartCycle();
    EntityPlayer.StartCycle();
    yield return new WaitUntil(() => EntityAI.IsDone && EntityPlayer.IsDone);
    cycle += 1;
}

```

You can use `yield return new WaitUntil()` with an anonymous delegate to wait for something to finish. And having a public property `IsDone` is easier to read and understand, and likely to produce better-quality code, than calling `runAILoop()`/`runPlayerLoop()` and checking for a bool.

Another, more generic approach:

```
public class GameManager : MonoBehaviour {
    private HashSet<Cycle> pendingCycles = new HashSet<Cycle>();

    private void OnEnable() {
        EntityAI.OnStart.AddListener(onCycleStart);
        EntityPlayer.OnStart.AddListener(onCycleStart);
        EntityAI.OnDone.AddListener(onCycleDone);
        EntityPlayer.OnDone.AddListener(onCycleDone);
    }

    private void onCycleStart(Cycle cycle) {
        pendingCycles.Add(cycle);
    }

    private void onCycleDone(Cycle cycle) {
        pendingCycles.Remove(cycle);
    }

    private IEnumerator cycleLoop(float cycleLength)
    {
        EntityAI.StartCycle();
        EntityPlayer.StartCycle();
        yield return new WaitUntil(() => pendingCycles.Count == 0);
        cycle += 1;
    }
}

public class CycleEvent : UnityEvent<Cycle> {}

public class Cycle {
    private CycleEvent onStart = new CycleEvent();
    public CycleEvent OnStart => onStart;
    private CycleEvent onDone = new CycleEvent();
    public CycleEvent OnDone => onDone;

    public void StartCycle() {
        StartCoroutine(runCycle());
        onStart.Invoke(this)
    }

    virtual protected IEnumerator runCycle() {

    }
}

public class EntityPlayer : Cycle
{
    override protected IEnumerator runCycle() {
        //[code here]
        onDone.Invoke(this);
    }
}

```

etc

This approach makes it very easy to add new objects to the queue without needing an increasingly complicated `WaitUntil` condition.
> 1 votes

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


# Question
Title: How does one organize AI interactions with Local and Remote Players?
**Scenario:** In a first-person multiplayer game, an AI monster grabs a player. (This would be first-person player on the client's local machine, and a third-person remote player on the master and other client machines)

I'm trying to weigh the merits of different implementations of how these interactions could be organised.

In this scenario, I can think of a couple different ways of implementing but I'm not sure what assumptions they might make which could result in a problem down the line:

1. The Monster could, in its grab function, have a test `IsFirstPerson` and then perform the FirstPerson specific or ThirdPerson specific grab mechanics, or
2. The Monster could talk to an IGrabbable interface on the Player (remote or local), which would return whether it is FirstPerson or ThirdPerson and then perform the specific grab mechanics, or
3. The Monster could talk to an IGrabbable interface on the Player (remote or local), which would return/dictate the full details of how the Monster should grab.

(And for clarity - differences in implementation of FirstPerson or ThirdPerson would be where the hands are or headlook - in first person it would look directly into the camera, but in third person it'd look at where the eyes are; differing struggle animations, etc)

# Answer
The monster shouldn't know or care whether the thing it is grabbing is a local or remote player, or what perspective that player is playing from. That's likely to lead to coding headaches and synchronization issues.

The *only thing* that might be different between clients is what animation it plays, if you want it to use a different animation for first-person than for third-person. The best way to approach this will partially depend on the multiplayer framework you're using. E.g. if you're using Photon, you can (IIRC) check an `IsLocalPlayer` property on the Player object. Your example #2 is best, since the player object should not know or care about the implementation details of the monster grabbing it.

If you think you need the monster to know about whether it's attacking a local or remote player for any other reason, you are probably approaching this from the wrong perspective. In that case, it would be helpful for you to clarify your reasoning.
> 3 votes

---
Tags: unity, architecture, networking, ai, online
---


# Question
Title: Is there a way to specify normals as per-face instead of per-vertex in Unity?
The documentation says that `mesh.normals`

> are assigned to vertices, not triangles.

I've got a somewhat detailed mesh where faces are joining at right angles. If I don't set the normals, everything takes on a kind of metallic appearance. If I set the normals on the vertices, though, then I have to specify which face I'm using and then the edges are very rounded.

I don't mind making separate meshes for each surface, but it seems kind of a waste to not share the vertices. Is there a way to specify per-face normals instead of per-vertex?

# Answer
I tried for a while to do this, but there was no way of setting normals that I could find that resulted in the appearance I wanted. With shared vertices, the object came out looking like this (a dynamic cylinder with a hole in the middle):

I bailed on the shared vertices and created separate sections; left, right, interior, exterior, assigned the normals there (Vector3.left or Vector3.right for the appropriate sides or "spoke" rays for the interior/exterior surfaces) and got the following:

This is a dynamic mesh, so I'm free to increase the number of sections that comprise the shape. Above is 12 sections, below is 30:

I went from lumpy toilet paper to the crisp edges I was looking for. Seems somewhat less efficient, but I tried to consider for a while how I could instruct unity to smooth some edges and not others and couldn't think of a reasonable way to do it (which is probably why things are the way they are.)

I was a bit concerned that Unity would smooth the outer surface but not smooth the corners, resulting in a wonky edge where the two meshes meet, but that wasn't an issue. That might be because all the "sub-meshes" are all actually on the same `mesh` in the script, but I've got a satisfactory result now and I'm not willing to spend a lot of time trying to find ways to break it.
> 1 votes

---
Tags: unity, 3d-meshes, dynamic-mesh
---


# Question
Title: Dragging a Rigidbody2d without moving other Rigidbodies
There are obstacles and other objects that are draggable. Colliders and dynamic rigidbodies are on the draggable object and there are colliders on the obstacles.

The problem is that with the following script, that was provided as an example in this answer, the draggable objects are colliding into each other, so the dragged object can push other draggable objects around.

How do I stop this from happening?

```
using System.Collections;
using UnityEngine;

public class DragTest : MonoBehaviour
{
    public enum DragMode {
        TransformPosition,
        MovePosition,
        Velocity,
        BoxCast
    }

    [Tooltip("Choose how to move the object to the cursor")]
    public DragMode mode;
    [Tooltip("Optional limit on how fast the object can follow")]
    public float maxSpeed = float.PositiveInfinity;
    [Tooltip("Select which layers should block the boxcast drag mode")]
    public LayerMask obstacleLayers;

    Rigidbody2D _body;
    BoxCollider2D _collider;

    delegate YieldInstruction dragMethod(Vector2 destination);

    // Start a drag using the selected method when clicked.
    void OnMouseDown() {
        dragMethod method = null;
        switch (mode) {
            case DragMode.TransformPosition:
                method = TransformPosition;
                break;
            case DragMode.MovePosition:
                method = MovePosition;
                break;
            case DragMode.Velocity:
                method = Velocity;
                break;
            case DragMode.BoxCast:
                method = BoxCast;
                break;
        }
        // Start a function that will run each frame/physics step
        // to update our dragged position until the button is released.
        StartCoroutine(Drag(method));
    }

    // Update the dragged position as long as the mouse button is held.
    IEnumerator Drag(dragMethod dragTo) {
        // Turn off our gravity while we're being dragged.
        float cachedGravityScale = _body.gravityScale;
        _body.gravityScale = 0f;

        // Stash our current offset from the cursor,
        // so we can preserve it through the move.
        var offset = transform.InverseTransformPoint(ComputeCursorPosition());

        while (Input.GetMouseButton(0)) {
            // Keep the object from accumulating velocity while dragging.
            _body.velocity = Vector2.zero;
            _body.angularVelocity = 0f;

            // Calculate desired drag position.
            var cursor = ComputeCursorPosition();
            var destination = cursor - transform.TransformVector(offset);

            var travel = Vector2.ClampMagnitude(
                destination - transform.position,
                maxSpeed * Time.deltaTime);

            // Let our chosen drag method choose how to get us there.
            yield return dragTo(_body.position + travel);
        }

        // Re-enable gravity as before.
        _body.gravityScale = cachedGravityScale;
    }

    // Using this method, the object will teleport through obstacles.
    YieldInstruction TransformPosition(Vector2 destination) {
        transform.position = destination;
        return null;
    }

    // Using this method, the object will stop at obstacles,
    // though it may penetrate for a frame before rebounding.
    YieldInstruction MovePosition(Vector2 destination) {
        _body.MovePosition(destination);
        return null;
    }

    // Effectively the same results as MovePosition.
    YieldInstruction Velocity(Vector2 destination) {
        var velocity = (destination - _body.position) / Time.deltaTime;
        _body.velocity = velocity;
        return new WaitForFixedUpdate();
    }

    // Using this method, the object will stop at the border of the obstacle.
    // It can "stick" to surfaces when dragged into them, because it keeps colliding.
    // Pull the cursor parallel or away from the surface to unstick it.
    YieldInstruction BoxCast(Vector2 destination) {
        // Compute the direction & distance to scan ahead.
        var travel = destination - _body.position;
        var distance = travel.magnitude;

        // Skip the query if we're not going anywhere.
        if (Mathf.Approximately(distance, 0f))
            return null;

        // Find the center of our box.
        Vector2 origin = transform.TransformPoint(_collider.offset);

        // Check for any obstacles that our collider would clip on the way.
        var hit = Physics2D.BoxCast(
            origin,
            _collider.size,
            _body.rotation,
            travel,
            distance,
            obstacleLayers);

        // If we hit something, stop just a hair before the collision.
        if (hit.collider) {
            var direction = travel/distance;
            distance = hit.distance - Physics2D.defaultContactOffset * 2f;
            destination = _body.position + direction * distance;
        }

        // Now it's safe to use any of our other methods without penetrating/tunneling,
        // since we took responsibility for avoiding collisions ourselves.
        transform.position = destination;
        return null;
    }

    // Initialize component dependencies.
    void Start() {
        _body = GetComponent<Rigidbody2D>();
        _collider = GetComponent<BoxCollider2D>();
    }

    // Utility functions to compute dragged position.
    float GetDepthOffset(Transform relativeTo) {
        Vector3 offset = transform.position - relativeTo.position;
        return Vector3.Dot(offset, relativeTo.forward);
    }

    Vector3 ComputeCursorPosition() {
        var camera = Camera.main;
        var screenPosition = Input.mousePosition;
        screenPosition.z = GetDepthOffset(camera.transform);
        var worldPosition = camera.ScreenToWorldPoint(screenPosition);
        return worldPosition;
    }
}

```

# Answer
This script was only intended to demonstrate that positioning objects with physics methods was possible.

You can make a few improvements to handle some of the edge cases you're observing:

1. Swap the dragged object to a different layer when dragging, so its own collider doesn't distract the physics query.

(In my original example, the draggables and obstacles were already on separate layers, but if you want draggables to count as obstacles then you need to swap the layer of just the dragged object)

public string draggingLayerName = "Dragging";

IEnumerator Drag(dragMethod dragTo) {
    int cachedLayer = gameObject.layer;
    gameObject.layer = LayerMask.NameToLayer(draggingLayerName);

```
   // ...

   while (Input.GetMouseButton(0)) {
       // ...
   }

   // ...

   // Done dragging. Put the object back on the layer we found it.
   gameObject.layer = cachedLayer;

```

}

2. Adjust the padding around boxcast hits to be aware of the direction from which we approached. If we come in at a very shallow angle, we need to back up further to escape collision.

```
if (hit.collider) {
    distance = hit.distance;
    distance += Physics2D.defaultContactOffset * 4f / Vector2.Dot(hit.normal, direction);
    destination = _body.position + distance * direction;
}
```
> 0 votes

---
Tags: rigidbody, collider
---


title: RPG movement holding down button

text:
# Question
Title: RPG movement holding down button
I've been writing a simple top down mini RPG in python.

My problem is that when I move the player I have to repeatedly tap the arrow key. Each time I tap the key the player moves 5 PX in the direction of the key I press, but if I hold down the key he doesn't keep moving, he just moves the first 5 PX.

My moving code looks like this:

```
# event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:          # check for key presses
            if event.key == pygame.K_LEFT:        # left arrow turns left
                x = x + -x_speed
            elif event.key == pygame.K_RIGHT:     # right arrow turns right
                x = x + x_speed
            elif event.key == pygame.K_UP:        # up arrow goes up
                y = y + -y_speed
            elif event.key == pygame.K_DOWN:     # down arrow goes down
                y = y + y_speed

```

And farther up I define the x\_speed ect.

How do I make it keep moving when I hold down the key?

# Answer
Your problem is the fact that you're only looking at `KEYDOWN` events.

What you need to do is toggle a boolean value when a key is pressed or released.

Something like this would work:

```
# event loop
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        sys.exit()
    elif event.type == pygame.KEYDOWN:          # check for key presses
        if event.key == pygame.K_LEFT:        # left arrow turns left
            pressed_left = True
        elif event.key == pygame.K_RIGHT:     # right arrow turns right
            pressed_right = True
        elif event.key == pygame.K_UP:        # up arrow goes up
            pressed_up = True
        elif event.key == pygame.K_DOWN:     # down arrow goes down
            pressed_down = True
    elif event.type == pygame.KEYUP:            # check for key releases
        if event.key == pygame.K_LEFT:        # left arrow turns left
            pressed_left = False
        elif event.key == pygame.K_RIGHT:     # right arrow turns right
            pressed_right = False
        elif event.key == pygame.K_UP:        # up arrow goes up
            pressed_up = False
        elif event.key == pygame.K_DOWN:     # down arrow goes down
            pressed_down = False

# In your game loop, check for key states:
if pressed_left:
    x -= x_speed
if pressed_right:
    x += x_speed
if pressed_up:
    y -= y_speed
if pressed_down:
    y += y_speed

```

This way, you're actually looking at *both* presses and releases, and moving while the key is pressed.
> 9 votes

# Answer
I don't know python, but have you tried setting a bool to true when the key is pressed, and changing the speed in an if statement based on that bool. When the key gets released you just have to set the bool back to false.
> 4 votes

# Answer
I don't know python or pygame, but assuming you're using a game library there should be a way to poll the state of the key, such as if it's currently down or not instead of if it was pressed since last update. Use that for checking and updating movement.

The next problem you will run into is it will update movement as fast as your logic update interval is as long as the key is held down. To fix this you need a variable to act as a cooldown so when you poll the state of the key and use it to move, the variable is set to the cooldown amount, and you can't move again until that cooldown reaches zero. So for an example of basic movement code assuming an arbitrary library and language:

```
constant int COOLDOWN_TIME = 170; //170 milliseconds
int cooldown = 0;

void update(int delta) {
    if (cooldown <= 0) {
        if (Input.isKeyDown(Key_Left)) {
            x -= x_speed;
            cooldown += COOLDOWN_TIME;
        }
        else if (Input.isKeyDown(Key_Right)) {
            x += x_speed;
            cooldown += COOLDOWN_TIME;
        }
        if (Input.isKeyDown(Key_Up)) {
            y -= y_speed;
            cooldown += COOLDOWN_TIME;
        }
        else if (Input.isKeyDown(Key_Down)) {
            y += y_speed
            cooldown += COOLDOWN_TIME;
        }
    }
    else {
        cooldown -= delta;
    }
}

```

Where delta would be the time in milliseconds passed since the last logic update.
> 3 votes

# Answer
I asked a question here that's very similar, and received the following answer:

> The way to deal with this is to set a timer once the person taps the phone. The most user friendly scenario that you'd implement would look something like this:
>
> 1. When you detect a tap, set a timer (t = timeToRepeat)
> 2. On each frame, decrease the timer by dt
> 3. If the timer reaches zero, move the sprite a tile and reset the timer
> 4. If the user releases their finger before the first cycle of the timer, move the sprite one tile
>
> Obviously the amount of time that you set your timer to will determine how fast your sprite moves. There are a few variations on this theme depending on the kind of behavior you want as well. For example, you can move the sprite once immediately upon detecting a tap and ignore step #4.

Implementing this would make the user able to tap to move a single time and to be able to move multiple tiles by holding, which I think is ideal.
> 2 votes

# Answer
I believe that this is what you were looking for:

```
keys = pygame.key.get_pressed()  # checking pressed keys
    if keys[pygame.K_ESCAPE]:  # If 'esc' - QUIT GAME
        game_exit = True
    if keys[pygame.K_RIGHT]:  # If 'right' - MOVE RIGHT
        character.move('right')

```

The longer you hold the key down, the more it would move
> 2 votes

# Answer
try to make a variable that holds up your movement results and then put the variable in the while loop not the for loop something like that

```
GameExit = True
    while not GameExit
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                GameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5
                elif event.key == pygame.K_RIGHT:
                    x_change = 5
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
        x +=  x_change

```

x is your object x place
> 1 votes

---
Tags: python, input, pygame, keyboard
---


# Question
Title: Moving an object to random points Unity3d c#
So here is the problem I want to change the position of gameObject to specific points that I declared with empty objects randomly but the problem is the moment the object reaches one of the points it starts shaking around and not doing the same thing again here is my code

```
public class EnemyController : MonoBehaviour {

public Transform[] movePoints;
public float speed;
private int amount;
private Transform currentTarget;

void Start () {
    randoming ();

}

void Update () {
    Movement ();
}

void randoming(){
    amount = Random.Range (0, movePoints.Length);
    currentTarget = movePoints[amount];
}

void Movement(){
    transform.position = Vector3.MoveTowards (transform.position, currentTarget.position, speed * Time.deltaTime);
    StartCoroutine (startMoving());
}

IEnumerator startMoving(){
    yield return new WaitForSeconds (5.05f);
    randoming ();
}

```

}

# Answer
You are calling `Movement` every `Update` frame, so you are starting a new coroutine for `startMoving` several times a second. You won't see the effects of this at first because each one is waiting 5.05 seconds, but after that I expect the object starts shaking because `randoming` will be called many times per second as all those coroutines finish. In other words, your object appears to be shaking because the `currentTarget`, towards which it is supposed to move, is being changed too rapidly for it to move significantly in any one direction.

It would be easier for you to just use a float as a timer to count down when you want to change targets instead of using the coroutine.

```
public class EnemyController : MonoBehaviour {

public Transform[] movePoints;
public float speed;
private int amount;
private Transform currentTarget;
private float timer = 0f;

    void Start () {
        randoming ();
    }

    void Update () {
        Movement ();
        timer += Time.deltaTime;
        if (timer > 5.05f)
        {
            randoming();
            timer = 0f;
        }
    }

    void randoming() {
        amount = Random.Range (0, movePoints.Length);
        currentTarget = movePoints[amount];
    }

    void Movement() {
        transform.position = Vector3.MoveTowards (transform.position, currentTarget.position, speed * Time.deltaTime);
    }

}

```
> 1 votes

# Answer
if you only want your objects to move to a random point i believe its a wrong approach. just define a general destination Like Below:

```
public Transform destination;

```

first set the Transform in inspector on any other way you know. then just in the start section make you object to move to that destination. for this you have to define another temp **Transform** Variable. its the whole code:

```
[SerializeField] private   Transform Destination;
    [SerializeField] private float speed;
    private Vector3 tempDestination;

Start()
{
  tempDestination = new Vector3(Destination.position.x+Random.Range(0,5),
            Destination.position.y + Random.Range(0, 5),
            Destination.position.z + Random.Range(0, 5) );
}

Update()
{
        transform.position = Vector3.MoveTowards(transform.position, tempDestination, speed);

}

```
> 0 votes

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


# Question
Title: Math / game design for non-linear armor degradation?
I have a game that is about starships shooting each other. Starships have a values that represent initial Health, Armour and Damage degradation

Example 1000, 800, 80% // 1000 HP, 800 Armour, 80 % mitigation 300, 250, 60% // 300 HP, 250 Armour, 60 % mitigation

Note Armour and mitigation are in relation to each other and armour will be lowered on damage, lowering the associated mitigation in the process.

Resolving damage start with a pure damage value, something like 50. I then check the targeted ship for existing damage entries. Depending on that, i reduce the "armour", translate it to a modified mitigation value and mitigate the damage by x%, reducing the armour in the process, so the next hit will encounter less armour, hence less mitigation etc.

**example**

A virgin ship has 1000/800/60% - hp/armour/% and is hit for an initial 50 damage.

Check the ship, see it has no damage received yet.

Take the damage (50), apply the armour modifier (800 of 800 remains, so 60% mitigation applies).

Split the damage into 40%/60% (hp, armour damage), so 20 of the 50 damage damage the hull, while 30 damage are eaten up by armour - lowering armour, and effective mitigation, for the next hits.

**Next hit, 50 damage**

Ship has 980/1000 Health, 770/800 armour.

With 800 armour giving 60% mitigation, 760 armour will give 57 % mitigation

50 damage are split into 43%/57% Hull/Armour damage -\> 21/29 points.

this continues until a ship has no hull left.

How can i modify this so it becomes more of progressive curve, i.e. initial hits take bigger chunks of armour/mitigation relative to later hits (currently the the first few hits obviously eat more mitigation than later hits, but i want it to be more even more effective at the beginning.

How do i modify my math ? Do i need to add a square/root somewhere ?

# Answer
An alternative method which I've used with some success is to apply a percentage of remaining armor as absolute mitigation.

Example:

> Mitigation factor: 10%
> HP: 1000
> Armor: 800
> Effective Mitigation: 800 * 10% = 80
>
> Ship is hit for 80 damage, armor is reduced by 80
>
> HP: 1000
> Armor: 720
> Effective Mitigation: 720 * 10% = 72
>
> Ship is hit for 80 damage, armor is reduced by 72, health is reduced by 8
>
> HP: 992
> Armor: 648
> Effective Mitigation: 648 * 10% = 65

### This has three primary effects:

* With a sufficiently high mitigation factor, armor is 100% effective at first and will rapidly decline after a certain threshold. This is a decent approximation of what you're asking for with a simple and easy to calculate formula.
* **Damage per hit affects armor penetration.** High damage, single shot weapons have an easier time punching through (doing more hull damage and leaving armor mostly intact) while multiple low damage hits mostly degrade armor.
* In your original system, hull and armor damage are essentially functions of each other (ignoring rounding error), so you might as well have just one health bar. The proposed system allows for hull and armor to degrade somewhat independently, **making the distinction mechanically meaningful**, while keeping the relation *1 damage = 1 hull = 1 armor* intact.
> 2 votes

# Answer
Of course there is no definite answer on this one. Only different possibilities, endless I would say. Still the question isn't easy to answer. Here are a few ideas that come to my mind, if they play out according to your wishes will only be decidable by you - probably in game.

First possibility: Loosen up on your "mitigation" model. Right now you strictly separate the incoming damage to either go to the armor or the hp value. This gives you a pretty clean mathematical model. But I can find two reasons why a player may expect another behavior from his armor:

1. It takes less damage when in lesser shape. If my armor is only at half its original strength it somehow only takes less damage from incoming blow, while the health of the hull takes more and more. As a player at this point I may feel betrayed by my protection or feel that this is an inefficient design.
2. With the damage to the shields declining, so will the mitigation percentage difference. At first the mitigation potential of the armor will drop by 3 for the first three hits, then by 2 for nearly 10 hits and then by 1 for the last 15.

(These numbers and observations are based on the following calculation of your model: Original Mitigation Model)

Still from a game design perspective, I would value the first point a lot more. The second though fits your desire to change the curve.

One radical way to achieve that is to fight the first irritation: Do not reduce the damage to the shields, always subtract the full incoming damage from your armor. That would lead to linear mitigation decline and nearly linear damage increase. The ships then would loose their complete armor quite some time before destruction and would since then receive the full incoming "pure" damage.

To rebalance your ships you might then have to create them with higher initial armor which will make the difference between initial damage protection and final damage protection (0) even greater. (For the calculation of the hits until armor destruction view this image: Linear Mitigation Decrease)

---

Second possibility: Keep the mitigation concept like you have it (alas: keep dividing the damage between reducing hull or armor), but choose a different formula to calculate mitigation from armor. Right now, the mitigation value is proportional to the armor value, determined by the proportion factor 60/800. Instead there are quite a few possibilities to link these to values. You want a model that starts high and falls steeply. A square function, like you proposed would do that for you.

To test that out I choose one extra point of the curve, say at armor value 600 you only want 30 percent mitigation left, and you got the two points to determine the factors in the quadratic function

```
Mitigation(Armor) = a * Armor² + b * Armor

```

For the example given these are the resulting coefficients:

```
a = 1/8000
b = -1/40

```

This will give you a model which at the first hit declines the mitigation by 6 percent and then by 4 and then by 3 and then by 2, quickly dropping from 60 percent to 30 in 10 hits. (Details)

This is only one example of an quadratic connection of the two values, you could choose different, even steeper points to determine the coefficients, since I did the calculation by hand I tried to keep it manageable.

If you would like to look at another example altogether for different mathematical solutions I would suggest exponential regress.

I will however not cover this here, hoping with the idea given you could apply the transfer to exponential curves. Be advised that these models would require more mathematical handiwork every time you would want to change the balancing of your game. (And of course the first time you would want to implement it. But for these topics there are a lot of resources out there, like the wikipedia math section or the stackexchange math forum.)

\[Side Note: In my (humble) experience simple equations make your balancing job a lot easier and may allow the player a greater understanding of your games mechanics, thus allowing him (and you as tester) a more strategic experience.\]

---

For my third (and final) suggestion I would return to try to find a different algorithm completely rather than a different mathematical solution. By that this suggestion is pretty similar to the first one in concept and in implementation.

Additionally it is really simple, we keep the Mitigation/Armor-Proportionality and the damage divide, but we artificially increase the weakness of the armor. After the damage was divided into hull/armor damage we take the armor damage and multiply it by two. So the first hit takes 20 of our hp and a high 60 of our armor.

By this we keep the original concept, with all mathematical effects: As the armor drops down, the damage the armor draws drops down too and the mitigation decline stagnates. But till then the armor drops down a lot lot faster and the mitigation drops even faster than with the second solution from 60 to 30 in 10 hits until finally calming down at hit 15. (Details)

Like the first concept this third one would call for an increase of your initial armor values (while not necessarily increasing initial mitigation). And of course the factor "2" is one to be tested, higher values increase the dropping rate of mitigation, and therefore steepen the curve.

---

You will have noticed, that I did not answer the question what you should do, but the question, what you could do. And I hope I did so in your interest. As game designer only you have all the information to decide between the presented options. All of them have different side effects which I tried to outline here and all will have to be paired with different rebalancings of your other values. But I consider all of them a possible solution to your problem and hope you find the same.
> 2 votes

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


# Question
Title: How to playlay multiple Particle Systems when colliding with multiple obstacles using object pooling?
I have two types of particle, one for each player:

1. Player 1 (Red Particle)
2. Player 2 (Blue Particle)

When player 1 collides with an obstacle then I want to play the red particle system, and when player 2 collides with an obstacle then I want to play the blue particle system.

Code:

TouchControll.cs

```
 public GameObject PlayersPartical;

  void OnTriggerEnter2D(Collider2D other)  //here my player collided with obstacle
    {
        foreach (Transform child in transform)
        {
            if (child.tag == "point")
            {

                //GameObject partical = Instantiate(twopartical[Random.Range(0,1)], transform.position, transform.rotation);
                //ParticleSystem heal = partical.GetComponent<ParticleSystem>();
                //heal.Play();
                GameObject partical = Instantiate(PlayersPartical, transform.position, transform.rotation);
                ParticleSystem heal = partical.GetComponent<ParticleSystem>();
                heal.Play();

                ObjectPooler.Instance.SpawnFromPool("redandbluepartical", transform.position, Quaternion.identity);
            }
        }
     }

ObjectPooler.cs

    public static ObjectPooler Instance;

    public void Awake()
    {
        Instance = this;
    }

    [System.Serializable]
    public class Pool
    {
        public string tag;
        public GameObject prefab1;
        public GameObject prefab2;
        public int size;
    }

    public List<Pool> pools;

    public Dictionary<string, Queue<GameObject>> pooldictionary;//which gameobject you should be pool

    void Start () {

        pooldictionary = new Dictionary<string, Queue<GameObject>>();

        foreach(Pool pool in pools) //add a pool in list
        {
            Queue<GameObject> objectpool = new Queue<GameObject>();

            for(int i=0;i<pool.size;i++)
            {
                GameObject obj =  Instantiate(pool.prefab1);
                GameObject obj1 = Instantiate(pool.prefab2);
                obj.SetActive(false);
                obj1.SetActive(false);

                //objectpool.Enqueue(obj);
            }

            pooldictionary.Add(pool.tag, objectpool);
        }
    }

   public GameObject SpawnFromPool(string tag,Vector3 position,Quaternion rotation)  //two tag red and blue partical
    {
        if(!pooldictionary.ContainsKey(tag))
        {
            Debug.Log("doesnot exist" + tag);
            return null;
        }

        GameObject objecttospawn =  pooldictionary[tag].Dequeue();

        //here how to call my trigger

        objecttospawn.SetActive(true);
        objecttospawn.transform.position = position; //pos
        objecttospawn.transform.rotation = rotation; //rotation

        pooldictionary[tag].Enqueue(objecttospawn);
        return objecttospawn;
    }

```

Image1:

Image2:

How do I call these particles?

# Answer
For your new question: I've changed the pooling system to new one. this one is not generic but I've written it spacial for your case:

Pooling.CS

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

public enum PlayerColor
{
    Blue,
    Red
};

public class Pooling : MonoBehaviour
{
    public static Pooling Instance;

    [Header("Particles systems")]
    public GameObject particleObject;

    [Header("Particles systems Materials"), Space(10)]
    public Material greenMaterial;
    public Material redMaterial;

    private List<ParticleSystem> particlesList;
    private ParticleSystemRenderer redrer;

    public void Awake()
    {
        Instance = this;
        particlesList = new List<ParticleSystem>();
    }

    public void PlayParticleFromPool(PlayerColor color, Vector3 position, Quaternion rotation)
    {
        if (particlesList.Count < 1)
        {
            GameObject firstParticleObject = Instantiate(particleObject, position, rotation);
            particlesList.Add(firstParticleObject.GetComponent<ParticleSystem>());
            firstParticleObject.transform.parent = transform;
        }

        for (int i = 0; i < particlesList.Count; i++)
        {
            if (!particlesList[i].isPlaying)
            {
                redrer = particlesList[i].GetComponent<ParticleSystemRenderer>();
                switch (color)
                {
                    case PlayerColor.Blue:
                        redrer.material = greenMaterial;
                        break;
                    default:
                        redrer.material = redMaterial;
                        break;
                }

                particlesList[i].Play();
                return;
            }
        }

        GameObject newParticleObject = Instantiate(particleObject, position, rotation);
        newParticleObject.transform.parent = transform;
        particlesList.Add(newParticleObject.GetComponent<ParticleSystem>());
        redrer = newParticleObject.GetComponent<ParticleSystemRenderer>();
        switch (color)
        {
            case PlayerColor.Blue:
                redrer.material = greenMaterial;
                break;
            default:
                redrer.material = redMaterial;
                break;
        }
        newParticleObject.GetComponent<ParticleSystem>().Play();
    }
}

```

And I simplified the player script to satisfy this new Pooling system, Replace Old Code with this:

```
public PlayerColor playerColor;

    void OnTriggerEnter2D(Collider2D other)  //here my player collided with obstacle
    {
        Pooling.Instance.PlayParticleFromPool(playerColor, transform.position, Quaternion.identity);
    }

```

Step By Step Guide How to use these scripts:

1. Replace Your Old Pooling system with new one.
2. Create "Empty Object" and assign the new Pooling script to it.
3. Now Create Two Material One for Red Player and another for Blue Player.
4. Setup Blue particle system Material like this: assign texture for blue particles.
5. Setup Red particle system Material like this: assign texture for red particles
6. Now Change Player Color like this:

7.Select Blue for blue player and select Red for red Player.

8. At last step set you pooling like this:

I Hope this will work. I've tested it and it did worked for me.
> 1 votes

# Answer
I don't know with whom this script is attached but I would say this job should be done by player itself and my way of doing this will be like this:

```
public GameObject playerPartical;

private void OnCollisionEnter(Collision collision)
{
    GameObject particalObject = Instantiate(playerPartical, transform.position, transform.rotation);
    ParticleSystem partical = particalObject.GetComponent<ParticleSystem>();
    partical.Play();
}

```

As this will be attached to each player then "player 1" will get reference to Red particles and "player 2" will get reference to "Blue particles". Now by this way each player will be only responsible for themselves.

But the best possible solution wold to Object pooling. As i don't know much about your game so i would stop here and if you have any question please let me know.
> 1 votes

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


# Question
Title: Multithreading: Each system on a different thread or a thread pool?
I'm building a fairly involved game using OpenGL and C++. I've been thinking about how to implement multithreading, and the two options are:

1) Each system (Graphics, Audio, Physics, et cetera) gets their own dedicated thread that they run off of.

2) Implement a thread pool, that picks up a jobs from a queue (priority queue), executes it and gets re-inserted into the pool to wait for new available job.

I was wondering which one is generally considered better: in terms of performance, maintenance, scalability, code smell, et cetera.

# Answer
> 5 votes
One important concern when deciding units of parallelization is usually to avoid sharing data between threads. Multiple threads operating on the same data is always hairy, because:

* if those accesses are not properly synchronized, you can encounter bugs triggered by race conditions which appear seemingly randomly and are extremely difficult to reproduce and analyze.
* if they *are* properly synchronized, those synchronization techniques can often lead to performance problems and even deadlocks (two threads are locking different data structures and waiting for the other thread to release theirs)

So you generally want threads to communicate with each other as little as possible.

Unfortunately, systems often operate on data delivered by other systems. A good example is the graphics system which renders the game state which gets constantly changed by the physics system. That means that access to the game state must be synchronized. If you render the game state while the physics system changes it, you might occasionally encounter really weird artifacts on the screen. For example, let's say the rendering system wants to render a character who is swinging a sword. The character and their sword are implemented as separate entities by the physics system. At the moment where the rendering system renders both entities, the physics system might have already updated the position of the character but not yet the position of the sword. So you occasionally see the sword getting rendered outside of the fist of the character.

There are two solutions to this synchronization problem, and neither is good. The first is to have one system wait until the other is finished. But if you run your systems in sequence anyway, then you gain nothing by multithreading and can just as well run them on the same thread. The second is to have two copies of the game state. While the rendering engine renders the old state, the physics engine calculates the next state. Then you have a synchronization point, switch out the two states, and proceed with the next frame. But this doubles the amount of RAM you need for your game state.

Another problem with using one thread per system is that the resource consumption between systems is often very unequal. There is little benefit in having 4 threads when 3 of them stall most of the time while only one of them actually maxes out its CPU core. You ideally want to distribute your load on all CPU cores equally.

For these reasons, you might rather look for units of parallelization within your systems.

If you need to run an update on 2000 objects, and those updates do not depend on the states of other objects, then you can use 4 threads and have each one process a set of 500 objects. In the idealized case, this cuts the processing time of that system down to one quarter.

Keep in mind that creating threads is expensive, so you should always use a thread-pool which maintains a number of long-living threads and passes units of work to these threads. I have also seen thread-pool implementations which allow you to pass a job together with a list of other jobs it depends on. The thread-pool will then wait with enqueueing that job until all the dependencies have finished. This makes it a lot safer to implement multithreading across system boundaries if those systems have dependencies on each other.

---
Tags: architecture, multithreading
---


# Question
Title: How to calculate more precisely the position of the pupil in function of the eye ball and a direction?
I have a game in which I have an eye in a head that should always move towards a piece of food (or another piece of food). The head is moved by the player. The food has a fixed position (for some amount of time).

I have solved the maths somehow, but I do not get the precision I want. As I turn around the food, the eye moves almost perfectly, but it is (1) outside the circle sometimes and (2) not perfectly positioned.

Example (left: food, right: head with eye ball with pupil outside the eye ball):

The position of the eye ball is updated on each move of the player.

# Screen recording

# Relevant code in `MainWindow.xaml.cs`

```
EyeBall eb = MyEyeBall;

eb.HorizontalAlignment = HorizontalAlignment.Stretch;
eb.VerticalAlignment = VerticalAlignment.Stretch;

c.Content = eb;

Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() =>
{
    Cell foodCell = GetFoodCell();

    // A - eye center
    // B - first food center (TODO : automatically the closest food)
    // A' - pupil center
    // d1 - distance from center of eye to boundary of pupil
    // d3 - pupil radius

    // hard coded values from the proportions in EyeBall.xaml
    double d1 = 6,
        d3 = 9;

    Point A = eb.TransformToAncestor(MyUniformGrid).Transform(new Point(eb.ActualWidth / 2, eb.ActualHeight / 2));

    Point B = foodCell.TransformToAncestor(MyUniformGrid).Transform(
            new Point(foodCell.ActualWidth / 2, foodCell.ActualHeight / 2));

    double sum = (d1 + d3) * (((FrameworkElement)eb.Child).ActualHeight / eb.ActualHeight);
    //double sum = eb.TransformToAncestor(MyUniformGrid).Transform(new Point(d1 + d3, 0)).X;

    double k = sum / (DistDouble(A, B) - sum);

    Point Ap = new Point(((A.X + k * B.X) / (1d + k)),
        (A.Y + k * B.Y) / (1d + k));

    Point Ap2 = MyUniformGrid.TransformToDescendant(eb).Transform(Ap);

    Debug.WriteLine("===============================================");
    Debug.WriteLine($"food cell position = {Board.Food.Pieces[0].Pos}");
    Debug.WriteLine($"d1 = {d1}, d3 = {d3}");
    Debug.WriteLine($"A = {A}, B = {B}");
    Debug.WriteLine($"k = {k}");
    Debug.WriteLine($"A': {Ap}     ->     {Ap2}");
    Debug.WriteLine("===============================================");

    eb.SetBallCenter(Ap2.X, Ap2.Y);
}));

```

# `EyeBall.xaml.cs`

```
public partial class EyeBall : Viewbox
{
    public EyeBall()
    {
        InitializeComponent();
    }

    internal void SetBallCenter(double x, double y)
    {
        MyBallGeometry.Center = new Point(x, y);
    }

    internal Point GetBallCenter()
    {
        return MyBallGeometry.Center;
    }
}

```

# `EyeBall.xaml`

```
<Viewbox x:Class="wpf_snake.EyeBall"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:wpf_snake"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Canvas Name="svg8" Width="61.809998" Height="60.000003">
        <Canvas.RenderTransform>
            <TranslateTransform X="0" Y="0"/>
        </Canvas.RenderTransform>
        <Canvas Name="layer1">
            <Canvas.RenderTransform>
                <TranslateTransform X="-46.272926" Y="-62.673704"/>
            </Canvas.RenderTransform>
            <Ellipse Canvas.Left="46.3" Width="61.8" Canvas.Top="62.7" Height="60" Name="ellipse971" Fill="#FF8A8EFF" StrokeThickness="0.45579806" StrokeMiterLimit="4" StrokeLineJoin="Round" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Opacity="1"/>
            <Ellipse Canvas.Left="52.9" Canvas.Top="68.4" Width="48.5" Height="48.5" Name="ellipse973" Fill="#FFFFFFFF" StrokeThickness="0.49706328" StrokeMiterLimit="4" StrokeLineJoin="Round" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Opacity="1"/>
            <Ellipse Canvas.Left="59.9" Canvas.Top="75.4" Width="34.5" Height="34.5" Name="circle979" Fill="#7BA9F2FF" StrokeThickness="0.07413793" StrokeMiterLimit="4" StrokeLineJoin="Round" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Opacity="1"/>
        </Canvas>
        <Path Stroke="Transparent" StrokeThickness="0" Fill="Blue" >
            <Path.Data>
                <EllipseGeometry  Center="45,30"  RadiusX="9"  RadiusY="9" x:Name="MyBallGeometry"/>
            </Path.Data>
        </Path>
    </Canvas>
</Viewbox>

```

Thank you.

# Answer
I can't provide you with the code solution, but here's some formulas you might find useful to do it yourself:

**Calculate eyeball position:**

`position = normalize(food_piece - head_center) * head_radius`

**Vector normalization:**

`unit_vector = vector / length(vector)`

be careful not to divide by zero here, so check length before performing division

**Vector length:**

`length = sqrt(vector.x^2 + vector.y^2)`

Alternatively, you may also use `atan2(y, x)`, if available, to get angle between head and food piece. And then convert the angle to the unit vector using `vector = (cos(angle), sin(angle))` and then multiply it by the head radius.

`atan2(food.y - head.y, food.x - head.x)`
> 1 votes

---
Tags: c#, 2d, mathematics, .net, wpf
---


# Question
Title: Monogame - how to make a smooth color transition with Color.Lerp()?
I would like to know how to dynamically change a color. My code:

```
Color myColor;
Color startColor = new Color(255, 255, 255);
Color finalColor = new Color(231, 214, 90);
myColor = Color.Lerp(startColor, finalColor, 0.5f);

spriteBatch.Draw(myTexture, Vector2.Zero, myColor);

```

But the color does not change, in fact I get something similar to the `finalColor`, that's perhaps because I need to decrement the `RGB` values of `startColor` and check if they match `finalColor`? Help would be much appreciated.

# Answer
> 3 votes
If you look at the Color.Lerp documentation you'll notice that the third parameter is the `amount`.

```
public static Color Lerp(Color value1, Color value2, float amount)

```

> amount - A value between 0 and 1.0 indicating the weight of value2.

What this means is that to get the color to change you'll need to change the `amount` over time between values of 0.0 and 1.0. To do this, create a member variable in your class and change it in the `Update` method.

```
 private float _colorAmount = 0.0f;

 protected override void Update(GameTime gameTime)
 {
     var deltaSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;

     _colorAmount += deltaTime;

     if(_colorAmount > 1.0f)
         _colorAmount = 0.0f;

     // rest of update method...
 }

 protected override void Draw(GameTime gameTime)
 {
     // start of draw method..

     var startColor = new Color(255, 255, 255);
     var finalColor = new Color(231, 214, 90);
     var myColor = Color.Lerp(startColor, finalColor, _colorAmount);

     spriteBatch.Draw(myTexture, Vector2.Zero, myColor);

    // rest of draw method...
}

```

Obviously the actual logic you use will differ from the example here, but this should give you enough to get started.

# Answer
> 1 votes
I made this general class to help with any kinda lerping transitions. Thought maybe someone could use it. `Memory.gameTime.ElapsedGameTime.TotalMilliseconds` is a public static variable that my project uses to track the game time you might need to change that for your project.

```
    public class Slide<T>
    {
        #region Fields

        private double _currentMS;
        private T _end;
        private Func<T, T, float, T> _function;
        private T _start;
        private double _totalMS;

        #endregion Fields

        #region Constructors

        public Slide(T start, T end, double totalMS, Func<T, T, float, T> function)
        {
            _start = start;
            _end = end;
            _totalMS = totalMS;
            _function = function;
        }

        #endregion Constructors

        #region Properties

        public double CurrentMS => _currentMS;
        public bool Done => _currentMS >= _totalMS;

        public T End { get => _end; set => _end = value; }
        public Func<T, T, float, T> Function { get => _function; set => _function = value; }
        public T Start { get => _start; set => _start = value; }
        public double TotalMS { get => _totalMS; set => _totalMS = value; }

        #endregion Properties

        #region Methods

        public void Restart() => _currentMS = 0d;

        public void Reverse()
        {
            T tmp = _start; _start = _end; _end = tmp;
        }

        public float UpdatePercent()
        {
            if (!Done)
            {
                _currentMS += Memory.gameTime.ElapsedGameTime.TotalMilliseconds;
                return (float)(Done ? 1f : _currentMS / _totalMS);
            }
            else
                return 1f;
        }

        public T Update()
        {
            float percent;
            if (_function!=null && (percent = UpdatePercent())!=1f)
                return _function(_start, _end, percent);
            return _end;
        }

        #endregion Methods
    }

```

For this question the you can use.

```
Slide<Color> ColorSlider = new Slide<Color>(new Color(255, 255, 255),
                               new Color(231, 214, 90), 2000d, Color.Lerp);
Color cval = ColorSlider.Update();

```

---
Tags: monogame, color
---


# Question
Title: MonoGame: Music does not stop playing upon exit of game
I use MediaPlayer to play the background music. Sometimes, the music does not stop playing when I exit the game. This is even though I use the following code:

```
    protected override void OnExiting(Object sender, EventArgs args)
    {
        base.OnExiting(sender, args);

        MediaPlayer.Stop();
    }

```

What is wrong?

# Answer
As suggested in the comments, you might need to put `MediaPlayer.Stop();` before `base.OnExiting(sender, args);`.
> 1 votes

---
Tags: monogame
---


# Question
Title: couldn't switch to requested monitor resolution in Windows 7
Run the game,and it shows that it couldn't switch to requested monitor resolution, DX11 could not switch resolution in Windows 7(both 32 and 64 bit ) when I tried to build the game with Unity 2017.3, and also on 2018.4, but the dialog keep popping out. I already tried to lowered the resolution and updated the integrated graphic driver, but nothing worked. Any idea would be appreicated.

# Answer
Quick UPDATE

We solved the problem by getting the old version of Unity 5.6, and use dirextx 9 since our program for some reason have to be compatible with Windows 7 32 bit and even some oudated Windows XP. We still do not know about how the issue happened when we used newer vesrsion.
> 1 votes

---
Tags: unity, directx, directx11, resolution
---


# Question
Title: The collision log is displayed only for the original obstacle and not for the duplicates
This is my first game attempt and I'm trying to create a game where my player (a box) stops whenever it collides with an obstacle. However, the log for the collision is only displayed when the player collides with the original obstacle, while no message is displayed for colliding with any other obstacles. Here's my code:

```
public class PlayerCollision : MonoBehaviour
{
    public PlayerMovement movement; //Reference to player movement script

    //This function will run when collision occurs, the info collision is stored in collisionInfo
    void OnCollisionEnter(Collision collisionInfo)
    {
        if (collisionInfo.gameObject.name == "Obstacle")
        {
            movement.enabled = false; //Stop the player from moving
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

```

# Answer
> 1 votes
its obvious that your **OnCollisionEnter** only works that is collided with other object with name of **"Obstacle"**. when you duplicate an object the name changes like **Obstacle(1)**.

if you want it work, you have to rename new objects as first one. right solution for this problem is tags. tags are shared names for group of objects.

instead of `collisionInfo.gameObject.name` use `collisionInfo.gameObject.tag` thenin up right side of you screen find tags section and define new tag named **Obstacle** and set this tag to all of your obstacles. when you duplicate and object, new one still has same **tag**.

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


# Question
Title: Attach an Animated Texture to a Character in Unity
Is it possible to have an animated texture of facial features on a characters face in unity? (I haven't made the game yet, I'm researching). I would like to achieve a cartoon effect.

# Answer
Yes you can achieve this using many way like:

**Solution # 1, Using sprite sheet like mechanism:** (not recommended)

It this way you will be having multiple texture for you character face and you will be changing character face texture over time.

Pros:

1. Easy to implement.

Cons:

1. Too many textures.
2. No run time controls.
3. Hard to make changes to the facial expression.

**Solution # 2, Using Blend shapes:**(recommended)

It this way you don't have to create too many texture instead you will be having only one texture.

Pros:

1. Only one texture to work with.
2. Full facial expression controls at run time.
3. Easy to edit.
4. Can create many expressions.

Cons:

1. time consuming at start.

How to create Blend shapes.
> 2 votes

---
Tags: unity, textures
---


# Question
Title: reading from texture2d resource in directx11
Hi^^ i am trying to read data in resource, which i used to do well without any problems. but suddenly it is not working.

1. first i made **immutable resource** that has data in it, which is `XMFLOAT4(1,1,1,1)` here.
2. next i made **staging resource** for reading.
3. lastly, i called map/unmap to read and store data into `outputArr`.

```
//(all HRESULT checked already)
    int WIDTH = 10, HEIGHT = 2;

    ID3D11Texture2D* resource; // create texture------------------------------
    D3D11_TEXTURE2D_DESC texDesc;
    texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texDesc.Usage = D3D11_USAGE_IMMUTABLE;
    texDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    texDesc.Width = WIDTH;
    texDesc.Height = HEIGHT;
    texDesc.CPUAccessFlags = 0;
    texDesc.ArraySize = 1;
    texDesc.MipLevels = 1;
    texDesc.SampleDesc.Count = 1;
    texDesc.SampleDesc.Quality = 0;
    texDesc.MiscFlags = 0;

    XMFLOAT4* initValues = new XMFLOAT4[WIDTH * HEIGHT];
    for (int i = 0; i < WIDTH * HEIGHT; ++i) {
        initValues[i] = XMFLOAT4(1,1,1,1);
    }
    D3D11_SUBRESOURCE_DATA data;
    data.pSysMem = initValues;
    data.SysMemPitch = sizeof(XMFLOAT4)*WIDTH;
    data.SysMemSlicePitch = 0;
    device->CreateTexture2D(
        &texDesc,
        &data,
        &resource);

    ID3D11Texture2D* staging; // create texture for reading --------------------
    D3D11_TEXTURE2D_DESC stgDesc;
    stgDesc.BindFlags = 0;
    stgDesc.Usage = D3D11_USAGE_STAGING;
    stgDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
    stgDesc.Width = WIDTH;
    stgDesc.Height = HEIGHT;
    stgDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    stgDesc.ArraySize = 1;
    stgDesc.MipLevels = 1;
    stgDesc.SampleDesc.Count = 1;
    stgDesc.SampleDesc.Quality = 0;
    stgDesc.MiscFlags = 0;
    device->CreateTexture2D(
        &stgDesc,
        nullptr,
        &staging);

    XMFLOAT4* outputArr = new XMFLOAT4[WIDTH*HEIGHT]; // READ-------------------
    dContext->CopyResource(staging, resource);
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
    dContext->Map(staging, 0, D3D11_MAP_READ, 0, &mappedResource);

    outputArr = reinterpret_cast<XMFLOAT4*>(mappedResource.pData);
    std::vector<XMFLOAT4> testV;
    for (int y = 0; y < HEIGHT; ++y)
    {
        for (int x = 0; x < WIDTH; ++x)
        {
            int idx = y * WIDTH + x;

            testV.push_back(outputArr[idx]);
        }
    }

    dContext->Unmap(staging, 0);

```

and it turns out, only when `WIDTH` is multiple of 16(`HEIGHT` doesn't seem to be matter here), it copies the data well into ALL element of array, otherwise it fill out just 0 into array until next 16 element.

For example, if width/height is 10/2, first 10 elements of `outputArr` will have proper data and next 6 elements have just 0, and next another 10 elements with data, and 6 elements with 0, so on.

i haven't had any problem on dealing with resources. and struggle still. just my humble assumption is that there might be specific alignment in number of width of resource that i miss. Or silly mistake in my process.

Hope anyone can find something from this question. thanks

# Answer
> 1 votes
i have found the solution. it looks even so pretty.

`testV.push_back(outputArr[idx])` should have been edited like

`testV.push_back(((XMFLOAT4*)((char*)mappedResource.pData + (y* mappedResource.RowPitch) + (x*sizeof(XMFLOAT4))))->y)`

i thought at first time that when i make a 2dTexture(xmfloat4) with `WIDTH * HEIGHT`, its size will be `16*WIDTH*HEIGHT`. But it was wrong !!!. it has some automatic padding in it. so the actual size would be `(16*WIDTH + padding)*HEIGHT`. *i have no idea why, just guessing because a texture can cover a lot of different type, so it makes different padding for types automatically??? maybe*

if anyone know why, plz let me know.

thanks

---
Tags: textures, directx, gpu, data, gpgpu
---


# Question
Title: Unity stop sprite moving when hit be another sprite
I have two dots/points that move onto the screen at start. I have a pencil move and when collide with the points the pencil writes which all works ok.

My problem is when the pencil `RigidBody` hit the `RigidBody` of the point, the point gets pushed out fo position. I cant change the point `RigidBody` to `static` because I need to move it at the start.

pencil script

```
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.name == "Point")
    {
        writing = !writing;
    }
}

```

# Answer
> 2 votes
That's because the two bodies behaving two solid object so when they collide there will impact of collision. instead change your objects from solid to trigger by checking "is Trigger" check box at collider settings like:

Now there will be no impact of collision but you have to change you script like this:

```
private void OnTriggerEnter2D(Collider2D collision)
{
     if (collision.name == "Point")
     {
         writing = !writing;
     }
}

```

Also don't do comparison on name instead use Tags. if you need more information on this pleas let me know.

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


# Question
Title: Drawing an arrow using the LineRenderer in unity
I'm trying to draw an arrow using a `LineRenderer` in Unity, using the code suggested here.

Based on the UI it all seems good, yet it draws a pin needle, rather than the arrow I would expect from the UI. If I understand the UI right, it should thicken 60% into the line and then become thinner again towards the end.

Any idea what might be going wrong?

# Answer
> 2 votes
first of all, you can make arrows with **linerenderer** but its not the best approach. line renderer is for effects and drawing. its hard to customize colliders to it. you can just use an **spriteRenderer** for this. but for a good Drawing i show you my inspector to how work with it.

you have to uncheck **"Use World Space"** to be able to update its position by **Transform** and add more **points** to your lineRenderer. and customize Width dependeing on you needs.

---
Tags: unity, line-renderer
---


# Question
Title: How to draw a string into a polygon? (Libgdx, Java)
I am working on a 2D grand strategy game (like Hearts of Iron from Paradox but as I said only 2D game) and I would like to render the area names on the map. I made the Polygons for each area. How can I render a String inside that polygon?

Here is the image from my game (I put some area names onto the image to show what I would like to achieve):  Here is the code where the polygon is being made (please check it because this is the first time I use polygons):

```
private Polygon pol;

    public Polygon polygon(Map m) {
        if (pol == null) {
            float[] vertices = new float[border().size * 2]; // the border() method returns a collection of 2D vectors/points which are the borders.
            for (int i = 0; i < vertices.length; i += 2) {
                Vector2 v = border().get(i / 2);
                vertices[i] = v.x;
                vertices[i + 1] = m.height - v.y - 1; // m.height is the map's height which is 2160; I convert here the coords (not sure if it is neceseray, the top left corner is the 0,0 coord in the map)
            }
            pol = new Polygon(vertices);
            pol.setPosition(0, 0);
            pol.setOrigin(0, 0);
        }
        return pol;
    }

```

How I checked if the area is on the screen:

```
private Vector3 ivm = new Vector3();
    public boolean isVisible(Camera cam) {
        for (Vector2 vec : points) {
            ivm.set(vec, 0);
            if (cam.frustum.pointInFrustum(ivm)) {
                return true;
            }
        }
        return false;
    }

```

# Answer
> 1 votes
I suggest.

Find right text size for your world. For example you can dynamically create font:

```
public static BitmapFont getFontInWorldUnits(float size, float worldHeght) {
   FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/simpleprintbold.ttf"));
   FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
   int calcSize = (int)(size/worldHeght * Gdx.graphics.getHeight());
   parameter.size = calcSize>72?72:calcSize;
   parameter.color = Color.WHITE; parameter.borderWidth = 2; parameter.borderStraight = true;
   parameter.characters ="0123456789LHAASDGGMATEJ CAPHEIW:.F,-+";
   parameter.minFilter = Texture.TextureFilter.Linear; parameter.magFilter = Texture.TextureFilter.Linear;
   BitmapFont tmp = generator.generateFont(parameter);
   tmp.getData().markupEnabled = true;
   tmp.getData().setScale((float)calcSize/tmp.getCapHeight());
   generator.dispose(); // avoid memory leaks, important
   return tmp;
}

```

Calculate "semi-center" for each polygon shape (find max, min for X, Y axis and then calculate center X ((maxX-minX)/2f), same for Y axis). Yes this is not exactly what you are asking for, but in most cases simple solutions are good enough. If this would produce too many mistakes, you can upgrade it later. Than, draw your text on calculated position (center text):

```
   //Vector3 inWordCoordinate = new Vector3(x ,y, 0);
   //Vector3 inScreeCoordinates = boardCam.project(inWordCoordinate);
   GlyphLayout layout = new GlyphLayout(font, text); //this line is needed to get text box
   //font.setColor(color);
   font.draw(game.batch, layout , inScreeCoordinates.x-layout.width/2, inScreeCoordinates.y+layout.height/2); //draw text

```

Possible improvements:

* When you calculate polygon "semi center" move it in y direction to be sure that it is in polygon (try not to do it in game loop). For this you can scan y-ax from top to bottom use Polygons contains(x,y) method. From max/min you can calculate new center.
* You can have different font sizes, based on polygon size (distance between polygon max, min values) you select font that fits best.
* If area is upright (height\>width) rotate text for 90 degrees or calculate even more precise angle, ...

Also there are other options (most likely not in your case). For example, if you have fix areas, write text/labels in some paint program directly on map, than make textures for each area (make some util program too automate it)...

---
Tags: java, libgdx, mathematics, rendering, text
---


# Question
Title: Why do I get compile errors in every project, even new ones, and how do I fix them?
I downloaded the latest version of Unity as you can see in the snap.

I just created a new project and when I press the play button it shows compile error even if I have not created anything nor any script. I receive 4 blank errors in Unity and one non critical. I am not able to clear them except the non critical one.

# Answer
This is usually caused by importing packages by unity. You can found **Package** inside **project inspector**.

this may be a little different for your project but solution to this is really simple, Open up package manager from **Windows-\>Package manager**. And remove the **"unity** **collaborate"** package if it didn't resolved the problem then remove the **"Text mesh** **pro"**. this sort of problem is usually caused by these two packages. If the problem is not yet resolved them remove all the packages except **"Package Manager UI"**. this resolve all the errors. **If you need any of the package then you have to reinstall it.**

I hope this will help.
> 1 votes

# Answer
This may sound simple, but have you restarted Unity? It could also be a package import issue. Especially with an empty project, try opening the Package Manager and reset to defaults.
> 0 votes

---
Tags: unity
---


# Question
Title: Libgdx: converting between two camera coordinates
I had a similar issue to the question here: Why is my text is too large even when scaled to .05f in libGDX?

So I created a second camera for my text elements. I'm rendering the text above some other elements, and under others, so I was trying to map between the two camera's coordinates when rendering.

That seems to be working OK, but I need to invert the `y` coordinate during the transformation. I'm wondering why that's the case?

Here's the code:

```
    // Setup camera
    OrthographicCamera camera = new OrthographicCamera(VIEWPORT_UNITS, VIEWPORT_UNITS * (height / width));
    camera.position.set(camera.viewportWidth / 2f, camera.viewportHeight / 2f, 0);

    // Setup text camera
    FitViewport fitViewport = new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    fitViewport.apply(true);
    gameContext.setHudViewport(fitViewport);
    OrthographicCamera textCamera = fitViewport.getCamera();

    // ... later, during render(), convert between coordinates
    Vector3 textPosition = new Vector3(fontX, fontY, 0);
    camera.project(textPosition);
    textPosition.y = Gdx.graphics.getHeight() - textPosition.y; // why?
    textCamera.unproject(textPosition);

    font.draw(spriteBatch, text, textPosition.x, textPosition.y);

```

# Answer
> 1 votes
Touch coordinates have the origin(0,0) at the top-left, screen coordinates have it at the bottom-left. Bottom-left is the normal origin in Maths / OpenGL, top-left is how android reports it's screen touches. There's not really a good reason as to "Why", it's just how things were originally coded by the Android/Libgdx devs.

OrthographicCamera has a few methods with a yDown boolean parameter which lets you flip it, but since you're using a Viewport that won't work.

---
Tags: libgdx, camera, coordinates, text
---


# Question
Title: How to run DOTween tweens in succession?
I have a function in my Unity game which marks a given cell GameObject as a valid cell for next move by changing the texture on it. I wanted to spice things up a bit by adding some tweens to the changing cells so I decided to use a simple tween in DOTween - I wanted to rotate the cell 360 degrees in-place while changing the texture when it's facing away from the player (so that the texture doesn't suddenly pop to a different one when it's visible). So I did something like that:

```
public void markAsLegal()
{
    centerPivot.DOLocalRotate(new Vector3(180, 0, 0), .5f, RotateMode.WorldAxisAdd);
    this.GetComponent<Renderer>().material.mainTexture = Resources.Load("textures/legal_hex") as Texture2D;
    centerPivot.DOLocalRotate(new Vector3(180, 0, 0), .5f, RotateMode.WorldAxisAdd);
    isLegal = true;
}

```

This, however, doesn't seem to wait for one rotate before starting the next one and so the cells end up in some weird middle ground, slanted. How can I make DOTween/Unity know that I want these commands to be executed in progression, ie. 180 degree rotation ends -\> change texture -\> finish the remaining 180 degrees?

# Answer
Thats because you are not waiting for the first tween to complete.

first you have to wait for fist tween to complete then on completion of first tween you have change texture and start second tween and by the end of the second tween make "isLegal = true;" so to achieve this you have to do this:

```
private void markAsLegal()
    {
        centerPivot.DOLocalRotate(new Vector3(180, 0, 0), .5f, RotateMode.WorldAxisAdd).OnComplete(ChangeTexture);
    }

    private void ChangeTexture()
    {
        this.GetComponent<Renderer>().material.mainTexture = Resources.Load("textures/legal_hex") as Texture2D;
        centerPivot.DOLocalRotate(new Vector3(360, 0, 0), .5f, RotateMode.WorldAxisAdd).OnComplete(EndRotation);
    }

    private void EndRotation()
    {
        isLegal = true;
    }

```

So what i did here First i started a tween to do the first half of the rotation and on the completion of the first tween i call "ChangeTexture()" to change the textures and start second to tween to complete the rotation and when second tween completed i call the "EndRotation()" to do this "isLegal = true;".

I hope this will help.
> 1 votes

---
Tags: unity, tweening, dotween
---


title: Websocket server thread per connection

text:
# Question
Title: Websocket server thread per connection
I'm creating an html5 multiplayer game and am looking at how to create a websocket server.

I've been looking at various libraries and one thing I noticed is that each one will create a new thread for every client that connects. Now I'm fairly new to websockets, but I know that in the past when it came to game server design that a thread per connection was bad practice.

Is that true for websockets? Why is there a need to a new thread for every connection?

# Answer
> 1 votes
For game servers, yes this is a little less than ideal. There's nothing magical about WebSockets that make using them different than other similar protocols.

Most libraries implementing WebSockets are not designed for games. Threads are deemed the easiest way to implement these things by some Web programmers, driving mostly off of the unfortunate design of Java (which uses a separate thread for practically everything up until NIO was released, and that didn't take off the way one would have hoped). C# also sadly stuck by this design. Some Web programming environments also don't support multiplexing connections in a single thread due to their integration with external Web servers (the popular Apache having also been a one-thread-per-active-connection model in the past).

For a small side project I've been toying with I found the Tornado server (Python) to be the easiest to get high performance WebSockets (no threads). There are absolutely WebSocket implementations in most other languages that don't require threads, but most of them are either difficult to use, mostly unknown third-party libraries, or out-dated/buggy. If you're looking for such a library for your language of choice, you should ask on the main forums or mailing lists for that language; surely someone there would be able to give you links to usable libraries.

# Answer
> 0 votes
You could use Akka to manage all the concurrency and thread management for you. Or you could use the Play Framework that already builds on Akka and that supports WebSocket quite nicely. With Play you can choose between Java and Scala on the server side.

# Answer
> 0 votes
JS is a single-thread by design. You can't implement multithreading at all.

The only thing I can recommend is to use

Basically it's just a wrapper for classic `ws` package, but also allow to specify a messaging protocol to get rid of parsing JSON.

---
Tags: networking, performance, server, multithreading, websocket
---


# Question
Title: Game not accepted in Google Play even though it's built in 64 bit (Unity)
I tried building my game according to the google play rules, but I get the following error message: "This release is not compliant with the Google Play 64-bit requirement

The following APKs or App Bundles are available to 64-bit devices, but they only have 32-bit native code: 1.

Include 64-bit and 32-bit native code in your app. Use the Android App Bundle publishing format to automatically ensure that each device architecture receives only the native code that it needs. This avoids increasing the overall size of your app."

According to the documentation (https://developer.android.com/distribute/best-practices/develop/64-bit) for Unity I should get a working version when I do:

1. Set Scripting Backend to IL2CPP
2. Select the \**Target Architecture \> ARM64 checkbox
3. Build as normal

I've built the game both as APK and as AAB, but neither are accepted. I am using Unity 2018.3.14f1.

I have downloaded this NDK: https://dl.google.com/android/repository/android-ndk-r16b-windows-x86\_64.zip and put the content to: C:\Users\MyName\AppData\Local\Android

# Answer
> 1 votes
Unchecked x86 from "Target architecture" and then make AAB for "ARM 64" and "ARM7" upload it to google play.

Some one on stack overflow answered it and he mentioned it due to x86 google play was not accepting the AAB. I am sorry i don't have link to that question.

Let me know if it worked.

---
Tags: unity, google-play
---


# Question
Title: Graphic render speed in libgdx using many sprite sheets
I am currently working on a customizable Player-character for my top down view 2D pixel game. I am using libgdx and aiming for android devices as well as desktop applications.

I am wondering about an efficient, but yet simple concept. So far my character is build up from different parts ( Feet, Body, Shoulder L, Shoulder R, Hand L, Hand R, Head, Haircut). Every part has its on layer, thus they are 8 layers already. My animations (for example walk cycle) has 8 frames. My character fits on a 24 x 48 px image, thus the naked walking character sprite sheet, with all body parts having their own image and keyframe ends up in having 8 layers x 8 images (24x48 px) = 64 frames.

This fills up 40% of a 512 x 512 sprite sheet. This is only for the walking down animation, weapons would be rendered from a separate sprite sheet, underneath the hands. So for the other 3 directions ( okay maybe they fit here), but certainly for other states (dying, hitting, casting spells) I would need separate character sheets.

Now my questions:

Since my character is customizable, it could end up that every layer has to be taken from a different sprite sheet ( naked head, metal armor, poor gloves, icy shoes etc) thus I would need to switch my textures a lot since they can't possibly fit on one sheet. Sometimes I have to use a sheet again later like: render body and so on naked, bind sword sheet, render weapon, use body parts sheet again and render hands on top.

Questions:

1. In an old book by Mario Zechner I read that sprite sheets with a size of 512 x 512 px are good to go for, since older devices still support this size. Is this still up to date or can I go for bigger Textures (which I then split in TextureRegion Arrays to use for the Animations).

2. Currently I tested using one sprite sheet (the one above) and took 7 TextureRegion Arrays to store the images of all body parts, then I created 7 Animations, which I render all on top of each other in the corresponding order.

Is it good to do so? Should I rather combine all the textures in a pre rendered TextureRegion (or so) and use this in ONE animation instance?

What are the expensive calls? Are they hidden in the use of the many animation instances? Is it the use of many TextureRegion instances?

As far as I can see I only use the texture ( sprite sheet ) in the beginning anyways to then split it up in my TextureRegion Arrays, which are then used in the render method. So does it even make any difference if I would be using different textures which I'd split up at the beginning? Would this splitting-up and preparing take much time if done during the gameplay? Currently I set it up in the create method. How much / many TextureRegions can be stored in memory simultaniously (since if all sprite sheets fit into memory I could preload them like this during the splash screen). Do I even need to worry about this with my low Pixel Resolution Assets? How to get a feeling for this?

# Answer
Atlas/texture size 2048x2048 is safe. (https://answers.unity.com/questions/563094/mobile-max-texture-size.html). You can even check it on the fly and select correct atlas, or even generate atlas based on current hardware.

```
private static int getMaxTextureSize () {
  IntBuffer buffer = BufferUtils.newIntBuffer(16);
  Gdx.gl.glGetIntegerv(GL20.GL_MAX_TEXTURE_SIZE, buffer);
  return buffer.get(0);
}

```

To optimize your idea, try different settings and count total render calls in draw method. At start of draw method set batch.totalRenderCalls=0 and at the end log/view it. Lower better.

If you need more optimization, create atlas dynamically, based on needed textures. Also don't do premature optimization ;)
> 1 votes

---
Tags: opengl, libgdx, android, rendering, gpu
---


# Question
Title: How does the stateTimer parameter is initialized in this method getKeyFrame(stateTimer)?
I have been following the tutorial https://www.youtube.com/watch?v=1fJrhgc0RRw&list=PLZm85UZQLd2SXQzsF-a0-pPF6IWDDdrXt&index=11

I an not able to understand what is stateTimer in getframe method and how is that initialized?

# Answer
It would be easier if you give us link with video timestamp:

https://youtu.be/1fJrhgc0RRw?list=PLZm85UZQLd2SXQzsF-a0-pPF6IWDDdrXt&t=620

"stateTimer" is float variable that, you need to reset (=0) it every time you start new type of animation (new state). When variable stateTimer is 0, current animation will start with first frame. Timer is increased by delta time and after defined duration between two frames method getKeyFrame will return next frame etc...

In short stateTimer is current animation timer. Org. code (this is called ones per render call):

```
    //if the current state is the same as the previous state increase the state timer.
    //otherwise the state has changed and we need to reset timer.
    stateTimer = currentState == previousState ? stateTimer + dt : 0;

```

Code is from example: https://github.com/BrentAureli/SuperMario/blob/dc48dcb6d5b25e8b3c22908df23a5328f13868f9/core/src/com/brentaureli/mariobros/Sprites/Mario.java
> 0 votes

---
Tags: libgdx, animation
---


title: Fixed vs Fixed Collision on ImpactJS

text:
# Question
Title: Fixed vs Fixed Collision on ImpactJS
I'm trying to implement a collision on ImpactJS entities that both will be stopped when collided and being pushed.

This will be exactly similar to player to player collision on top down games such as Battle City where you can't push the other player and vice versa.

All collision type combination does not seem to work on this case. It still pushes the other and FIXED vs FIXED is being ignored.

# Answer
This solution is only a workaround and not what I'm exactly looking for but close. It still pushes the player 1 pixel back if the entity collides with player.

Player = PASSIVE, Entities = FIXED
> 0 votes

---
Tags: javascript, impactjs
---