# Question
Title: How to rotate multi-tile structure on grid?
I need to be able to place structures in my game that **span multiple tiles and can also be rotated**. My idea on how to solve this would be to use 2D arrays that hold data about the structure.

EXAMPLE: (simplified)

Crafting table layout: `XOX`

`X` \- data `O` \- data, but also used as a pivot point

If we were to rotate it clockwise, it'd look like this:

```
X
O
X

```

My problem lies in that these positions have to be real-world coordinates, so here's the above example again but in a way that makes sense for my actual grid in-game. (replacing the X and O with coords):

```
(0,1)(1,1)(2,1)

```

And now, rotated clockwise (around the pivot point, which is `(1,1)`):

```
(1,2)
(1,1)
(1,0)

```

Another example purely for more information, but more complex (2x3 array):

Complex workstation (**(6,4) IS THE PIVOT!**):

```
(5,5)(6,5)(7,5)
(5,4)(6,4)(7,4)

```

Rotate it counterclockwise and we should get this:

```
(5,5)(6,5)
(5,4)(6,4)
(5,3)(6,3)

```

I have tried and succeeded in doing it only on a conceptual level with the "X" and "O"s, but I don't know how to implement actual coordinates.

I've never dealt with rotation matrices before so any advice, suggestion or solution on how to implement this is appreciated.

# Answer
You can rotate a 2D point \\$\vec p\\$ around a center coordinate \\$\vec c\\$ by treating it as though it had a third dimension with a value of one, and multiplying it by a special matrix:

$$\begin{align}\begin{bmatrix}p\_x^\prime\\p\_y^\prime \end{bmatrix} &= \begin{bmatrix}a & -b & c\_x -ac\_x +bc\_y\\b & a & c\_y - bc\_x - ac\_y\end{bmatrix}\begin{bmatrix}p\_x\\p\_y\\1\end{bmatrix}\\ &=\begin{bmatrix}ap\_x - bp\_y +c\_x -ac\_x -bc\_y\\bp\_x + ap\_y + c\_y - bc\_x - ac\_y\end{bmatrix}\end{align}$$

where \\$a = \cos \theta\\$ and \\$b = \sin \theta\\$ given your counter-clockwise rotation angle \\$\theta\\$. In your case, for 90-degree rotations, these will only ever be -1, 0, or 1.

$$\begin{align} 0°&: \begin{bmatrix}1 & 0 & 0\\0 & 1 & 0\end{bmatrix} & 90°&: \begin{bmatrix}0 & -1 & c\_x + c\_y\\1 & 0 & c\_y - c\_x\end{bmatrix}\\ 180°&: \begin{bmatrix}-1 & 0 & 2c\_x\\0 & -1 & 2c\_y\end{bmatrix}\quad &270°&: \begin{bmatrix}0 & 1 & c\_x - c\_y\\\-1 & 0 & c\_y + c\_x\end{bmatrix} \end{align}$$

You can verify that multiplying any of these matrices by \\$\vec c = \begin{bmatrix}c\_x\\c\_y\\1\end{bmatrix}\\$ just yields \\$\begin{bmatrix}c\_x\\c\_y\end{bmatrix}\\$ again, so the center point stays fixed for all of these transformations.
> 1 votes

---
Tags: unity, 2d, mathematics, matrix, grid
---


# Question
Title: How can I add these bones to my meta human? Or is there a way I can make virtual bones count when retargetting?
Paid for animations thinking they would be fine and they mostly are but... the hands are using these IK bones that I do not have. Is there a way I can add the bones to my meta skeleton within unreal? I tried creating virtual bones but they dont seem to come up in the retarget manager :( Also, I can only seem to add one virtual bone to the root whereas both the foot and hand IK root bones are parented to the root bone here.

Any help would be massively appreciated!

# Answer
> 0 votes
I guess you need to open the skeleton in Blender (or other studio) to fix this. There are some tutorials about that.

---
Tags: unreal-4, unreal, skeletal-animation, rigging, bones
---


# Question
Title: How to extend GameMaker Studio's IDE editor, like in Unity?
Unity allows you to create custom inspectors, custom editor windows and custom property drawers.

Is there a counterpart of this in GameMaker Studio 2.x or isn't it possible yet?

# Answer
It's been a while since this was asked, but hopefully, this can be helpful to anyone learning.

In Gamemaker you cannot currently do this, at least not in the way where a window is integrated within a tab or window in the engine itself. However, the way one would go about doing this in a practical sense within GM look to the Room Editor. In short, to make extra development tools you make them within the executable itself in an "editor" room. So once executed the room is its own sub-engine space where you can have custom object-makers and room-builders that optimize certain things and overall fits your taste/needs.

To harvest this data from the executable one needs to keep in mind exporting to specific Gamemaker file types and the like. This part may be a little tricky, but once figured out you basically have everything one needs to have functioning extra tools with whatever UI you'd like. Just remember to maybe not include the "maker" files in the actual game exe when you're done.
> 0 votes

---
Tags: game-maker, editors
---


# Question
Title: Why the mouse doesn't move in mouse-look feature of RPG/FPS games?
## Description

The mouse look (or free look, i.e., move the mouse to change the view/camera) is common in RPG and FPS games. In my cloud game project, I tried to achieve this feature. Before programming, I tested an RPG game (Genshin) in Windows, I started it directly in my PC and used spy++ to check what happened when I moved the mouse. I got these results:

It seemed that however I moved the mouse, although the role's view changed, the positions in WM\_MOUSEMOVE messages didn't change too much. Actually, 640 and 343 were about the half of the resolution sizes (1280\*720).

## Question

How those games achieve this: move the mouse and change the role's view, but the positions in messages don't change? What bottom winapis are used? (I hooked `ClipCursor` and the input parameters of ClipCursor were just my screen's width and height.) In cloud games, I need to use remote mice (clients' inputs) to achieve this feature, what can I do?

# Answer
> How those games achieve this: move the mouse and change the role's view, but the positions in messages don't change?

See the `WM_SETCURSOR` messages immediately following the `WM_MOUSEMOVE` ones? That's how!

They will always reset the mouse cursor to the center of the viewport, i.e. `SetCursorPos(iViewportWidth / 2, iViewportHeight / 2)`.

In your case that would be `SetCursorPos(640,360)` \- c.f. SetCursorPos

The next time you move the mouse Windows sends the new cursor position in a `WM_MOUSEMOVE` message, like `(628, 363)` \- and the program then calculates `(628 - 640, 363 - 360)`, which is `(-12,3)` and is the *relative* mouse movement (in respect of the last value). So it will then calculate the new camera view of looking more to the left (because `x = -12` is negative) and a little bit further down (`y = +3`). It then immediately resets the cursor position to the center via `SetCursorPos(640,360)` and the process repeats.

This way the mouse cursor will never reach the window borders and be clipped by Windows - which would lead to strange effects.
> 2 votes

---
Tags: c++, rpg, windows, first-person-shooter
---


# Question
Title: Checking Scriptable Object equality without references
A rather simple question, how do you check equality of a scriptable object without references?

For example, I have a weapon class that holds a list of damage types the weapon deals, which consists of a float and a ScriptableObject class (Element).

```
[System.Serializable]
public class DamageInfo
{
    public float damage;
    public Element damageType;

    public DamageInfo(float damage, Element damageType)
    {
        this.damage = damage;
        this.damageType = damageType;
    }
}

```

Elsewhere in my code on the weapon I have my DoDamage function.

```
private IEnumerator DoDamage(WeaponAttack attack, Health otherHealth, Vector3 position)
{
    OnHitObject?.Invoke(this, otherHealth.gameObject, position);
    foreach (var damageInfo in Damage)
    {
        //if(damageInfo == Fire) etc

        yield return new WaitForSeconds(0.1f);
    }
    yield break;
}

```

What I would like to do is check what type of Element damage I am currently iterating in order to apply different modifiers, I know this can be done through setting up editor references and comparing against them, but that would require far too much editor setup each time and seems to me using a simple enum while less flexible would be less work overall(even to change in future).

Even setting all the references one time on a globally accessible class, removes the modularity/easy extensibility of using ScriptableObjects in the first place.

Is there any better way I can check for equality without having to use editor set references? Seems to me to be a huge downside of ScriptableObjects.

Thanks

# Answer
> 5 votes
One of the advantages of defining your elements/damage types/etc. in data as `ScriptableObject`s is that you can add/remove/update the collection of elements with pure data changes — no new code, refactoring, or re-compilation required. You might even be able to ship new elements in bonus content packs or mods.

But by checking for specific elements explicitly inside your `DoDamage()` function, you lose those benefits. Now even if you can add a new element purely with data, you still need code changes to imbue it with its special characteristics.

There are a few ways we can respond to this:

1. Accept that new elements will always require new code anyway, and hard-code the set of elements into an enumeration that's easy to check against.
2. Invert the dependency, so instead of `DoDamage()` handling the special characteristics for each element, that behaviour instead lives in the element data, and `DoDamage()` can ask the element to apply its special effects on its behalf, without needing to know which element is which.
3. Create an abstraction, where `DoDamage()` doesn't need to know about specific elements, just common *categories* of damage response.

---

**Option 1** is the simplest. Create an `enum` that lists your elements...

```
public enum ElementType {
    Normal,
    Fire,
    Ice,
    // etc...
}

```

Then your `Element` class can expose its type as a read-only member you can set in the Inspector:

```
[field:SerializeField]
public ElementType elementType {get; private set;}

```

And `DoDamage()` can use a switch statement to split out different behaviours for each type, without comparing them against a cached reference:

```
foreach (var damageInfo in Damage)
{
    switch (damageInfo.damageType.elementType) {
         case ElementType.Fire:
            // TODO...
            break;
    }
}

```

This assumes you're still using your `Element` `ScriptableObject`s to hold other properties - like say localized text, icons, colours, effects to use for the element. If they're just an empty object used as an ID, then you can remove them and completely replace them with the `ElementType` `enum` instead.

---

**Option 2** can take different forms depending on your needs. The common thread is that we've removed the handling of element-specific effects from the `Weapon` class and pushed them into the `Element` class or something it references. The weapon's `DoDamage()` method might then look like...

```
foreach (var damageInfo in Damage)
{
    damageInfo.damageType.OnDoDamage(attack, otherHealth, position);
}

```

Nice and tidy, and never needs to change as we edit our collection of elements. How we implement this on the element side can be a bit more varied...

Maybe you have only a few specific kinds of special effect you might want to mix and match. You could code those behaviours into your `Element` class along with some member variables to enable/disable or tune them. Something like...

```
public void OnDoDamage(WeaponAttack attack, Health otherHealth, Vector3 position) {
    if (_statusEffect != null) {
        _statusEffect.ApplyTo(otherHealth.gameObject);
    }

    if (_damageOverTime > 0f) {
        otherHealth.ApplyDamageOverTime(_damageOverTime);
    }

    // ...
}

```

Or maybe you want more bespoke behaviour for some elements, without turning all elements into a giant mess of optional effect toggles and parameters with tons of conditional checks in your combat code. You could make `OnDoDamage` virtual, and then make subclasses of `Element` that override it with just the behaviour you need for each subtype.

That doesn't need to mean a new code file for every new element. I implemented a system like this recently and found a lot of elements I wanted to use shared similar behaviours, so I could often stamp out a handful of different elements from a single derived type. And although this does mean we're still changing code to add new elements, those code changes are localized to the new element's class itself, not spread like tendrils through the weapon or other scripts that use elements.

If you need even more flexibility, you could create an abstract class that represents one "building block" of an effect to apply on damage, then derive that to make building blocks that spawn prefabs or change stats or manipulate AI, etc... Then each element `ScriptableObject` can have a `[SerializeReference]` collection of these building blocks assigned to it, letting you build up complex behaviour purely through data. Its `OnDoDamage()` method then iterates that collection, invoking each building block as it goes.

---

**Option 3** is a bit of a hybrid, useful if you want a large and flexible collection of elements, but have a relatively controlled vocabulary of what elements are allowed to do.

For instance, we could create a flags enumeration that lets us tag an element with various different properties it should have...

```
[System.Flags]
public enum ElementEffect {
    None        = 0,
    Loud        = 1 << 0,
    Bright      = 1 << 1,
    Ignite      = 1 << 2,
    Paralyze    = 1 << 3,
    // etc...
}

```

Then expose such a set of tags on the `Element` `ScriptableObject`.

Your `DoDamage` method can then check, for each damage type, does it have any relevant behaviours to trigger. Something like...

```
foreach (var damageInfo in Damage)
{
    if ((damageInfo.damageType.effects & ElementEffect.Loud) != ElementEffect.None) {
        // TODO: Alert nearby agents with hearing.
    }

    if ((damageInfo.damageType.effects & ElementEffect.Ignite) != ElementEffect.None) {
        if (otherHealth.IsFlammable) {
            // TODO: Set target on fire.
        }
    }

    // Etc.
}

```

Here, the weapon code processing these behaviours doesn't need to know whether the flammable target is being ignited by a "Fire" element or an "Explosion" element or by a "Lightning" element - as long as they use the common stimulus `ElementEffect.Ignite` then we trigger the corresponding behaviour. And we can add new elements that share this behaviour without modifying the weapon code. (Though of course, we still need to write new code when we want to introduce a *new* behaviour).

---
Tags: unity
---


# Question
Title: How can I change the objects speed movement at run time but only once each time?
The is a bit long but I separated the relevant parts at the bottom of the question.

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

public class Waypoints : MonoBehaviour
{
    [Header("Objects To Move")]
    public Transform objectToMovePrefab;
    public int numberOfObjectsToMove = 1;

    [Header("Speed")]
    public float speed;
    public bool randomSpeed = false;
    public float minRandomSpeed = 1;
    public float maxRandomSpeed = 100;
    private bool changeSpeedOnce = false;

    [Header("Rotation")]
    public Quaternion rotationTothinkWhatToDoHere;

    [Header("Waypoints")]
    [SerializeField] private List<Transform> waypoints;
    public bool moveOnWaypoints = false;

    [Header("Delay")]
    public bool useDelay = false;
    public float delay = 3;
    public bool randomDelay = false;
    public float minRandomDelay = 0.3f;
    public float maxRandomDelay = 5;

    [Header("LineRenderer")]
    public LineRenderer lineRenderer;
    public bool moveOnLineRenderer = false;
    public List<Vector3> lineRendererPositions = new List<Vector3>();

    [Header("Cinemachine Cameras")]
    public CinemachineVirtualCamera virtualCamera;

    private List<WaypointsFollower> waypointsFollowers = new List<WaypointsFollower>();

    private void Start()
    {
        for (int i = 0; i < numberOfObjectsToMove; i++)
        {
            var parent = GameObject.Find("Moving Object Parent");
            var objectToMove = Instantiate(objectToMovePrefab, parent.transform);
            objectToMove.name = "Platfrom";

            waypointsFollowers.Add(objectToMove.GetComponent<WaypointsFollower>());
        }

        virtualCamera.Follow = waypointsFollowers[0].gameObject.transform;
        virtualCamera.LookAt = waypointsFollowers[0].gameObject.transform;

        WaypointsMovementStates();

        SpeedUpdater();

        if (useDelay)
            StartCoroutine(SendObjectstomoveWithDelay());
    }

    private void Update()
    {
        if (moveOnLineRenderer)
        {
            lineRendererPositions.Clear();

            if (moveOnWaypoints)
            {
                foreach (Transform wp in waypoints)
                {
                    lineRendererPositions.Add(wp.position);
                }
            }

            lineRendererPositions.AddRange(GetLinePointsInWorldSpace());
        }

        SpeedUpdater();
    }

    IEnumerator SendObjectstomoveWithDelay()
    {
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomDelay)
                {
                    delay = Random.Range(minRandomDelay, maxRandomDelay);
                }

                yield return new WaitForSeconds(delay);

                follower.go = true;
            }
        }
    }

    private void SpeedUpdater()
    {
        if (changeSpeedOnce == false)
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomSpeed)
                {
                    follower.speed = Random.Range(minRandomSpeed, maxRandomSpeed);
                }
                else
                {
                    follower.speed = speed;
                }
            }

            changeSpeedOnce = true;
        }
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        var positions = new Vector3[lineRenderer.positionCount];
        //Get the positions which are shown in the inspector
        lineRenderer.GetPositions(positions);

        //the points returned are in world space
        return positions;
    }

    private void WaypointsMovementStates()
    {
        // If moving on both linerenderer positions and waypoints objects
        if (moveOnLineRenderer && moveOnWaypoints && waypoints.Count > 0)
        {
            if (useDelay == false)
            {
                foreach (WaypointsFollower wpf in waypointsFollowers)
                {
                    wpf.go = true;
                }
            }
        }

        // If moving on linerenderer positions only without moving on waypoints objects
        if (moveOnLineRenderer && moveOnWaypoints == false)
        {
            if (waypoints.Count > 0)
                waypoints.Clear();

            if (useDelay == false)
            {
                foreach (WaypointsFollower wpf in waypointsFollowers)
                {
                    wpf.go = true;
                }
            }
        }

        // If only to move on waypoints objects without moving on linerenderer positions
        if (moveOnWaypoints && waypoints.Count > 0 && moveOnLineRenderer == false)
        {
            lineRendererPositions.Clear();

            foreach (Transform wp in waypoints)
            {
                lineRendererPositions.Add(wp.position);
            }

            if (useDelay == false)
            {
                foreach (WaypointsFollower wpf in waypointsFollowers)
                {
                    wpf.go = true;
                }
            }
        }
    }
}

```

The method SpeedUpdater I call it in the Update :

```
private void SpeedUpdater()
    {
        if (changeSpeedOnce == false)
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomSpeed)
                {
                    follower.speed = Random.Range(minRandomSpeed, maxRandomSpeed);
                }
                else
                {
                    follower.speed = speed;
                }
            }

            changeSpeedOnce = true;
        }
    }

```

and I'm using helper flag bool name changeSpeedOnce. If the randomSpeed is true I want it to give each moving object a random speed once the problem is if I want to change the flag randomSpeed at run time for example if at run time I change the randomSpeed to false then make all the objects move in the same speed and if I set it to true again in the run time give each one again a random speed value but only once.

If I don't use the helper flag changeSpeedOnce and set the randomSpeed to true it will stutter because it will give each moving object a new random speed value every frame.

# Answer
In your case only use *Update()* for 2 things:

1. To check if way point already is reached;
2. If not yet, move gameobject small incremental distance;

Other parameters of gameobject, - ,such as speed, should be stored in easy accessible manner and its value set *only when you require*, NOT every frame in *Update()*. This is how I move units in my RTS game.

This would be simplified example of code:

```
public bool isMoving;
public Vector3 nextPoint;
public float speed;

private Vector3 dir = new Vector3();
void FixedUpdate()
{
    if (isMoving)
    {
        if (Vector3.Distance(transform.position, nextPoint) < 0.5f)   //are we there yet?
        {
            isMoving = false;

        }
        else
        {
            dir = (nextPoint - transform.position).normalized;  // direction of movement (also could be moved outside Update() function in most cases)
            transform.Translate(dir * speed);  // move a little bit!
        }

    }

}

```

Note: *dir* here is directional vector pointing from current position of gameobject to position of *nextPoint*.

*speed* here defines how far object is moved every frame. Basically speed of object. Can be set from everywhere.
> 1 votes

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


# Question
Title: How can I make all the objects to move between the waypoints?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementSpeedController : MonoBehaviour
{
    public List<Transform> objectsToMove = new List<Transform>();
    public List<Vector3> positions = new List<Vector3>();
    public int amountOfPositions = 30;
    public int minRandRange, maxRandRange;
    public bool randomPositions = false;
    public bool generateNewPositions = false;
    public float duration = 5f;
    public bool pingPong = false;

    private void Start()
    {
        if (generateNewPositions || (positions.Count == 0 && amountOfPositions > 0))
            GeneratePositions();

        StartCoroutine(MoveBetweenPositions(duration));
    }

    private void GeneratePositions()
    {
        for (int i = 0; i < amountOfPositions; i++)
        {
            if (randomPositions)
            {
                var randPosX = UnityEngine.Random.Range(minRandRange, maxRandRange);
                var randPosY = UnityEngine.Random.Range(minRandRange, maxRandRange);
                var randPosZ = UnityEngine.Random.Range(minRandRange, maxRandRange);
                positions.Add(new Vector3(randPosX, randPosY, randPosZ));
            }
            else
            {
                positions.Add(new Vector3(i, i, i));
            }
        }
    }

    IEnumerator MoveBetweenPositions(float duration)
    {
        for (int i = 0; i < positions.Count; i++)
        {
            float time = 0;
            Vector3 startPosition = objectsToMove[0].position;

            while (time < duration)
            {
                objectsToMove[0].position = Vector3.Lerp(startPosition, positions[i], time / duration);
                time += Time.deltaTime;
                yield return null;
            }

            objectsToMove[0].position = positions[i];
        }
    }
}

```

Now only the first object in `objectsToMove` is moving between the waypoints but I need all of the elements of `objectsToMove` to move between the waypoints. If I try this:

```
objectsToMove[i].position = Vector3.Lerp(startPosition, positions[i], time / duration);

```

I will let out of bound index exception because the size of `objectsToMove` is not the same the size of `positions[i]`

# Answer
In my opinion best thing to do is:

To make one movement script and to attach it to *each* object, so that each object can run its own movement script **separately**. Then just fire moving command to each object, and pass them a path where you store all waypoints. It could look something like this:

```
 myGameObject.GetComponent<theMovingScript>().TakePathAndGoNow(positions);

```

Because now you are trying to iterate through waypoints, and also iterate through gameObjects, and things get messy quick.

Think of your game objects as , well .. separate objects and let each run its own logic. In Unity you can write one script and attach it to many objects - and now your objects can have their own speeds, go to different paths etc, even it is really only one script file.

In short: let Unity do the heavy work for you.
> 2 votes

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


title: Get on what tile has mouse clicked

text:
# Question
Title: Get on what tile has mouse clicked
I am writing a chess game using Java and Swing, And I wanted to get the tile position on which a mouse clicked. I searched through internet, but all of them were really off, and never accurate. When I clicked on a tile's first half, it said it was tile 1, but on the second half, it said it was tile 2, but it was still tile 1. So I was wondering, how can I do it?

My tile size is (75, 75) This is the code I've written for tileX: `Math.floor((double)evt.getX() / 75)`, and this is the code I've written for tileY: `Math.floor((double)evt.getY() / 75)`.

Code for drawing:

```
ImageIcon l_winter = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/winter/light.gif");
        ImageIcon d_winter = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/winter/dark.gif");
        ImageIcon l_wood = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/wood/light.png");
        ImageIcon d_wood = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/wood/dark.png");
        String theme = th;
        int color = 0;
        for (int i = 0; i < 600; i = i + 75) {
            for (int j = 0; j < 600; j = j + 75) {
                JLabel panel = new JLabel();
                panel.setText(null);
                panel.setSize(75, 75);
                if (color == 0) {
                    if (theme.equals("wood")) {
                        panel.setIcon(l_wood);
                    } else if (theme.equals("winter")) {
                        panel.setIcon(l_winter);
                    } else {
                        panel.setText("notexture");
                    }
                    //panel.setBackground(new Color(white[0], white[1], white[2]));
                    color = 1;
                } else {
                    if (theme.equals("wood")) {
                        panel.setIcon(d_wood);
                    } else if (theme.equals("winter")) {
                        panel.setIcon(d_winter);
                    } else {
                        panel.setText("notexture");
                    }
                    //panel.setBackground(new Color(black[0], black[1], black[2]));
                    color = 0;
                }
                panel.setLocation(j, i);
                getContentPane().add(panel);
            }
        if (color == 0) {
            color = 1;
        } else {
               color = 0;
            }
        }

```

# Answer
The most likely reason for your problem is that the 0:0 position of your content pane you attach your tiles to and the 0:0 position of the object you've attached your mouse listener to (that code seems missing from the question) do not line up. As DMGregory pointed out, adding the offset factor to the mouse positions should do the trick.

But there is a better solution for your problem.

Each of your chess tiles is a separate JLabel (which you confusingly call "panels", which is a different thing in swing). JLabels can have mouse listeners themselves. Those listeners will only fire for events which happen within that label. That means you can assign individual mouse listeners to each label instead of just one mouse listener for everything. That way you can leave the calculation which label was clicked to the Swing framework.

First, create a mouse listener class which takes information about the tile its supposed to handle in its constructor:

```
public class TileMouseListener implements MouseListener {
    private int x;
    private int y;

    public TileMouseListener(int x, int y) {
        this.x = x;
        this.y = y;
    }

    mouseClicked(MouseEvent e) {
        System.out.println("Click on " + x + ":" + y);
    }
    /* ...implementation of the other mouse listener methods... */
}

```

Then assign a new instance of that mouse listener to every JLabel you want to be able to react on mouse events happening to it.

```
panel.addMouseListener(new TileMouseListener(i, j));

```
> 0 votes

---
Tags: java, mouse, swing, chess
---


# Question
Title: Unity higher Z position tiles rendered underneath
When placing tiles in an isometric tile-map in Unity, I try to place blocks on top using the "Z Position Value" However it looks like higher Z position values get rendered underneath.

In this picture, the green cubes have a z position of 0 whereas the yellow cubes have a z position of 1. I want the yellow cubes to render on top, but they are underneath. I'm using an Isometric Z as Y tile-map and have the Transparency Sort Axis set to (x=0,y=1,z=-0.26).

# Answer
> 3 votes
Ok I'm going to edit my non-answer for I have just discovered how to fix this !

If you're using URP as I suspect you may be, go to your 2D renderer pipeline file (Renderer 2D Data) and edit the Transparency Sort Mode to Custom Axis and Transparency Sort Axis to (0, 1, \[Y dimension of the grid * -0.5\] - 0.01).

That will hopefully fix it for you as it did for me.

For EONS I've tried to find those options that were in Project Settings -\> Graphics for non-URP projects and remembered that it might just be in the files I had created at the very beginning of my project setup.

---
Tags: unity, rendering, tilemap, isometric
---


title: Quaternion.AngleAxis smallest value?

text:
# Question
Title: Quaternion.AngleAxis smallest value?
If I'm using an angle with a value of somewhat below 0.1 degrees in Quaternion.AngleAxis, the quaternion will not apply a rotation at all. Why is this?

# Answer
If you slowly decrement the angle bit by bit and print the resulting quaternion in round-trip precision, you'll notice that eventually the w component rounds to 1. This corresponds to the identity quaternion, ie. "no rotation".

The formula for the w component is \\$\cos \frac \theta 2\\$ where your angle is \\$\theta\\$. So we can use that to find the angle where this would have to round to 1 when stored in a 32-bit float.

We have 23 bits of mantissa, which means we need the result to be within \\$2^{-24}\\$ of 1 to round up. That means at or above \\$\frac {16777215} {16777216} \approx 0.999999940395355\\$.

We can find the critical angle at which that happens as...

$$\theta^\* = 2 \cos^{-1} \left( \frac {16777215} {16777216} \right) \approx 0.039564682° $$

So, angles of rotation less than about 0.04 degrees just aren't accurately representable with single-precision floating point.

(Unity actually gets a bit further than this - not rounding to 1 until we're down to 0.02797646°. That may have to do with how it normalizes the quaternion)

Fortunately, for any object less than 2896 pixels in diameter, a rotation at this angle or less amounts to less than a pixel of difference in a rendered image, and so it gets rounded out by our rasterization or antialiasing anyway, so in practice this isn't really the limiting factor in the precision to which we can express orientation in a rendered game frame.
> 2 votes

---
Tags: unity, quaternion
---


# Question
Title: How many choices for attacks should a player be given?
If you remember the old Fallout 1 + 2 games, there you could select where to shoot/hit the enemy. But of all the choices, only chest or head made sense. Chest to maximize hit probability or, if a hit was almost certain, head for maximum damage. But one could also choose limbs etc.

In other games you can often attack with a standard attack or a variety of special attacks. Most of the time only one or two of them make sense.

I, as a programmer, always analyse a game for best strategy and "bang for the buck" so i naturally don't want to implement useless or silly choices in a game. But if i break it down to what really matters, i could write a bot that plays most games for me as many games are that simple.

Let's assume it is NOT possible to have several choices of equal value. How many choices should i present to a player with one or two being effective and several others being "duds" ?!

If i exaggerate this issue then you could make Fallout 1 a game where you move your character and click an enemy and thats it, best hit location is determined by the game as it mostly is obvious. But that removes the "i have options" feeling, i assume.

I am really somewhat lost with this.

# Answer
> 12 votes
The core idea I teach my students is that choices in a game should be **contingent** and **situational**.

That is, there should be situations in which you would choose one option and situations in which you would choose another. This leverages the player's skill, judgement, and intuition in discerning which of these situations they're in.

You give an example of this with head vs body shots.

* "My hit chances are low, I'd better aim conservatively to minimize the risk of missing" --\> aim for body
* "My hit chances are high, I'm not at much risk of missing and can prioritize damage" --\> aim for head

Here, the exact threshold between "low" and "high" hit chance, or how much risk of missing the player is willing to take, are subjective and situational. Different players will come to different conclusions in different situations, depending on their aggression or risk tolerance or details of the scenario.

Maybe the enemy is on its last legs and so damage isn't so important as just landing a hit to end the fight. Maybe *you're* on your last legs and if you don't get a headshot now it's over, so it's an all-or-nothing gamble. Maybe you're concerned about running out of ammo, maybe you're more concerned about draining your healing item supply. Each of these different elements add layers to the decision, and opportunities for players to choose to prioritize one or another.

Together, these considerations keep the player's mind and subjectivity engaged in the decision, so it doesn't just collapse to a calculation.

Another important aspect of contingency is beliefs / predictions about your opponent's strategy, or unseen information like what's around the next corner. Even if your opponent is an AI, knowing that they have, say, a 20% chance to do a berserk charge when reduced to 10% health will impact players' decisions about when to prioritize damage or reliability or other effects like disarming/stunning/immobilizing/knocking back.

You can take pretty much every system in your game and brainstorm actions where it would be a positive or negative factor. Got a loot system? Maybe some actions can boost your loot drops or increase the chance of rare items, so I'll play differently when farming/grinding for a specific drop. Got a reputation/morality system? Maybe some combat choices are more honourable than others, so I'll play differently depending on the character I'm roleplaying or the factions I'm trying to befriend.

Each time you weigh adding a new combat option, the question to ask yourself is "in what situations should a player choose this over the options I already have?" *and* "in what situations should a player choose another option over this one?"

If you have strong answers to both questions, that's a sign the choice will create interesting decisions for your player. Particularly if sorting between those situations demands considering lots of factors (like my health, its health, engagement distance, amount of ammo, healing item supply, distance from a safe location, chance of backup, etc...) that can test their observation, quick thinking, tactical judgement, resource management, priorities, and intuition.

If there's only a few situations where it pays to choose one thing or its alternatives, or those situations are obvious (lacking the subjective assessment of high/low and risk of the example above), then it's likely to collapse to a calculation instead of challenging your players.

There's a good Extra Credits video on this topic too.

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


title: 2D moving objects in angle

text:
# Question
Title: 2D moving objects in angle
Im making simple 2D space shooter with use of html5 and JavaScript.

The idea is simple, shoot down as many aliens as you can.

I made it to the point where I have player which can move and rotate, but I want the player to move in the angle, like 80s Asteroids (you set angle then press forward key and ship goes forward in that angle)

my movement now is simple:

```
up = y -= speed * delta time
down y += speed * delta time
left x -= speed * delta time
right x += speed * delta time

```

my rotation is made like this:

```
ctx.save();
ctx.translate(this.x + this.w / 2, this.y + this.h / 2);
ctx.rotate(this.angle);
Draw.Rect(ctx,this.w /2 * (-1),this.h / 2 * (-1),this.w,this.h,"red",1);//context,x,y,w,h,color,opacity
ctx.restore();

```

angle:

```
if(keys.e)this.angle += 0.1;
if(keys.q)this.angle -= 0.1;

```

# Answer
**The Simple Approach: Sin and Cos**

It looks like you're close. If you want to keep it simple, and assuming positive y is up and 90 degrees means go straight up and 0 degrees means go straight to the right, something as simple as **y += speed * sin(angle), x += speed * cos(angle)** should work.
> 1 votes

---
Tags: javascript, html
---


# Question
Title: Creating a Full Stadium of People, Ready as a Game Asset (ie. not too CPU intensive)
I am trying to make a boxing scene in my game. I decided to attempt to make the large stadium first (It's a boxing management game, so the scene can be 'pre-rendered' perhaps, the fight events (eg. Big hits, blocks, dodges) are going to be calculated based upon the boxers skill values and some luck etc.

I have this scene in Maya:

My first idea was to 'scatter' assorted people into the crowd. But on further advice it seems this might be too resource-heavy.

I am very keen to learn such things as LOD, or effects to make it look like the crowd is full of people. Also smoke etc effect to cover empty areas (or allow for much reduced detail) would be amazing.

A little bit broad question I realise, but I'm looking for some starting points of what to learn to achieve this stuff.

Many thanks

# Answer
In answer to one of your comments:

> I actually have the same question, but regarding the seats in the stadium. Would it be better to make them in maya (all of them) or is it better to import just one chair mesh to Unity and place them procedurally?

There is extra performance overhead for multiple GameObjects; for example, it's faster to render one mesh containing 100 chairs than to render a single chair mesh 100 times. You can reduce overhead by doing manual instanced rendering using `Graphics.DrawMeshInstanced()` but that is done with code and can be an extra headache to set up. I'd suggest grouping multiple chairs into one mesh.

*However*, you should **not** put all of the chairs in the entire arena into a single mesh, as this prevents frustum culling from working. *Frustum culling* refers to skipping render of objects that are not inside the camera's boundaries. If all of the chairs are in a single mesh that wraps all the way around the arena, that means that at least some of the chairs will be visible to the camera no matter what direction the camera is pointed, preventing frustum culling. I once worked on a racing game for mobile where the artist had made the barrier around the entire track as a single 200k poly mesh. This ended up causing major performance issues because the engine could never cull any part of the barrier, so we eventually had to break the barrier into segments.

I would suggest grouping chairs into sections, and making each section a single mesh. This way you have less overhead than if each chair was its own object, but frustum culling will still work for sections of chairs that are not in front of the camera.

EDIT: As DMGregory noted in a comment, in the likely event that the chairs are completely stationary, you can also use static batching to have Unity automatically combine multiple instances of a mesh into a single mesh. So for example, if you imported a mesh containing 1 chair and added 500 copies of that chair to the scene, using static batching you could let Unity combine multiple chairs into a single mesh. I do not know offhand how this would work with frustum culling.
> 1 votes

---
Tags: unity, 3d, maya, level-of-detail
---


# Question
Title: Where should I handle player movements in a Java Game?
I had an old pure Java 2D top-down game that I'm trying to reformat a bit. Before, I had a bit of a messy game loop that didn't use delta timing for any movements or animations. Now, I'm trying to implement this delta timing.

I implemented delta timing into the game loop with two framerates (60FPS and 30FPS) to test it, but I noticed that the movement created with the 30FPS was half of what was obtained using the 60FPS.

When I moved the player, I did something like:

```
posX += Game.deltaTime * SPEED;

```

and this didn't work well because the delta time was the same for both the 30FPS and 60FPS.

So, I did some calculations... I run into some problems if I use change the player's position from the update() method, because it runs at a constant 60UPS.

Here are my calculations

```

int deltaXPerSecond = Game.deltaTime() * SPEED * 60;

// To get the delta X over a second, I multiplied deltaX by 60 (UPS)
// with 30FPS, it was 9.9, with 200FPS it was 1.5

// Game Loop

private static final double UPDATES_PER_SECOND = 1.0 / 60.0;

@Override
        public void run() {

            /*
             * Note: This game loop uses Majoolwip's game loop.
             * https://www.youtube.com/watch?v=4iPEjFUZNsw&list=PL7dwpoQd3a8j6C9p5LqHzYFSkii6iWPZF
             */

            double firstTime = 0;
            // converts to seconds because System.nanoTime is extremely accurate.
            double lastTime = System.nanoTime() / 1000000000.0;
            double passedTime = 0;
            double unprocessedTime = 0;

            double frameTime = 0;
            int frames = 0;
            int fps = 0;

            boolean render = false;

            // Continuously repeats this loop until the game is stopped.
            while (running) {
                render = false;
                firstTime = System.nanoTime() / 1000000000.0; // converts to seconds.

                // Gets how many milliseconds have passed between now and the last time.
                passedTime = firstTime - lastTime;
                deltaTime = (float) passedTime;
                lastTime = firstTime;
                unprocessedTime += passedTime;
                frameTime += passedTime;

                while (unprocessedTime >= UPDATES_PER_SECOND) {
                    unprocessedTime -= UPDATES_PER_SECOND;
                    // Sets render to true. This makes the game render only when it updates
                    render = true;

                    // Updates the game
                    if (frameTime >= 1.0) {
                        frameTime = 0;
                        fps = frames;
                        frames = 0;
                        System.out.println("FPS: " + fps);
                    }
                    update();
                }

                if (render) {
                    frames++;
                    render();
                }
                else {

                    /*
                     * If the game doesn't need to render or update,
                     * the GameLoop thread sleeps for 1 millisecond,
                     * causing a decrease in CPU usage.
                     */

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

```

What am I doing wrong? Shouldn't these numbers be approximately the same regardless of the frame rate? Do I need to change the game loop? Please let me know what I am missing.

# Answer
Your player's movement, a crate falling off a cliff, and all physics-related simulations are basically (discrete) integrals computed over time. An object's **position** represents its displacement in a reference system; **velocity** is the rate of position change over time; **acceleration** is the rate of velocity change over time... We compute all these values by integrating at each update using very simple formulas like Euler's method.

If we want the output to be the same for any given input on any machine, we need to integrate over the same time interval at each loop. Therefore, we use a **fixed timestep** for our calculations; this value depends only on the number of *updates per second* we want. We also *decouple* logic and rendering, so we can deal with them separately: the renderer *produces* time, and the integrator *consumes* it in fixed-size chunks.

If your player behaves differently at different refresh rates, then your game loop still depends on the rendering rate, but we don't want this to happen. A game loop like this:

```
// ABSOLUTELY UNTESTED CODE
double t = 0.0;
final double dt = 1.0 / 60.0;  // game updates per second

double currentTime = System.nanoTime();
double accumulator = 0.0;

while (!quit) {
    double newTime = System.nanoTime();
    double frameTime = newTime - currentTime;
    currentTime = newTime;

    accumulator += frameTime / 1000000000.0;  // convert to seconds

    while (accumulator >= dt) {
        update();
        accumulator -= dt;
        t += dt;
    }

    render();
}

```

would call `update()` only if enough time has passed to make `accumulator` have at least one `dt` chunk. Additionally, if your application freezes this gets recorded during the next computation of `frameTime`: the inner loop will be executed multiple times until `accumulator` becomes smaller than `dt` once again.

Please note that `dt` is a fixed delta time, related to the game logic only. You can use it to move your objects around in their own `update()` function:

```
x += SPEED * dt;

```

This code is being executed as fast as possible, assuming that render operations are actually limited by the hardware. If you want to artificially limit the number of times `render()` is called, you can:

* Couple it to the UPS rate with the same flag trick in your sample code;
* Duplicate all variables to manage game loop and render loop separately (I actually see no reason to force a game run at 53 FPS though).

Glenn Fiedler wrote some articles about integration and timestep I absolutely loved, which helped me to improve my understanding of game engines and be aware of when certain instructions are to be called when programming a game. The full game physics series is available here, I hope you'll appreciate the reading too.
> 1 votes

---
Tags: java, game-loop, deltatime
---


# Question
Title: Can you show rng code running in real time in a game?
First off, I know almost nothing about game development/rng but I will learn. So apologies for sounding uninformed.

I want to make a sandbox ios game with several activities to do within, one of which is poker, but I want the poker to be infallibly transparent unlike online poker. They wouldn't dare.

So I want to show the rng code to be viewable by players as the hand plays out, so players will know its legit, and can verify after the hand etc if they have concerns, is this possible, can you "show" rng?

# Answer
Yes, you can. There are already online platforms that are doing exactly that, by providing you the hash of the online secret key that is used as the seed for the random generation. Same seed = same random result. Now when the hand/ game is over, you can reveal the original secret. Players can verify by hashing it themselves and compare it to the previous provided hash. There is no problem to give the algorithm away how to create a hand as long as the seed stays secret.

The seed just has to be long enough that people can't brute force it in the time others are playing the game.
> 14 votes

# Answer
See mental poker. That article describes a problem that's a bit harder than the one that you outline, as you are asking merely how to prove to the players that you gave them the "right" cards. For that problem, you can simply post a hash of the deck before the game, then post the deck afterwards. The players can then check that the deck hashes to the correct value.

If the players are really paranoid, however, they may worry that you're in cahoots with one of the players and telling them what cards the other players are getting. They also may worry that the deck isn't being chosen randomly, and merely posting the seed doesn't solve that, as that just raises the question of how the seed is chosen. The above article discusses how it's possible to eliminate even those possibilities.
> 3 votes

---
Tags: architecture, ios, random, poker
---


# Question
Title: Identify when Unity Button Enters Pressed State
I am trying to create a UI Button Prefab with a text child element that I would like to use all over my application. Its intended behavior is very simple:

* Its size would be dependent on the text's width (this has been achieved using content size fitter and a horizontal layout group).
* Its states would be done using sprite swap (this had also been done partly)

The problem is that the pressed state uses an image on which the button is visually pressed (its top moves downward a few pixels). This is a nice effect and the image works great, however, I cannot make the text move in synchrony with the image to sell the downward movement.

My way of thinking was to use an initial padding of 4 at the bottom in the horizontal layout group (to move the text upward) then change it to 2 when the button enters a pressed state. Something like this:

```
using UnityEngine.UI;

public class ButtonController : MonoBehaviour {
    public Button buttonComponent;
    public HorizontalLayoutGroup buttonLayout;

    // Update is called once per frame
    void Update() {
        RectOffset tempPadding = new RectOffset(
        buttonLayout.padding.left,
        buttonLayout.padding.right,
        buttonLayout.padding.top,
        buttonLayout.padding.bottom);

       if (buttonComponent.isPressed) { //This does not work OFC!
        tempPadding.bottom = 2;
       } else {
           tempPadding.bottom = 4;
       }

       buttonLayout.padding = tempPadding;
    }
}

```

The problem is that I cannot seem to identify when the button enters said pressed state, which seem like a simple enough problem yet I cannot find an answer to it. I've looked all over the internet but couldn't find anything useful.

# Answer
The Guys over at the Unity3D sub-Reddit had come up with a good solution, using the even handler. I have not come up with this answer, and I don't want to take credit for it, but there is no one else to post it here; so, I have to:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ButtonController : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public HorizontalLayoutGroup buttonLayout;

public void OnPointerDown (PointerEventData pointerEventData)
{
    RectOffset tempPadding = new RectOffset(
        buttonLayout.padding.left,
        buttonLayout.padding.right,
        buttonLayout.padding.top,
        buttonLayout.padding.bottom);

    tempPadding.bottom = 0;
    buttonLayout.padding = tempPadding;
}

public void OnPointerUp(PointerEventData pointerEventData)
{
    RectOffset tempPadding = new RectOffset(
     buttonLayout.padding.left,
     buttonLayout.padding.right,
     buttonLayout.padding.top,
     buttonLayout.padding.bottom);

    tempPadding.bottom = 4;
    buttonLayout.padding = tempPadding;
}
}

```
> 0 votes

---
Tags: unity, 2d, sprites, unity-ui
---


title: perspective camera with libgdx

text:
# Question
Title: perspective camera with libgdx
I am trying to setup a viewport using perspective camera. I am trying to render a scene like this I read an official blog post about the cameras and found a few tests within gdx test suits. However, I am still kinda confused. I have no idea how to manipulate the test suits nor i have any idea what the code does other than just following the code given in the test.

I have a couple of sub-questions,

* was the game in the screenshot rendered with perspective camera or just the grids?
* Is it possible to work with Orthographic and Perspective Camera at the same time? so that i can render different elements with different camera?
* Is there any detailed and easy to understand guide that explain perspective camera really well? I find libgdx severely lack of documentation regrading these.

# Answer
> was the game in the screenshot rendered with perspective camera or just the grids?

I think it's 2D. Just because of there're no true 3D objects.

> Is it possible to work with Orthographic and Perspective Camera at the same time?

Yes, it is possible. Example and explanation.

> Is there any detailed and easy to understand guide that explain perspective camera really well?

Very good tutorial about cameras in libgdx: here

More links about mixing 2D and 3D
> 0 votes

# Answer
I found this link to a blog by Mario Zechner on the Camera classes:

https://web.archive.org/web/20200427232345/https://www.badlogicgames.com/wordpress/?p=1550
> 0 votes

---
Tags: camera, libgdx, perspective
---


# Question
Title: How can I create the arriving/ engaging in combat movement like in StarCraft 2?
I currently have two armies (smaller scale) crashing into each other. They will usually form a line of units fighting. I have no idea how to handle a unit coming from behind the line to properly go around its allies to reach the enemies. Like in this position, where a new unit approaching from the green army needs to navigate around the battle front to reach the red enemies:

StarCraft 2 handles this beautifully, as seen here:

I've read that SC2 uses steering for local avoidance and A\* and some other methods to plan out the paths. Which all is perfectly clear, but I haven't found anywhere any details on engaging the enemy.

This is what I have, it's been a month and I still haven't solved this specific issue.

How is it possible to do continuous checks of possible destinations before engaging the enemy, wouldn't it be too costly? To clarify, in the video of the Zerglings vs Zealots, they first engage each other and form a line, all the other units that come after them will go around the line, but, if space opens in the line they will immediately go towards it. This kind of arrival behaviour is briefly explained in their GDC talk, they have a cone of vision in which they do checks. The only ideas I had was

1. Have a cone of vectors (in the direction of Velocity) and do checks for each vector to see if it could provide a favorable position to move to

issue: Cannot figure out the math to create offsetted (by an angle) vectors, but it seems like a pretty decent solution
2. Have a spatial query in a rectangle to where the unit is moving

issue: How do I check for an empty space? I can get all entities in that rectangle but how can I check for empty places and score them (how favorable are they)? Are they even reachable, I'd still need some kind of raycast like with the first option

I have circlular collision shapes, seperation and goal following in place. I somewhat have introduced a goal system that should further spread the units, but as it stands I still lack the arrival behaviour described in the GDC talk.

# Answer
Your main diagram illustrates the lowest green unit not knowing which way to go. When I initially came to this problem I found standard avoidance would make the unit yo-yo between friendly units. So, instead I force the unit to pick a direction to move around friendlies and stick to that avoidance direction. This could lead to the unit moving the slower way round to the right in your example image but that's probably not something that matters much in an RTS. It doesn't have to be perfect - just not *too* stupid.

> Which all is perfectly clear, but I haven't found anywhere any details on engaging the enemy.

Steering can be used when engaging the enemy in the same way. But the steering rules do get quite a bit more complex.

> How is it possible to do continuous checks of possible destinations before engaging the enemy, wouldn't it be too costly?

If you store the unit positions in some sort of spatial partitioning data structure then finding out which units are at a particular area isn't too costly.

I've written a little more & put some diagrams on the spatial partitioning & boids avoidance behaviours similar to SC2 here: boids avoidance for surrounding groups

With accompanying youtube vid here which demonstrates tweaking the behaviours to get the desired effect: video of advanced boid avoidance & surrounding

I stress that verbose visual debugging of steering forces becomes essential (as they mentioned in the SC2 talk) if you want to get complex interactions working and understand what's going on. You can see I took the debug visualisations quite far in the video.
> 2 votes

# Answer
The GDC multi-game session AI Navigation: It's Not a Solved Problem - Yet includes an explanation of how Star Craft 2 handles navigation. The SC2 content is presented in the first 20 minutes of the talk. There's a joint question and answer portion at about the 54 minute mark with a number of question pitched to SC2.

While a complete transcript of the material is outside the scope of an answer, here's an overview with some key portions that apply to your question as posted.

The pathing in SC2 occurs in three steps: planning, steering, collision.

### Planning

The planning is done using A\* & funnel algorithms on a constrained Delaunay triangulation. A sparse regular grid is used to locate units within the triangulation. From your post, it sounds like you've focused on grid-based solutions. If you're interested in an SC2 style solution, you should explore a navmesh style model.

The planning step does account for the attack range of the unit, but it does **not** include any mobile units (they are dealt with via steering & collision). Note: mobile units in this context seems to mean any units capable of moving as the can potentially be nudged out of the way (as discussed under collisions). Units only store the next two steps of their pathing plan; the assumption is that by the time a unit gets further than that, things have probably changed enough to require re-planning anyway.

### Steering

Compared to pathing & planning, steering required the most work in SC2. Most of the steering behaviors are based the Boids work pioneered by Criag Reyonlds.

The high level steering behaviors identified are:

* Following
* Flocking
* Grouping
* Separation
* Avoidance
* Arrival

Of these, the avoidance step required many iterations to find a solution that worked well. In the end they settled on the following approach:

* figure out what you can ignore
* plot obstacles
* don't turn if the center path is clear, otherwise aim for the closest gap
* don't path into walls
* check the steering intent of on coming traffic to avoid the "hallway dance"; that is to say: if an oncoming unit has decided to steer to the north to go around you, you shouldn't also steer north as you'll collide with their intended course correction

The arrival step is discussed during the Q&A session. While a group may to collective pathing, each individual unit gets its own destination point. Furthermore, the system never allows two units to path to the same location.

### Collisions

SC2 units are allowed to push other units using a limited physics model. The overall rule set is complex but here are some of the basics:

* conceptually all mobile units are modelled as circles
* idle friendly units get pushed out of the way
* faster units get pushed out of the way more than slower units
* typically opposing units push each other out of the way equally
* units being told to hold a position don't get pushed
* attacking units don't get pushed (mentioned during the Q&A)
* the simulation is limited in the number of "rounds" required to find an outcome

In the animation clip you linked, it looks as if the units that arrive later either don't realize that an allied unit has stopped in front of them or are failing to take appropriate action. Connecting it back to the SC2 presentation, that seems like a problem with either collision detection or avoidance. It's also possible the problem stems from the arrival steering behavior - that is to say, the late units are attempting to move to the location that their engaged ally has stopped at.
> 2 votes

---
Tags: algorithm, movement, path-finding, rts
---


title: Blend tree for triggers?

text:
# Question
Title: Blend tree for triggers?
I have a hero that can aim his gun.

When the user aims down, I play the animation "gun\_aim\_lo". When the user aims up, I play the animation "gun\_aim\_hi".

I do this via a BlendTree.

The "BlendVal" is set by the current mouse position.

```
float f = Input.mousePosition.y / Screen.height;
_animator.SetFloat("BlendVal", f);

```

This works fine.

When the user then presses the fire button, the hero shoots his gun.

I play the gun\_shoot animation using a Triggger like that:

```
_animator.SetTrigger("PistolShootTrigger");

```

However, I have now noticed that I need different gun\_shoot animations, just like for the aiming: I need a gun\_shoot\_hi and a gun\_shoot\_lo animation according to the aiming position, else it would look strange if the user for example aims low and then the shoot-straight-animation is being played.

I would need to be able to blend between them according to where the user aims when he shoots.

Can I combine a BlendTree with a trigger?

I think I can only trigger single animations, and not a blend tree.

Can somebody tell me how my idea could be achieved?

# Answer
> 1 votes
I should not have been so anxious.

I just replace the Pistol Shoot Animation with a Pistol Shoot BlendTree. The Pistol Shoot BlendTree uses "BlendVal" as well, so I don't have to change anything.

It works great.

---
Tags: animation
---


# Question
Title: Find out triangles that are not occluded from a camera view?
For a project i need to find out triangles that are directly seen by the camera / user. Triangles that are occluded by other triangles should be ignored. There may be 200 thousand triangles in a model, so raycasting on a CPU is no possibility due to performance. Is there something build in to unity or opengl that can do this? If not how would you approach this problem? Many 3d editing software use techniques, e. g. to select or slice only triangles that are visible.

# Answer
You could use a rendering pass that writes "triangle IDs" to an offscreen framebuffer instead of rendering colors. Then you can read the pixels from the offscreen framebuffer and get the IDs of all visible triangles. That means you need to extend your vertex data to contain such triangle IDs, create a 32-bit-per-pixel framebuffer, and write a simple fragment shader that only writes the triangle IDs into the framebuffer (and discards color information etc). Depth-testing must of course be enabled.

Note that this solution might miss very small triangles that don't even occupy a single pixel. It also won't work properly with triangle strips (you'll need "3-vertices-per-triangle" vertex buffers instead).
> 1 votes

---
Tags: unity, opengl, occlusion
---


# Question
Title: How do I add custom data to a ListView widget in Unreal?
I have a UserWidget object with a ListView in it.

How do I add objects add and custom data to them, such as names?

# Answer
First read the tooltip info:

To add an item with custom properties, you need the following parts:

* List View
* Data entry object
* Presentation widget

The idea behind this setup is most likely to keep data and presentation separated.

### Data entry object

The data entry object's purpose is only to store data. Create it as a Blueprint class that inherits from Object.

When we add new items to the ListView, we create a new data entry object:

**Important:** To make FruitName visible, that property needs to have the following settings enabled in the data entry object (BP\_Fruit\_Data\_Entry):

### Presentation widget

This is what we tell our ListView that we want to display. We do it here:

**Important**: In order for our Presentation widget (W\_Fruit\_Presentation\_Widget) to be shown here, it needs to:

1. Inherit from **UserWidget**
2. Implement the **User Object List Entry** interface:

### Presenting the data

When you have added a new data entry object to your list, it will automatically create a new presentation widget of the class that you defined.

When it does that, it will call **On List Item Object Set**. This is where you take the data and put make it presentable:

Here's an overview on how it works:

I created an example project a simple setup here: https://github.com/01F0/umg-listview-example
> 2 votes

---
Tags: unreal-4, blueprints
---


# Question
Title: How do I check if animation is of Animation Type "Humanoid"?
One can set the Rig / Animation type of an animation to "Generic", "Humanoid", etc.

How could I check by script if an animation rig has been set to type "Humanoid"?

# Answer
Somebody from Unity answered this question to me:

```
You can check AnimationType in script using Asset Import PostProcessor: https://docs.unity3d.com/ScriptReference/AssetPostprocessor-assetImporter.html

Here is the code showcasing how you would access the AnimationType:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class CustomImportSettings : AssetPostprocessor
{
    void OnPreprocessModel()
    {
        ModelImporter importer = (ModelImporter)assetImporter;
        ModelImporterAnimationType type = importer.animationType;
    }
}

```
> 1 votes

---
Tags: unity, animation
---


# Question
Title: What does Camera.main.WorldToScreenPoint mean?
Is that the same as changing a Canvas in the editor to World Space mode and then drag a Camera ?

# Answer
> 3 votes
This is covered by the documentation:

> **Declaration**
>
> `public Vector3 WorldToScreenPoint(Vector3 position);`
>
> **Description**
>
> Transforms position from world space into screen space.
>
> Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.

So this is a math function that converts a position vector from one coordinate space to another.

You give it the coordinates of a point in your game's world space (like the `transform.position` of an object in your scene), and it returns to you the coordinates of the pixel on the screen where that point would be displayed, given the camera's current view settings.

This has nothing to do with canvas components per se, or what camera they use for their pointer interaction events.

Please be sure to consult the docs first when in doubt — they explain a lot of these basics faster than waiting for an answer here.

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


# Question
Title: What is happening during queue_free() process?
From time to time, I encounter a hard-to-reproduce bug with a similar line of code:

```
## File: Level.gd

func _on_player_invisible() -> void:
    player.queue_free()

```

which sometimes crashes with: *Attempt to call `queue_free` in base `null instance` on a null instance*

---

I have added this null check condition, but the crash can still be observed:

```
## File: Level.gd

func _on_player_invisible() -> void:
    if player: player.queue_free()

```

# Answer
> 4 votes
## Reproducing the error

I managed to reproduce this reliably. It happens when calling `queue_free` on a `Node` that has already been freed (but the reference is not actually null, the error message is misleading).

This code should produce the error:

```
player.queue_free()
yield(get_tree(), "idle_frame")
player.queue_free()

```

For the error to happen, it is necessary and sufficient that a frame happens between both calls of `queue_free`. If multiple calls of `queue_free` happen in the same frame, there is no error. Multiple frames happening between the calls of `queue_free` do not prevent the error.

---

## Observed behaviour

Before calling `queue_free` for the first time, we observe:

```
print(player == null)                  # false
print(!is_instance_valid(player))      # false
print(player.is_queued_for_deletion()) # false

```

After calling `queue_free`, we observe:

```
print(player == null)                  # false
print(!is_instance_valid(player))      # false
print(player.is_queued_for_deletion()) # true

```

After a frame passes (and thus the `Node` has been freed), we observe:

```
print(player == null)                  # false
print(!is_instance_valid(player))      # true
print(player.is_queued_for_deletion()) # ERROR

```

The error is: `"Attempt to call function 'is_queued_for_deletion' in base 'null instance' on a null instance."` (notice that it isn't actually null, instead it has been freed). *As a consequence `is_queued_for_deletion` is not a good filter by itself.*

For reference, if we call `is_queued_for_deletion` on null, we get: `"Invalid call. Nonexistent function 'is_queued_for_deletion' in base 'Nil'."`.

Finally, if we attempt to call `queue_free` again, we get the error you saw: `"Attempt to call function 'queue_free' in base 'null instance' on a null instance."`.

---

**Addendum on Nil vs Null**: One of the possible types a `Variant` can have is `Nil`, which by definition is `null`. This is what you get if you write `null` on GDScript (A `Variant` of type `Nil`). However a "null instance" is not of type `Nil`. Instead you get "null instance" when you have an invalid pointer. Thus, C++ methods which do not return `Variant` but can return an invalid pointer will not give you `Nil` (For example `get_node_or_null`) and if they give you an invalid pointer, and you try to use it you get the "null instance" error. The same error you get with `queue_free` as explained in this answer (after the `Node` is freed, any pointers to it are now invalid).

---

## Preventing the error

Therefore to prevent the error when the code can call `queue_free` multiple times, we want to avoid calling it when a frame has passed since the last call. That is, we want to avoid calling it when `is_instance_valid(...)` is false. In other words, we only call it when `is_instance_valid(...)` is true:

```
if is_instance_valid(player):
    player.queue_free()

```

Note that `is_instance_valid(null)` is also false. So we don't need to check for null.

Thus, checking `is_instance_valid(...)` is both necessary and sufficient to prevent the error. We could check for `is_queued_for_deletion` also to make sure that `queue_free` is only ever called once (although this is not necessary to prevent the error).

---

## How `queue_free` works, looking at the source code

Looking at the source for `queue_free`, the first thing we find is that it actually binds to the method `queue_delete` (source). Which looks like this (source):

```
void SceneTree::queue_delete(Object *p_object) {

    _THREAD_SAFE_METHOD_
    ERR_FAIL_NULL(p_object);
    p_object->_is_queued_for_deletion = true;
    delete_queue.push_back(p_object->get_instance_id());
}

```

*That null check produces a different error (source).*

There you can see where `_is_queued_for_deletion` is set to true, which we check with `is_queued_for_deletion()`.

Note that no check is done on whether or not this is called multiple times.

As per the process that actually frees the Node, it is in `_flush_delete_queue` (source). It consumes the queue, and calls `memdelete` (source).

The method `memdelete` calls the "predelete handler" for the object if it has one, then the destructor and finally releases the memory. It is likely that there is a "predelete handler" as the `Object` class has one (source) that sends the `NOTIFICATION_PREDELETE`. Which the `Node` class handles (source) by setting its `owner` to null, removing itself from its parent, and then removing all the children and calling `memdelete` on them.

Finally, it is the destructor of the `Object` class (source) the one that disconnect signals connect from it, then disconnects the signals connected to it. Then removes the instance from the object database… Which is what `is_instance_valid` checks.

---
Tags: godot, memory, gdscript
---


# Question
Title: Imposters in Unity - How to set which color is used as 'transparent' in the RenderTexture?
I'm still working at making imposters for my Unity scenes. Here I am attempting to make a large block of stadium seating, using the one seat mesh as shown.

I'll try to explain in full what Ive done so far:

1. Imported 3d mesh of seat
2. Created RenderTexture 'seat' (default format R8G8B8A8\_UNORM)
3. Added new Orthographic camera in front of seat. (settings: Clear Flags=Solid Color; TargetTexture='seat'
4. Created some quads and aligned them so I can see the textured side.
5. Gave the quads a new material 'seat'.

I've gone through many of the settings in the Material and other places changed many things here and there such as 'transparent' or 'cutout' and lots of the other settings but cannot get rid of the magenta color in the seating textures I created.

Also tried making that color alpha 0 but it had no effect. And tried various colors as transparent (magenta, white, black).

Am I doing this completely wrong? Hopefully I am just missing some small setting. Ideally somewhere I can just set the magenta color to mean transparent pixels.

Really do need help here honestly have been trying very hard to achieve this alone but not getting anywhere fast.

# Answer
> 1 votes
So the solution turned out to be quite simple. After doing all the steps I mentioned in the question, you will need to make sure the camera that you use to generate the RenderTexture has it's Clear Flags set as 'Solid Color', then that color should be set as white, with Alpha=0.

Then you'll have created a material for your quads, which will take the RenderTexture as the Albedo. I used the Standard Shader and just set the Rendering Mode to 'cutout'.

It now renders the image perfectly without the background being visible.

My next challenge which I am sure I will need help with but will try alone is to figure out a system of choosing which angle of the seat will be displayed on each quad. When there is a stadium full of seats, and the main camera is moving about, there will need to be some way for each quad to decide what texture to display. I am sure to find this a huge challenge.

All the best

---
Tags: unity, 3d, level-of-detail
---


# Question
Title: Move 2D Rotating object in its facing direction
I have a 2D object that constantly moving forward (in the direction its facing). So initially its facing right, and moving right, but as the rotation z-axis changes, so should its direction. Most of what I'm finding is based on the Asteroids game physics, but what I'm doing is not like that (I think), I'm not adding force to the object when I want its direction to change. Basically what I'm trying to do have it's X & Y velocity change based on its z rotation value. Here is an example of something similar to what I'm attempting to do:

Moving object

# Answer
You can compute the direction to move in like this:

```
direction_vector = {.x = cos(facing_angle), .y = sin(facing_angle)};

```

Depending on where exactly you define "zero degrees" to be, you might have to swap sin/cos or make one of them negative.

Wikipedia has a nice animation showing the relationships
> 3 votes

---
Tags: 2d, movement
---


# Question
Title: Animation Clip rotates model in unexpected way
I have 2 animation clips. In the following animation preview, the same model is being used for both clips.

As you can see in the Animation window dopesheet, there is no significant rotation difference. However, one animation clip rotates the model 90 degrees to the left.

I have inspected all the rotation values in the animation tab. I just don't see any difference.

What causes this significant rotation difference?

# Answer
I got it. The rotation was due to a rotation in the "hip" bone (y was -70).

I didn't take a look at that one as it was so much down low in the hierarchy. But being the root of my model, it makes sense.

I zero-ed it out, and now both animations face approximately the same direction.
> 1 votes

---
Tags: unity, animation
---


title: Formula for attack range using hexagons

text:
# Question
Title: Formula for attack range using hexagons
I need a little help with a formula to calculate the attack range for my turn-based strat game. Since it's a hexagon grid, I'm having trouble coming up with a formula that would pick the character range variable and calculate if an enemy object is in range. I'm using Game Maker Studio 2.3. My old script used to check like this:

```
var unity_attack_range = attacker.RNG;

var hex_dist = 90 * unity_attack_range;
with(defender)
{
    if (point_distance(defender.x, defender.y, attacker.x, attacker.y) <= hex_dist)
    {
        //attack code stuff
    }
}

```

As you can see, it multiplies the attacker range variable by 90 (hexagon width/2), and then it would just point the distance between the attacker and, if inside it, then you can attack. However, I noticed it makes a circle-shaped check after the attacker with the current formula, and it will include enemies from outside the supposed range.

The hexagon shape is 180 x 120, and the distance between each hexagon center is 90 in both axis.

I don't think it will be worth entering all positions to check, since for range = 5, it would be necessary 90 positions to check manually. I need ideas on how to make it work with maths, like Civ 6 does. Any ideas? Also, thanks for the attention!

# Answer
You can achieve the desired result (if I interpreted your picture correctly) by replacing your point\_distance function with something like this.

The function determines the number of steps that are required to go from hexagon (x1,y1) to hexagon (x2,y2). This works by first determining the number of diagonal steps (which decrease the X and Y distance simultaneously); then it computes the number of remaining horizontal or vertical steps and adds them to the total.

It expects coordinates to be in unit coordinates, like you marked them on your picture; so you should either use cell grid indices directly, which is preferred, or divide your coordinates by 90.

```
int hexagon_distance(int x1, int y1, int x2, int y2) {
    int x_distance = abs(x1 - x2);
    int y_distance = abs(y1 - y2);

    int diagonal_steps = min(x_distance, y_distance);

    int remaining_x_distance = x_distance - diagonal_steps;
    int remaining_y_distance = y_distance - diagonal_steps;

    if (remaining_x_distance > 0) {
        return (remaining_x_distance / 2) + diagonal_steps;
    } else {
        return remaining_y_distance + diagonal_steps;
    }
}

```
> 1 votes

---
Tags: algorithm, game-mechanics, geometry, hexagonal-grid, game-maker-studio-2
---


# Question
Title: Playerbody is turning, but not moving in direction turned
So, I have a simple WASD script, and I've added a part so when Mouse X is moved, the playerBody (character) rotates in that direction, so, when W is pressed (to go forward) the player does not move in the direction turned, but it moves in the same direction. Although the playerBody has turned, the player still moves in the same direction.... why?

```
using UnityEngine;
using System.Collections;

// This script moves the character controller forward
// and sideways based on the arrow keys.
// It also jumps when pressing space.
// Make sure to attach a character controller to the same game object.
// It is recommended that you make only one call to Move or SimpleMove per frame.

public class Move : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Transform charBody;
    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        float MOUSEY = Input.GetAxis("Mouse Y") * speed * Time.deltaTime;
        float MOUSEX = Input.GetAxis("Mouse X") * speed * Time.deltaTime;

        charBody.Rotate(Vector3.up * MOUSEX);

    }
}

```

Thanks

# Answer
Your `moveDirection` vector is not taking into account the character's orientation because you use world space vectors in the `moveDirection` calculations.
The `new Vector3(MouseX, 0, MouseY)` will always point to the position at `MouseX` units along the world X axis and `MouseY` units along the world Z axis (i.e., relative to the world center point). And the character will move along this world space vector no matter where the character is looking at.
To have the direction that depends on the character's orientation you need to use the character's directional vectors instead of the world space vectors.
So, to move the character `x` units forward you need to use the character's `transform.forward` vector that represents a directional vector that points to the character's 'look' direction.
This vector have magnitude 1 (i.e. the length is 1 unit), so you need to multiply it by your desired `x` value to get a vector that represents a motion from character's current position forward for the `x` units.
Same thing for right/left movement, but here you use `transform.right` vector.

```
moveDirection = transform.forward * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
moveDirection *= speed;

```
> 1 votes

---
Tags: c#, movement
---


# Question
Title: Linear algebra: Are vectors that define a game object considered to be a subspace?
In Linear-algebra a subspace is a collection of vectors that when added with each other or scaling would result in another vector in that same subspace.

How does subspaces relate to objects/players within the game world?

An object (player or enemy) in a game itself is just a collection of vertices that can be defined as a collection of vectors right? Does that mean that each object is also a subspace?

If I scale one object to be large enough to overlap/collide with another object does that mean those two objects are still in their own subspaces?

# Answer
> 2 votes
## Coordinate systems

For CG (computer graphics) we use hierarchical coordinate systems. Coordinate systems often called a space (World, Screen/View, Local space) define an origin, scale and rotation in 2D, 3D, ... nD.

Hierarchy connects the coordinate spaces (generally via transformation matrices)

An object in its local space is transformed to world space (places it in the world) then transformed to screen space (puts it on the screen).

You must select which coordinate space you want a vector to work in. If you have a vector in local space and want to add a vector from view space you must transform one of the vectors to the others space.

Most game frameworks will come with all the utilities needed to manipulate vectors, matrices, and coordinate spaces. However I would strongly suggest that you write your own so you can get a thorough feel of what is going on. If you are comfortable using vectors then it will not be that difficult with a bit of research.

## Question

> *"If I scale one object to be large enough to overlap/collide with another object does that mean those two objects are still in their own subspaces?"*

Yes until you transform them both to world space. They will then be in the same coordinate system. You can then test if they overlap.

---
Tags: linear-algebra
---


# Question
Title: Random Spawning Traffic at Pace Fitting "Frogger"-style Gameplay
In my game level, you have to cross a busy road to buy something and then cross back again. The general gameplay mechanics are now set up and playable. But I wanted to know if this routine I used to randomly spawn the cars can be improved upon.

So far, I simply set the percentage chance of it spawning a car that frame (I have 0.01f for now), and only call the spawnCar() method when my random number 0-1 is less than that chance. Like so:

```
private void Update()
    {
        if (Random.Range(0f, 1f) < 0.01f)
            SpawnCar();

    }

    void SpawnCar()
    {
        Color color = new Color(Random.Range(0,2), Random.Range(0, 2), Random.Range(0, 2), 1);
        if (Random.Range(0, 2) == 0)
        {

            Car car = Instantiate(carPrefab, new Vector3(SPAWN_POSITION_X, 0, Random.Range(1, LANE_WIDTH)), Quaternion.Euler(0, -90, 0));
            car.InitCar(true, Random.Range(8,15), color);

        }
        else
        {
            Car car = Instantiate(carPrefab, new Vector3(-SPAWN_POSITION_X, 0, -Random.Range(1, LANE_WIDTH)), Quaternion.Euler(0, 90, 0));
            car.InitCar(false, Random.Range(8, 15), color);
        }
    }

```

But sometimes there are lots of cars, sometimes not so many. I am wondering if there are better ways, or other factors I can account for when spawning the cars to give a better difficulty curve. (The level is constantly revisited so ideally it will get harder and harder perhaps 10 or so times until it's at 'max difficulty')

# Answer
> 2 votes
First of all, I see a big problem with your code. You are potentially spawining a car each `Update`. That means you are making the spawn frequency dependent on the update frequency, which is tied to the framerate. That means players with more powerful hardware who have a higher framerate will encounter more cars than players with lower framerate.

There are several ways you can fix that problem. You could move your spawning code from `Update` to `FixedUpdate`. Or you could put the spawning code into a Coroutine which uses `yield return WaitForSeconds(seconds);` in order to roll for spawns in regular intervals.

But the solution I would prefer could also be used to solve the problem you actually posted about, namely to prevent clustering and dry-spells: Implement your own timing logic in Update using the `Time` class.

* Have a variable which tracks the time until you spawn the next car
* Have your update-method reduce that variable by `Time.deltatTime` (seconds since the last update).
* When it's below 0, spawn a new car.
* After you spawned a car, roll a random number between two values to determine the time until the next car is going to spawn.

This way you can control precisely how much minimum and maximum time you have between two spawns. The script could look something like that:

```
public float minTimeToNextCar = 1.0f; // change to taste
public float maxTimeToNextCar = 2.0f; // change to taste
private float timeToNextCar;

void Start() {
    // initialize timeToNextCar with a random value so not all cars spawn at once on start
    timeToNextCar = Random.Range(minTimeToNextCar, maxTimeToNextCar);
}

void Update() {
    // reduce the time left until the next car spawn
    timeToNextCar -= Time.deltaTime;
    // check if it is time to instantiate a new car
    if (timeToNextCar <= 0.0f) {
        /* Your code to instantiate a car */
        // roll time until next car spawn
        timeToNextCar += Random.Range(minTimeToNextCar, maxTimeToNextCar);
    }
}

```

You might notice that the two variables which control the spawn frequency are public. That gives you several options to control them externally. You could either create your own difficulty controller script which sets the min and max time of several spawns based on the the elapsed time. Or use a solution I find very elegant: Control those values via curves in a Timeline.

---
Tags: unity, c#, random, spawning
---


# Question
Title: In games physics engines, what is "tunneling", also known as the "bullet through paper problem"?
I have recently had an issue where *sometimes* a collision would not be detected. Someone told me that maybe I had an tunneling issue.

In the context of game development using physics, what is tunneling?

---

This is a low-ball question; I realized when suggesting someone that maybe they had that issue that we did not have a clear explanation around about what the issue was, so this question is meant to help users explain things with fewer words.

# Answer
> 41 votes
## What is tunneling and why it happens

In video games, physic objects will have an specific position which is updated by the physics engine each frame based on its velocity and any forces applied to it.

*Motion depicted with very low frame rate to draw attention to the fact that it is not continuous. Note that although the depiction is 2D, this is not specific to 2D.*

---

When the physics engine computes the new position, it must check for collisions and respond to them. For example, if the new position results in a collision with a wall, the physics engine must compute a collision response (e.g. bouncing) so that the object does not end up stuck in the wall.

*Collision depicted. With same low frame rate as before.*

---

However, if the object is **moving too fast** (or if the frame rate extremely low), the physics engine may compute the new position to be on the other side of the wall. As if the object had, somehow, gone through it. We refer to this as **tunneling** (as if the object had made a *tunnel* under or through the wall and ended at the other side).

*Tunneling depicted. Frame rate is much lower than before.*

---

## Solutions

Solution to the problem include checking for collisions at multiple steps along the motion of the object…

*Multiple checks per frame depicted.*

---

… Or checking against a shape that extends from the old position of the object to its new position. *This is known as a "sweep collision detection", and it is integral part of a "continuous physics simulation".*

*Single shape using to check sweeping motion depicted.*

---

Some other ways to mitigate the problem include:

* Enforcing a maximum speed for objects (e.g. terminal velocity).
* Making thicker walls. *Thick geometry is also good to hide some shadow mapping problems, so these go hand-in-hand.*
* And more physics frames, of course.

*Optimizations are beyond the scope of this answer.*

---
Tags: physics-engine, terminology
---


# Question
Title: OpenGL height map accuracy for planetary rendering
I am trying to implement planetary rendering and I am trying to use OpenGL tessellation to model the terrain. Here is an overview picture using cube faces projected onto a sphere:

If I use the following code for the tessellation evaluation shader, I get a smooth sphere even when rendering a near view.

```
#version 410 core
layout(quads, equal_spacing, ccw) in;
in mediump vec2 texcoord_tes[];
out mediump vec2 texcoord_geo;
uniform mat4 projection;
uniform mat4 transform;
void main()
{
  vec2 c = mix(texcoord_tes[0], texcoord_tes[1], gl_TessCoord.x);
  vec2 d = mix(texcoord_tes[3], texcoord_tes[2], gl_TessCoord.x);
  texcoord_geo = mix(c, d, gl_TessCoord.y);
  vec4 a = mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x);
  vec4 b = mix(gl_in[3].gl_Position, gl_in[2].gl_Position, gl_TessCoord.x);
  vec4 p = mix(a, b, gl_TessCoord.y);
  float s = 1.0 / sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
  gl_Position = projection * transform * vec4(p.xyz * s * 6388000, 1);
}

```

Here is a near view using the computed scaling factor (`float s = 1.0 / sqrt(p.x ...)`):

However if I take the scale factors from a floating-point texture, I can see quantisation artifacts. The scale factors (or heightmap values) are extracted from the texture using `float s = texture(hf, texcoord_geo).r`. The code for the tessellation evaluation shader in this case is as follows:

```
#version 410 core
layout(quads, equal_spacing, ccw) in;
in mediump vec2 texcoord_tes[];
out mediump vec2 texcoord_geo;
uniform sampler2D hf;
uniform mat4 projection;
uniform mat4 transform;
void main()
{
  vec2 c = mix(texcoord_tes[0], texcoord_tes[1], gl_TessCoord.x);
  vec2 d = mix(texcoord_tes[3], texcoord_tes[2], gl_TessCoord.x);
  texcoord_geo = mix(c, d, gl_TessCoord.y);
  float s = texture(hf, texcoord_geo).r;
  vec4 a = mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x);
  vec4 b = mix(gl_in[3].gl_Position, gl_in[2].gl_Position, gl_TessCoord.x);
  vec4 p = mix(a, b, gl_TessCoord.y);
  gl_Position = projection * transform * vec4(p.xyz * s * 6388000, 1);
}

```

In this case the near view looks like this and shows artifacts:

My question is, what am I doing wrong? Or is it normal that OpenGL textures are less accurate than 4-byte floating point numbers? Any help is appreciated.

# Answer
> 0 votes
Thanks everybody for looking into it! I found the solution now. The problem was that I was using `GL11/GL_RGB` for the internal texture format of the heightmap:

```
(GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 GL11/GL_RGB tilesize tilesize 0 tex-format tex-type buffer)

```

Instead I had to use `GL30/GL_R32F` as the internal texture format.

```
(GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 GL30/GL_R32F tilesize tilesize 0 tex-format tex-type buffer)

```

Also see OpenGL documentation for glTexImage2D.

---
Tags: opengl, rendering, graphics, heightmap, planet
---