title: Managing AI state transitions in Unity

text:
# Question
Title: Managing AI state transitions in Unity
I am building a horror game in Unity, and I am trying to make an enemy movement controller. The way it works, is the enemy has two states, made available via an `enum` called `EnemyStates` the possible values are `Chasing` and `Patrolling`. When the enemy spawns it, it defaults to `patrolling`, which when done makes them follow a specific path set by waypoints on the map.

When a gameobject tagged as 'Player' is within chase distance, the enemystate is switched from 'Patrolling' to chasing, and the target is set to the player gameobjects transform. The mob then begins chasing the player.

I am doing all of my checks in the Update() function, which works mostly, but causes problems in this area;

Since it's checking every frame, it's overwritting it's previous state even if it's the same as the last time. When the enemy is patrolling then switches to 'chase' state, it plays a special one-time animation via a SetBool() with an exit time. The problem is that since it's in the Update() function, it's continually trying to call the one-time animation overwritting itself and not doing anything.

I am trying to find the best approach to handle target change etc without relying on Update() to do it, but still making the target update correctly when either 1.) A new player gets closer and the enemy starts chasing them, or 2.) No players are within range, and the enemy goes back to patrolling.

I was thinking, maybe it would be best to put the distance check on the player, and when the player is close enough to the enemy, update the enemies target and enemystate directly ? Then when the player gets out of range of the enemy, it updates the enemies target and enemystate back to patrolling?

Is that the best approach, or is there something else I should be doing? I have attached my current bit of the mobController.cs that I am working with.

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

// Need to redo all of this. The first thing the mob should do after it spawns, is head to the first waypoint. Then check if a player is close by, and if so set them to the target.
// We also need to build this so that if the monster is currently chasing somebody, they first do the 'Howl' animation, proceeded by the chase animation (which should be a run).
// Once the player gets out of distance from the monster, it goes back to the 'patrol' animation (which should be a walk or crawl)

public class mobController : MonoBehaviour
{

    public string mobName;
    public GameObject mobNameObject;
    public TMP_Text mobNameText;
    public float chaseDistance;
    public float deathDistance;

    private NavMeshAgent agent;
    private Animator animatorController;

    private float defaultspeed;
    private int currentWaypoint = 0;

    enum EnemyStates
    {
        Patrolling,
        Chasing
    }

    [SerializeField]
    GameObject target;

    [SerializeField]
    AudioClip chaseMusic;

    [SerializeField]
    Transform[] waypoints;

    [SerializeField]
    EnemyStates currentState;

    // Start is called before the first frame update
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        target = this.gameObject;
        animatorController = GetComponent<Animator>();
        float defaultspeed = agent.speed;
    }

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

        // Loop through every player, see if any are close. If they are, set the mob to chasing. If not, set it to patrolling.
        GameObject[] gos = GameObject.FindGameObjectsWithTag("Player");
        GameObject closest = null;

        Vector3 position = transform.position;

        float localdistance = Vector3.Distance(target.transform.position, transform.position);

        if (localdistance < chaseDistance)
        {
            //Debug.Log("You are being chased!");
        }

        // Loop through all players, see if the mob is near anyone. If so, and it's not the original target, start chasing them instead.
        foreach (GameObject go in gos)
        {
            float distance = Vector3.Distance(go.transform.position, transform.position);

            // This will need updated eventually. Right now, if the player gets above the chase distance, the mob will go back to patrolling.
            // We should probably make this a decision based thing. (Should the mob follow indefinitely, until another target gets closer?

            if (distance < chaseDistance)
            {
                target = go;

                target.GetComponentInChildren<AudioSource>().clip = chaseMusic;
                if (!target.GetComponentInChildren<AudioSource>().isPlaying)
                {
                    target.GetComponentInChildren<AudioSource>().Play();
                }

                // Play the howl animation to start the chase
                if (currentState != EnemyStates.Chasing && target != this.gameObject)
                {
                    animatorController.SetBool("move", false);
                    //animatorController.SetBool("howl", true);
                    StartCoroutine(StopHowl());

                    currentState = EnemyStates.Chasing;
                    animatorController.SetBool("chase", true);

                }
            }
            else
            {
                currentState = EnemyStates.Patrolling;

                if (target != this.gameObject)
                {
                    target.GetComponentInChildren<AudioSource>().Stop();
                }
            }

            // If the monster is close to a target player, do the death sequence.
            if (distance <= deathDistance)
            {
                agent.isStopped = true;
                animatorController.SetBool("move", false);
                animatorController.SetBool("attack", true);
                target.GetComponent<CharacterController>().GameOver();

                // Then reset the target to self until next update
                target = this.gameObject;
                currentState = EnemyStates.Patrolling;
            }
        }

        // If the mob is not chasing anyone, return to waypoint patrolling
        if (Vector3.Distance(transform.position, waypoints[currentWaypoint].position) <= 0.1f)
        {
            Debug.Log("Updating waypoint");
            currentWaypoint++;

            if (currentWaypoint == waypoints.Length)
            {
                currentWaypoint = 0;
            }
        } else
        {
            Debug.Log("Too far away from waypoint");
        }

        if (currentState == EnemyStates.Chasing)
        {
            agent.destination = target.transform.position;
            //agent.speed = defaultspeed + 2;
            animatorController.SetBool("chase", true);
        } else
        {
            agent.destination = waypoints[currentWaypoint].position;
           //agent.speed = defaultspeed;
            animatorController.SetBool("chase", false);
            animatorController.SetBool("move", true);
        }
    }

    IEnumerator StopHowl()
    {
        yield return new WaitForSeconds(1);
        animatorController.SetBool("howl", false);
    }
}

```

# Answer
> 0 votes
About a third of the way into your Update() function, you have this:

```
 // Play the howl animation to start the chase
if (currentState != EnemyStates.Chasing && target != this.gameObject)
{
    animatorController.SetBool("move", false);
    StartCoroutine(StopHowl());
    currentState = EnemyStates.Chasing;
    animatorController.SetBool("chase", true); //<----------
}

```

Later in the `Update()` function you have this, which is called every frame as long as the enemy is in the `Chasing` state:

```
if (currentState == EnemyStates.Chasing)
{
    agent.destination = target.transform.position;
    animatorController.SetBool("chase", true); //Why are we calling this again?
}

```

Notice you call `animatorController.SetBool("chase", true);` in two places, the latter of which is called every frame. Presumably you don't need the second one at all.

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


title: SetFullscreenState not returning

text:
# Question
Title: SetFullscreenState not returning
When I call the `IDXGISwapChain::SetFullscreenState` method, it does not return. The window goes fullscreen, but accepts no further input. A `println!()` put right after never fires. I am assuming there is some sort of deadlock happening behind the scenes, but the docs don't go into what all it locks.

* Does `SetFullscreenState` perform any locking?
* If so, what does it lock?
* What other issues could cause `SetFullscreenState` to never return?

I am using Rust 1.44.1 with `winapi` 0.3.9. I am passing `minwindef::TRUE` and a null pointer as arguments (passing `minwindef::FALSE` returns, but does the opposite of what I want). I am using the following options in the swapchain desc:

```
desc.BufferCount = 1;
desc.BufferDesc.Width = width;
desc.BufferDesc.Height = height;
desc.BufferDesc.Format = dxgiformat::DXGI_FORMAT_R8G8B8A8_UNORM;
desc.BufferDesc.RefreshRate.Numerator = 60;
desc.BufferDesc.RefreshRate.Denominator = 1;
desc.BufferUsage = dxgitype::DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.OutputWindow = *hwnd.inner();
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Flags = dxgi::DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
desc.Windowed = minwindef::TRUE;

```

# Answer
> 1 votes
I figured out the issue.

Before returning, `SetFullscreenState` sends a `WM_MOVE` *then* a `WM_SIZE` to the event loop. I was only paying attention to the `WM_SIZE`, which never got called because my version of `WM_MOVE` blocked.

---
Tags: windows, winapi, fullscreen, rust
---


# Question
Title: How to rotate an object based on the movement and angles of Lifters
I have Lifters that "carry" an object. I want the object to move and rotate based on how those Lifters move. Requirements include:

* Supporting 1-4 Lifters at any side of the Object (e.g., both on one side, opposite, so on - can't make any guarantees about their positions relative to the object)
* Supporting any orientation of the Object (e.g. the Object could be flipped on its side, sideways, or upside down; can't make guarantees that Forward is always facing forward, etc)

As such I implemented this by having the object move by setting its velocity to the average of the Lifters' velocity.

Now, if not all of them move (or if there's a disparity in their velocities), I want the object to rotate, like so:

This is done by keeping track of how much an individual lifter has moved in a frame from the Object's position, and calculating the angle via

```
m_Angle += Vector3.SignedAngle(lastPos - transform.position, currentPos - transform.position).

```

This "movement angle" I add up for every Lifter and then at the end, Rotate the Object via `Transform.Rotate(Vector3.up, m_Angle)`.

However, this approach has some problems:

1. Calculations are done along the Y axis and therefore does not angle the Object up or down if the Lifters have different vertical positions,
2. `m_Angle` actually overshoots, but I found simply dividing `m_Angle` by the `number of Lifters` made it perfectly accurate. I do not know why this works.

Because I want this to rotate the object in "3 dimensions", I have attempted to calculate the "euler angles" of each Lifters' movement via:

```
Vector3 oldDisplacement = lastPos - transform.position;
Vector3 newDisplacement = currentPos - transform.position;
Quaternion rotation = Quaternion.FromToRotation(oldDisplacement, newDisplacement);
m_EulerAngles += rotation.eulerAngles;

```

And then at the end, I rotate the Object based on these "movement angles":

```
transform.Rotate(m_EulerAngles, Space.World);

```

This works in three dimensions, however it is off in the same way that `m_Angle` was before I divided it. It rotates the object too far. On top of that it seems to produce rotations along axes that have no displacement.

I want the object to only rotate exactly by the angle created by the Lifter's movement. This should keep it "synced" to Blue instead of rotating past as you see here.

When I check how much rotation Blue is adding per frame, I get an output like so:

```
Blue is adding (0.000, 359.507, 0.066); on movement (-0.015, 0.000, 0.000)

```

Despite moving solely on the x-axis, there is a z-euler angle being created, and the y-euler angle of 0.493 degrees is too much for -0.015f movement. I do not know why `rotation.eulerAngles` is inaccurate in my usage.

The only issue I can perceive is that since the Object's position is also moved at the end, the angle calculation assumes it is not moving and generates a larger angle (e.g., perhaps `newDisplacement` should be something like `currentPos - (transform.position - m_Body.velocity * Time.deltaTime)` ). However, removing the Object's movement from the finalPosition of the Lifter seemingly has no effect. Or perhaps there is some finite precision in Quaternion.FromToRotation? Or my math is incorrect in some way?

I'd love a sanity check on the code or approach or if I should approach this problem from a different perspective.

EDIT: Here's an example gif of the functionality with `m_EulerAngles` code (so the rotation overshoots, but works in 3D - also I recorded the gif at lower fps that's not the game's framerate)

# Answer
One of the major elements I was struggling with in my scenario was the over-rotation from the `Quaternion.FromToRotation()` method.

I noticed that it gave small angles even when an individual Lifter had not moved (e.g., when `From rotation` and `To rotation` were identical). I had focused so much on the moving Lifter I did not notice the non-moving Lifter was adding rotation when it should not have been.

I limited angle calculation and addition to only when an individual Lifter moves and suddenly the rotation is perfectly accurate, and furthermore did not need the questionable division of `Lifters count` from the vector method.
> 0 votes

# Answer
Trying to track displacement/deltas each frame is probably making this more complicated than it needs to be.

A much simpler solution is *not* to use deltas, and just update current position/rotation each frame based on the lifters.

Here's a simple example:

```
public class LifterManager : MonoBehaviour {

    [SerializeField] private Transform lifter1;
    [SerializeField] private Transform lifter2;
    [SerializeField] private Transform liftedObject;

    private Quaternion rotationOffset;

    void Start() {
        //get the difference between (the angle between the lifters)
        //and (lifted object's current rotation). later, we can apply
        //this difference to achieve the desired rotation when the lifters move
        Quaternion rot = GetLifterAngle();
        rotationOffset = liftedObject.rotation * Quaternion.Inverse(rot);
    }

    private void Update() {
        //position at midpoint between our two lifters
        liftedObject.position = (lifter1.position + lifter2.position) / 2f;
        //get the (angle between the lifters) and apply our previously saved offset.
        //This rotates the lifted object according to the movement of the lifters
        Quaternion rot = GetLifterAngle();
        liftedObject.rotation = rot * rotationOffset;
    }

    private Quaternion GetLifterAngle() {
        return Quaternion.LookRotation(lifter2.position - lifter1.position, Vector3.up);
    }
}

```

We don't care how the lifters moved since the last frame; we just care where they are currently positioned.

This simplified example doesn't track position offsets (basically, initial distance between each lifter and the point on the object that they grabbed) so the object can sometimes "jump" a bit when lifted. In your final code you'll probably want to keep track of those position offsets so you can maintain the relative distance between each lifter and the point they grabbed.
> 0 votes

---
Tags: unity, c#, physics, rotation, quaternion
---


# Question
Title: How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction?
Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead.

It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre-existing momentum will carry it wildly off-course, and not straight toward PointB.

It could turn exactly 180° around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions.

It would be more efficient to turn and start accelerating in *some specific direction* that will bleed off the unnecessary momentum but keep any useful momentum, course-correcting so that it is now moving toward PointB.

**I'm trying to figure out how to calculate that "specific direction" that the rocket needs to start accelerating toward, in order to efficiently reach PointB.** I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed.

Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc.

Can anyone help me out?

# Answer
> 1 votes
An elegant solution popped into my head:

The core of it is this code that should run each frame:

```
Vector3 desiredVector = (destination - transform.position).normalized;
Vector3 currentVector = body.velocity.normalized;
accelerationVector = desiredVector - currentVector;

```

This code picks an acceleration vector that will counteract momentum that is moving us away from the target, and produce a reasonably optimal trajectory.

However, this code is only concerned with counteracting momentum that is moving us away from the target ("undesired momentum"). There's a certain point where we've already killed almost all of the undesired momentum and now we should thrust straight towards the target. To achieve this, we can set a threshold that controls when we stop trying to counteract undesired momentum and simply start accelerating straight towards the target.

A more complete solution looks like this:

```
[SerializeField] protected float acceleration = 1;
[Range(0, .5f)]
[Tooltip("Controls how soon we stop curving and thrust straight towards the target")]
[SerializeField] protected float velocityThreshold = .2f;
[Tooltip("We consider the target reached when the distance is less than this value")]
[SerializeField] protected float distanceThreshold = 1f;
[SerializeField] protected Vector3 accelerationVector = Vector3.forward;

private Rigidbody body;

void Start() {
    body = GetComponent<Rigidbody>();
}

private void Update() {
    body.velocity += accelerationVector.normalized * acceleration * Time.deltaTime;
    //rotate us to face the direction we're currently moving in
    transform.LookAt(transform.position + body.velocity.normalized * 2f, Vector3.up);
}

public void ChangeDestination(Vector3 newDestination) {
    StartCoroutine(MoveTowards(newDestination));
}

private IEnumerator MoveTowards(Vector3 newDestination) {
    //Counteract momentum that is moving is in the wrong direction
    do {
        UpdateAccelerationVector(newDestination);
        yield return null;
    } while (accelerationVector.magnitude > velocityThreshold);
    //Thrust straight towards target
    while (Vector3.Distance(transform.position, newDestination) > distanceThreshold) {
        accelerationVector = newDestination - transform.position;
        yield return null;
    }
}

/// <summary>
/// Calculate an acceleration vector that will counteract any undesired momentum and move us along an optimal curve
/// </summary>
/// <param name="destination"></param>
private void UpdateAccelerationVector(Vector3 destination) {
    Vector3 desiredVector = (destination - transform.position).normalized;
    Vector3 currentVector = body.velocity.normalized;
    accelerationVector = desiredVector - currentVector;
}

//draw the acceleration vector using gizmos
private void OnDrawGizmos() {
    Gizmos.DrawLine(transform.position, transform.position + (accelerationVector.normalized * 10));
}

```

You will almost certainly need to adjust the velocity and position thresholds to suit your specific situation, and may eventually need to find a more robust solution than a simple numeric threshold, but this should get you most of the way there.

# Answer
> 2 votes
Let's assume that although it takes time to change our momentum, we're allowed to change our acceleration vector instantaneously. (If we have to model gradually changing acceleration over time, computing the optimal intercept trajectory gets *much* harder, so I'd argue it's not worth it - the trajectory we'll get this way still has \\$C\_1\\$ continuity, so it looks smooth from the player's eye view, and that's often enough to look plausible).

Using the observation in this previous answer:

* if start at point \\$\vec A\\$ with a velocity of \\$\vec v\_1\\$,
* and we have a maximum acceleration given by \\$ a\_{max} \\$
* then if we project a point \\$\vec D\\$ out \\$ T \\$ seconds along our current velocity, (\\$ D = \vec A + T \vec v\_1\\$)
* and draw a circle around that point with radius \\$ \frac {T^2} 2 a\_{max}\\$
* ...then we have a viable parabolic trajectory to reach any point on or inside that circle at time \\$T\\$.

So, imagine this in motion: we launch a tiny green dot from our position, representing the disc of points we could occupy \\$T\\$ seconds from now. (Or ball - the reasoning applies in 3D too if needed). As the dot moves away it also grows. And ultimately, it grows faster than it moves away, so eventually it will touch even points behind our start position.

Our question then is: when does the border of this disc/ball touch our destination point \\$C\\$?

ie. At what time \\$T\\$ does...

$$\begin{align} \\| \vec C - \left( \vec A + T \vec v\_1 \right) \\| &= \frac {T^2} 2 a\_{max}\\ \left( \left( \vec C - \vec A \right) - T \vec v\_1 \right)^2 &= \left( \frac {T^2} 2 a\_{max}\right)^2, \text{let } \vec c = \vec C - \vec A\\ \vec c \cdot \vec c - T \vec c \cdot \vec v\_1 + t^2 \vec v\_1 \cdot \vec v1 &= \frac {T^4} 4 a\_{max}^2\\ 0 &= T^4 \frac {a\_{max}^2} 4 - T^2 v\_1^2 + T \vec c \cdot \vec v\_1 - c^2 \end{align}$$

This is a quartic function - not the simplest to solve, but you can find existing libraries with solvers you can use. (One is suggested in the comments here)

Once you run the solver, you can take the least positive real solution \\$ T\_\*\\$ as the earliest opportunity to hit this point.

Then your point \\$\vec D = \vec A + T\_\* \vec v\_1\\$, and your acceleration vector is \\$\vec a = \left( \vec C - \vec D \right) \frac 2 {T\_\*^2}\\$, which should have magnitude \\$a\_{max}\\$ to within our accumulated rounding error, by construction.

Continue accelerating with this vector \\$\vec a\\$ for duration \\$T\_\*\\$ and you'll trace a parabolic curve to your destination point. Your velocity on impact will be along the line joining your destination and the point halfway between \\$\vec A\\$ and \\$ \vec D\\$.

---
Tags: unity, physics, movement, vector
---


title: Unity hangs when saving prefab asset

text:
# Question
Title: Unity hangs when saving prefab asset
For game saving purposes, I'm keeping track of references to ScriptableObjects through a lookup table, so that I can serialize/deserialize using the SO's position in that table. I have a lot of individual SOs that I want to be able to serialize, so I wrote an editor script to populate that table automatically. The table exists in a MonoBehaviour on a prefab.

Originally, I wasn't saving the prefab, because in the inspector it looked like the changes were successfully applying. However, those were showing in-memory changes; when you open the asset, the changes don't exist. The problem is, when I added the line to save the asset (`PrefabUtility.SavePrefabAsset`) Unity started hanging at the end of every import while showing that it was importing SO Lookup Table. I feel like I'm missing something obvious here, but Google hasn't been any help. What's wrong with my code?

Here's the editor script. Every time assets finish loading, it adds any ScriptableObjects that aren't in the lookup table and exist in one of the specified directories, and removes any that were deleted from or moved out of those directories.

```
public class SOLookupTableAutoPopulator : AssetPostprocessor
{
    const string SO_LOOKUP_TABLE_PATH = "Assets/Prefabs/SO Lookup Table.prefab";

    // every ScriptableObject in these directories is automatically added to the lookup table prefab
    static readonly string[] DIRECTORIES_TO_TRACK = new string[]
    {
        "Assets/ScriptableObjects/ExampleDirectory1",
        "Assets/ScriptableObjects/ExampleDirectory2"
    };

    static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        var lutPrefab = AssetDatabase.LoadAssetAtPath(SO_LOOKUP_TABLE_PATH, typeof(GameObject)) as GameObject;
        var soLookupTable = lutPrefab.GetComponent<SOLookupTable>();

        // remove first in case asset moved between two tracked directories
        foreach (var path in pathsInTrackedDirectories(deletedAssets.Concat(movedFromAssetPaths)))
        {
            soLookupTable.LookUpTable.RemoveAll(o => o.Path == path);
        }

        var toAdd = pathsInTrackedDirectories(importedAssets.Concat(movedAssets))
            .Where(p => AssetDatabase.GetMainAssetTypeAtPath(p).IsSubclassOf(typeof(ScriptableObject)));

        foreach (var path in toAdd)
        {
            if (!soLookupTable.LookUpTable.Any(o => o.Path == path))
                soLookupTable.LookUpTable.Add(new ScriptableObjectPathTuple(path));
        }

        PrefabUtility.SavePrefabAsset(lutPrefab);
    }

    static IEnumerable<string> pathsInTrackedDirectories (IEnumerable<string> pathList)
    {
        return pathList.Where(p => DIRECTORIES_TO_TRACK.Any(d => p.StartsWith(d)));
    }
}

```

The lookup table looks like this:

```
public class SOLookupTable : MonoBehaviour
{
    public List<ScriptableObjectPathTuple> LookUpTable;

    public int GetID (ScriptableObject so)
    {
        return LookUpTable.FindIndex(o => o.Asset == so);
    }

    public ScriptableObject GetSO (int id)
    {
        return LookUpTable[id].Asset;
    }
}

```

And here's the class that the lookup table contains. I track the path in addition to the asset itself for the deletion phase of OnPostprocessAllAssets - you can't retrieve an asset from a path that points to a deleted asset.

```
[Serializable]
public class ScriptableObjectPathTuple
{
    public ScriptableObject Asset;
    public string Path;

    public ScriptableObjectPathTuple (string path)
    {
        Path = path;
        Asset = AssetDatabase.LoadAssetAtPath(path, typeof(ScriptableObject)) as ScriptableObject;
    }
}

```

# Answer
> 1 votes
Turns out the saving code was triggering OnPostprocessAllAssets in a loop. To fix it, I added a simple check to skip OnPostProcessAllAssets if the only asset that was being processed was the prefab itself, like so:

```
if (importedAssets.Length == 1 && importedAssets[0] == SO_LOOKUP_TABLE_PATH)
{
    return;
}

```

---
Tags: unity, asset-management, prefabs
---


# Question
Title: How do I debug within an animation loop?
I'm trying to see some values within an animation loop, and am naively just `console.log`'ing when I need to, however, this usually results in the browser crashing from all the logs.

I'm working in JavaScript, but I don't think this issue is specific to JavaScript. How do people usually debug within an animation loop to see what values are?

# Answer
**Use breakpoints.** Every major browser has those right now, and if you are using any decently supported toolset (e.g. using javascript in some other context) it should also have support.

This lets you step through line by line and inspect whatever values you need to without having to constantly rerun your code with additional logging statements.
> 1 votes

# Answer
Store logs into array for later examination. Inspect in browser, or save to JSON file and feed to external scripts. If there is too much data: skip some % of logs, look at small slices of it, apply some strong filters, or calculate statistics. Use visualization (like `D3` or `pyplot`) if you feel fancy.

Alternatively, it *might* be possible to limit number of log lines, though I've failed to find anything relevant.
> 0 votes

---
Tags: javascript, animation, debugging
---


# Question
Title: Switching between world and battle scene with no or minimum loading?
I am making a strategy game where the player roams a grid map. When the player encounter enemy on the map he is transferred to a "battle" scene where two armies are fighting in turn based battle. Imagine Heroes 3 like game.

My question is:

1. Should I load the battle scene in additive mode and temporary hide the "world map" and when the battle is finished to just show the "world map" and hide the "battle" scene?
2. Or i should unload the world scene and load the battle scene, and when the battle is over -\> unload the battle scene and load the world scene ?

I think the 1st approach will give me less loading time between the two scenes, but will require more RAM ?

Second approach is standard one, but i will have loading between the scenes ?

My idea is to have no or minimal loading between battle and world scenes.

What do you guys thing ? Did you know what is the best practice in this case ?

By the way, i am using Unity as a engine.

# Answer
> 1 votes
For minimum loading times, you can have both the world map and the battleground in the same scene as two different gameObjects.

One option would be to have **both of them in the same space** as two different gameObjects and just deactivate the one you are not currently playing on. You can also keep both active and use rendering layers to tell the camera which one to render at any given moment. This option would be required when you want to use baked global illumination, so the two objects won't cast lights or shadows on each other. Also keep in mind that you need to avoid any physics collisions between the two different objects.

If you want to use physics-based rendering with pre-baked lightmaps but don't want to use rendering layers and don't want to worry about physics collisions either, then another options would be to use **spacial separation**. Like placing the battleground at Y-coordinate +1000 and the world map at Y-coordinate -1000. Just make sure that the camera far-plane distance is short enough that the player isn't going to see the other when looking up or down.

# Answer
> 0 votes
This is possible now without additive scenes by using async.allowSceneActivation.

**Note:** Unity will CRASH if you don't let it complete any async load operation that you start. so...

* Don't exit play mode while an async load is waiting to be activated.
* Don't let players cancel scene transitions once the async load starts

**Less important notes:**

* Your next scene's initialization is probably the real problem, try to optimize init before worrying about async load.
* The lag that appears when you first call LoadLevelAsync is only present in the editor.

```
public string levelName;

     AsyncOperation async;

     public void StartLoading() {
         StartCoroutine("load");
     }

     IEnumerator load() {
         Debug.LogWarning("ASYNC LOAD STARTED - " +
            "DO NOT EXIT PLAY MODE UNTIL SCENE LOADS... UNITY WILL CRASH");
         async = Application.LoadLevelAsync(levelName);
         async.allowSceneActivation = false;
         yield return async;
     }

     public void ActivateScene() {
         async.allowSceneActivation = true;
     }

```

Just call StartLoading() when you are certain that a scene transition is incoming and then ActivateScene() when you are ready to swap. I'm willing to live with the danger of unity crashes to avoid the hassle of additive scene loading.

---
Tags: unity, performance, loading, scene
---


# Question
Title: Data structure for collecting entities for instanced rendering
My game, a citybuilder, has many simple entities that rendered via glDrawArraysInstanced. A large city has over 600,000 entities, but most of those entities are one of a few hundred meshes. Every frame, I need a way to collect all those entities so that every entity with the same mesh, texture, and shader pass can be rendered with one draw call. Since my game thread is separate from my render thread, I currently use a data structure, which I call the draw buffer, to collect a plan for what order to draw things in.

This data structure has become a real problem. It's essentially a three dimensional chain of pointers to dynamic arrays, with the first dimension being shader pass, the second mesh, and the third texture. Every frame, the game goes through all entities (which are not in any particular order), filters out the ones that aren't in the view frustum, and inserts that mesh's data into the data structure. The draw buffer takes up a lot of memory and is highly fragmented.

I feel like this isn't the right approach, but I'm not sure what the right approach is. I'm trying to figure out if there is a way to do it without storing what I plan to do, but I do think that can be done without multiple passes on the entity list. Maybe I can keep a master version of the data structure without view frustum culling and compute view frustum culling somewhere else. Then I wouldn't have to rebuild the data structure every frame. Instead I would have to update the data structure every time something is added or removed -- fortunately entities never change shader pass, texture or mesh, so entities will always stay in the same place in the master data structure.

I hope this makes sense to someone because it barely makes sense to me. The question is, can I solve this problem with a better data structure, or should I consider a different approach entirely? Thanks for any advice you guys have.

# Answer
The general recipe for efficient instance drawing is as follows:

1. Send mesh data once.
2. Generate and send attribute array, where each row contains instance coordinates and possibly other information (color, animation, etc), one row per instance.
3. Configure attribute array to be updated (`glVertexAttribDivisor`) per instance, as opposed to per vertex by default.
4. Invoke instanced rendering (`glDrawArraysInstanced`).
5. Read and apply attributes in vertex shader.

Because you have provided no code, I am redirecting you to third-party example.
> 1 votes

---
Tags: opengl, data-structure, instancing
---


# Question
Title: What is a good length for looping background music in a Tower Defense game?
We know that the soundtrack is important and expensive for an indie's budget.

I requested a looping background track for for my Tower Defense game, where zombie/monsters attack the player. So, for the entire level, the player will keep hearing this music.

In this kind of game, is 30 seconds good for a looping music track, or I need to increase it?

# Answer
> 2 votes
There isn't necessarily a "correct" length to aim for with a looping track — that's why you'll find different game tracks have different lengths!

Instead, you may want to go research some games that have a similar style and audio feel to what you want. Look up their soundtrack online and check the lengths of the tracks they use, or time the repeats yourself with a stopwatch in your own play or while watching a Let's Play recording.

Do this also for a game or two you find '"too repetitive" for your taste, musically, and compare. That gives you a lower bound to aim above.

You may also want to consider commissioning a short looping track with "stems" — multiple separate layers that you can fade in and out over a longer period to break up the repetition, or signal changes in gameplay state like boss waves. This can make a short loop seem much longer and less repetitive.

In my TOJam 2016 game Last One Standing, the sound designer I worked with, David Vitas, split the single BGM track into two layers: one with just the percussion, and one with the melody. In-game, I play both in sync, but vary the volume of the melody with the intensity of action, punctuating moments of rest in the gameplay with little drum solos. Because it's reacting to the gameplay, it rarely loops exactly the same way twice in a row, making it feel much longer and more dynamic, even from a very simple basis. (In that case, it was about a 90 second loop)

# Answer
> 1 votes
It depends a lot on:

* The kind of music. When you have subliminal muzak which is more ambience than music, then you can get away with it being a lot shorter (in practice these tracks still tend to be pretty long, because they are so simple to compose). But more nuanced music with more recognizable motives and progressions needs to be a lot longer so the loops don't become too noticeable.
* How long sessions are in your game. A game which is played for a couple minutes at a time can get away with a lot less soundtrack than one which is played for hours on end.

But in general, the usual length of ingame BGM tracks tend to be around 2-3 minutes.

---
Tags: music
---


title: Camera bounds with container overflow

text:
# Question
Title: Camera bounds with container overflow
I'm using **Phaser** to create a small web based game, but I would like some advice on how to handle multiple resolutions and scrolling.

Basically what I would like to achieve is the following :

* The game view must fit in a container (maybe smaller than the browser window) of any size and still cover it all
* The aspect ratio must be maintained
* The camera must follow the player and stop scrolling when the world’s bounds are reached

The world has a fixed size that never changes (pretty small).

The framework seems to already have everything required to do what I described.

For the game config I use:

```
{
    width: 1280,
    height: 700,
    scale: {
        mode: Phaser.Scale.ENVELOP
    },
    ...
}

```

Then for the camera:

```
this.cameras.main.startFollow(this.player);
this.cameras.main.setBounds(0, 0, this.gridSizeX * this.gridCellSize, this.gridSizeY * this.gridCellSize);

```

Very basic stuff, but the scale mode make the game area overflow its container. That’s exactly what I want but the camera bounds become incorrect as demonstrated here:

Do you know a way to setup the camera to scroll until the end of the overflowing area ?

Thanks a lot!

**EDIT**:

I tried to change the size of the camera to make it equal to the size of the canvas' parent container, like this:

```
this.cameras.main.setSize(
    this.game.canvas.parentElement.offsetWidth,
    this.game.canvas.parentElement.offsetHeight
);

```

The result is:

In this example the size of the window is **1280x700** and the size of the container is **1024x560**.

So setting the size of the camera to **1024x560** give the result above.

I'm getting confused.

Any idea?

# Answer
I've finally found a workaround. I share it in the hope it could help someone else.

I think the `scaleManager` is bugged, so I've set the scale mode to `Phaser.Scale.NONE` and do it manually.

I've created a `GameObject` named `CanvasScaler`, that I add to my scene like this:

```
export default class PlayScene extends Scene {
    [...]
    create () {
        const scaler = new CanvasScaler(this, 'CanvasScaler');
        this.add.existing(scaler);
    }
}

```

The `CanvasScaler` listen for the `resize` event of the `ScaleManager` and re-calculate the size of the canvas and the position and size of the camera :

```
import * as Phaser from 'phaser';
import { proxy } from "essentials/utils/utils";

export class CanvasScaler extends Phaser.GameObjects.GameObject {
    public constructor(scene: Phaser.Scene, type: string) {
        super(scene, type);
        this.bind();
    }

    private bind(): void {
        this.scene.scale.on('resize', proxy(this.resizeCanvas, this));
        this.resizeCanvas();
    }

    private resizeCanvas() {
        const containerWidth = this.scene.scale.canvas.parentElement.offsetWidth + 1; // + 1 to ensure the size of the camera is not 1px short after rounding
        const containerHeight = this.scene.scale.canvas.parentElement.offsetHeight + 1; // same

        const gameWidth = this.scene.scale.gameSize.width;
        const gameHeight = this.scene.scale.gameSize.height;
        const gameRatio = gameWidth / gameHeight;

        let newWidth = containerWidth;
        let newHeight = containerWidth / gameRatio;

        if (newHeight < containerHeight) {
            newHeight = containerHeight;
            newWidth = containerHeight * gameRatio;
        }
        const marginTop = (containerHeight - newHeight) / 2;
        const marginLeft = (containerWidth - newWidth) / 2;

        // Scale the canvas
        this.scene.scale.canvas.style.width = Math.round(newWidth) + 'px';
        this.scene.scale.canvas.style.height = Math.round(newHeight) + 'px';

        // Center it into view
        this.scene.scale.canvas.style.marginTop = Math.round(marginTop) + 'px';
        this.scene.scale.canvas.style.marginLeft = Math.round(marginLeft) + 'px';

        const scaleRatioX = marginTop ? containerWidth / gameWidth : 1;
        const scaleRatioY = marginLeft ? containerHeight / gameHeight : 1;
        const offsetX = Math.floor((-marginLeft) / scaleRatioY);
        const offsetY = Math.floor((-marginTop) / scaleRatioX);

        // Update the camera size and position
        this.scene.cameras.main.setViewport(
            offsetX,
            offsetY,
            marginLeft ? (gameWidth - (offsetX * 2)) : gameWidth,
            marginTop ? (gameHeight - (offsetY * 2)) : gameHeight
        );
    }
}

```

Here is the result:

The camera's `setBounds` and `startFollow` stay the same.
> 0 votes

---
Tags: phaser
---


# Question
Title: Unity RigidBody2d.MovePosition() not working on dynamic rigid body
As it says, .MovePosition() won't move my character. I know other ways to move but I want .MovePosition() in particular as I think it will solve the camera's jittery movement when the player pushes through a collision.

This script works on a kinematic rigidbody but not on a dynamic one.

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

public class PlayerMovement : MonoBehaviour {

    Rigidbody2D rbody;
    Animator anim;
    public float speed = 0;
    SpriteRenderer sr;

    void Start () {
        rbody = GetComponent<Rigidbody2D> ();
        anim = GetComponent<Animator> ();
        sr = GetComponent<SpriteRenderer>();
    }

    void Update(){
        sr.sortingOrder = ((int)Camera.main.WorldToScreenPoint (sr.bounds.min).y) * -1;
        Vector2 movementVector = new Vector2 (Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        if (movementVector != Vector2.zero) {
            anim.SetBool ("isWalking", true);
            anim.SetFloat ("inputX", movementVector.x);
            anim.SetFloat ("inputY", movementVector.y);
        } else {
            anim.SetBool ("isWalking", false);
        }
        Vector2 newPos = rbody.position + movementVector *Time.fixedDeltaTime;
        rbody.MovePosition(newPos);
        //rbody.position = Vector2.MoveTowards(rbody.position, newPos, Time.deltaTime*speed);
    }
}

```

FYI I'm on Unity 5.6 if that helps.

# Answer
> -1 votes
You are right, you can not use `MovePosition` with non kinematic rigidbody.

From Unity Rigidbody.MovePosition documenttion:

> Use Rigidbody.MovePosition to move a Rigidbody, complying with the Rigidbody's interpolation setting.
>
> (...)
>
> Set Rigidbody.position instead, if you want to teleport a rigidbody from one position to another, with no intermediate positions being rendered.
>
> (...)
>
> If the rigidbody has isKinematic set false then it works differently. It works like transform.position=newPosition and teleports the object (rather than a smooth transition).

TLDR;

`MovePosition` is for kinematic rigidbodies as those are not affected by phisics you can just move them where you want. Non-kinematic rigidbodies are affected by physics, thus should be moved with `AddForce` method. It is either one or the other.

# Answer
> 0 votes
@IndieForger answer above is correct but you CAN use MovePosition with non kinematic rigidbody as well even though docs says it's mostly for kinematic. JUST MAKE SURE 'Simulated' is checked ON in Rigidbody component and if U don't want gravity set it to 0. Then it will work as intended.

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


# Question
Title: Is it possible to generate and solve a maze in one run?
I'm using *recursive backtracker* or *depth first fearch* (correct me if it's not the same) algorithm to generate unique 2d mazes for my game. However for the gameplay I intend to implement the logic also needs to know the solution path from A,B-X,Y (to solve the maze). For that I intend to run a second process, that does that. I wonder if there is any chance to do in one run - generate and solve (to save some processing and load-times).

# Answer
> 1 votes
If your depth-first search starts from the entrance or exit of the maze, then this is trivial.

Each time your generator explores/carves out a cell, store the direction you entered that cell from. This effectively gives you a map of arrows tracing out the path back to the origin of your search.

From your chosen destination point, follow those arrows until you reach the origin of the search. This gives you the path through the maze that connects the two points in linear time.

If your search starts from somewhere in the middle, then you need to build this path in two parts: start at your entrance, and backtrack along the arrows to the origin, marking the cells as "visited" as you go. Then start at your exit and do the same, until you reach a cell that's already been marked "visited". Join the two paths you've traced so far at the point where they reach this cell, forming a single path connecting the entrance and exit.

---
Tags: maze
---


title: Making an auto patcher

text:
# Question
Title: Making an auto patcher
I'm currently in the last phases of an original release for my upcoming risk game - I'm looking at making a patching system to autopatch the game.

My current concept for it is-

1: Player opens the game

2: Game checks valid serial key

3: If valid, game checks latest version

4: If newer, game prompts opening of auto patcher

5: If opened, patcher downloads version list, with all version

6: Patcher loops through list to find all newer patches and downloads all version files with links to patch data

7: Patcher checks with the website for each file, checking if downloading all patches is smaller than downloading the latest version of the file: if smaller, downloads patches; if bigger, downloads latest file

8: If smaller patch file, patcher incrementally alters file with each patch applied by each small patch file, from oldest to newest. If larger, patcher simple overwrites the file

9: Patcher asks exit/launch game so players can enjoy the game

Does this sounds like a sane way to do the patcher or will it come back and bite me later on?

# Answer
The reasoning and processing at points 5-8 is fixed for a given pair of old version and latest version.

Therefore, do it once on the update server: the protocol can be simplified to a single exchange in which the patcher says the installed game is version X and the server sends a "recipe" with a list of the appropriate incremental patches and replacement files, which the patcher then downloads and applies.

Don't forget to allow for forced partial or total replacement of any game client files, either by user request (e.g. after removing malware or after a file system accident) or because the patcher says so (e.g. some file doesn't match the expected hash).

You also need to update the patcher itself.
> 2 votes

# Answer
I recently developed an autopatcher/autoupdater in c#. It expects the existence of server-side metadata containing for each file its respective md5 hash as well. i don't know if you've considered this hash approach for file comparison instead of relying in a "version number". It could also solve your "incremental patch" problems.

This also means that on the server-side, you only need to keep updated a single directory with the most recent files and then recompute the server metadata to refresh all their hashes whenever you want to make public the fact that there is a new version.

Checkout my open source repository if you're interested in this approach: https://github.com/igor-ruivo/generic-auto-updater
> 0 votes

---
Tags: deployment, patching
---


# Question
Title: How to draw a Voronoi Splitscreen view in GMS, where each player's screen area is a polygon shape?
I'm trying to implement the Voronoi Splitscreen effect that Squirrel Eiserloh described at GDC 2016, and I'm having trouble figuring out how to 'clip' the rendered scene for one player along a diagonal line or polygonal shape.

So how can I draw the scene inside set of points or a shape other than rectangle?

# Answer
The best way I found to do this is to draw each view to a surface, and cover the area of the surface that isn't the view with a black polygon. Then draw all your view surfaces additively to an otherwise black view port. It's not cheap, but it works well enough. It comes with the added advantage that decorating the borders or moving and rotating the split at runtime is trivial, as is smoothly unsplitting/resplitting the view.
> 1 votes

---
Tags: mathematics, rendering, camera, game-maker
---


# Question
Title: Joystick servo control axis value when idle (unity)
When the joystick servo control is idle (user not moving it) , i don't believe the axis value will be 0 because there's a lot of thing that interfere with the value (such as calibration , inaccuracy , physics problem in real life , ect . . ) . Is anybody have tested at which range the joystick servo control axis value is safe to be considered as idle? (both negative and positive) . I'm looking for constants here.

To anyone confused what does i meant with joystick servo control , picture below :
(ps : not my image, i found it on google)

# Answer
This is why the unity input system supplies built-in functionality to define **deadzones**.

A deadzone is an area in which the stick's value will be clamped to its closest extreme (0-1).

A standard deadzone is usually under 15% tilt and over 95% tilt. You are of course free to change this however you wish.
> 0 votes

---
Tags: unity, controllers
---


title: World rotation independent mouselook

text:
# Question
Title: World rotation independent mouselook
Preface: I am terrible at using quaternions right.

I wanted to create a world rotation independent mouselook script. That is, no matter the 'down' for the camera, the mouselook should feel natural to the player in relation to what is displayed on screen.

I now have the following script running on update in my camera:

```
        Quaternion worldRot = Quaternion.LookRotation(Vector3.forward, Vector3.left);

    xRot += -rotSpeed * Input.GetAxis("Mouse Y");
    yRot += rotSpeed * Input.GetAxis("Mouse X");
    transform.rotation =
        Quaternion.AngleAxis(yRot, worldRot * Vector3.up) *
        Quaternion.AngleAxis(xRot, worldRot * Vector3.right) *
        worldRot;

```

Unsurprisingly, it tumbles all over the place. I think the issue is in basing the rotation angles on the worldRot (World rotation as seen by the camera), while then also rotating the whole by worldRot. I cannot get my head around how else to go about it, though...

My initial alternative was to use

```
        transform.rotation =
        Quaternion.AngleAxis(yRot, Vector3.up) *
        Quaternion.AngleAxis(xRot, Vector3.right) *
        worldRot;

```

But this anchors the mouse's movements to the world rather than the camera, which as described above isn't desired either.

Based on this (or, perhaps, in a completely different way), how do I make a mouselook system with an arbitrary down vector?

# Answer
For a typical FPS camera that can't look straight up/down (to stay away from the gimbal lock point where the view just spins), I'd use Quaternion.Euler to construct it from your yaw and pitch variables.

We'll measure our yaw and pitch relative to the current world orientation, so all we have to do is multiply this by the world orientation quaternion to get our net orientation:

```
Quaternion GetUpdatedCameraRotation(Quaternion worldOrientation) {

    yawDegrees = (yawDegrees + rotationSpeed  * Input.GetAxis("Mouse X")) % 360.0f;
    pitchDegrees = Mathf.Clamp(pitchDegrees - rotationSpeed * Input.GetAxis("Mouse Y"),
                  -maxPitchDegrees, maxPitchDegrees);

    return worldOrientation * Quaternion.Euler(pitchDegrees, yawDegrees, 0f);
}

```

When the world orientation changes, we'll need to update our yaw and pitch to preserve the direction we're looking, under the new frame of reference:

```
void UpdateWorldOrientation(Quaternion newWorldOrientation) {

    Vector3 forward = Quaternion.Inverse(newWorldOrientation) * transform.forward;

    pitchDegrees = Mathf.Asin(-forward.y) * Mathf.Rad2Deg;

    yawDegrees = Mathf.Atan2(forward.x, forward.z) * Mathf.Rad2Deg;
}

```

Note that as-written, "up" on the screen will always point to the current world up - you'll never be twisted sideways. If your world orientation changes suddenly, you'll likely want to blend to the new camera orientation over several frames (eg. using `Quaternion.RotateTowards`), so the player sees the camera twist to orient to the new up/down, rather than suddenly popping into a new orientation.
> 2 votes

# Answer
In hindsight, I was way overcomplicating this.

The usual y rotation should be done around transform.up rather than vector3.up. The usual x rotation should be done around transform.right rather than Vector3.right.

No explicit quaternion multiplications needed.

It was ultimately quite simple. Thanks for all the pointers.

As for the resulting code; I first made the camera actually a child of the object that actually gets rotated. Because of that, the camera's rotation becomes local to that rotation. Therefore, the actual mouselook script is no more than

```
    Vector2 look = input.Player.Look.ReadValue<Vector2>();
    look *= Time.deltaTime;
    yLook += look.y * LookSensitivity;
    yLook = Mathf.Clamp(yLook, -85, 85);
    transform.Rotate(Vector3.up * (look.x * LookSensitivity));
    camera.transform.localRotation = Quaternion.Euler(-yLook, 0, 0);

```

Mind you that this is run by the parent with reference to the child. It is holding on to a yLook field because we rotate the camera by it, but don't want it to influence the camera's movement. The parent object runs the following code on itself.

```
transform.rotation = Quaternion.LookRotation(World.transform.up, World.transform.forward);

```

I found that separating the code out like this allowed me to do more complex camera movements elsewhere in the script. At no point does the camera itself really need to be concerned with what 'up' is.
> 0 votes

# Answer
I assume that since you said "no matter the 'down' for the camera", you want the rotation to be relative to the camera and you are not actually rotating "the world".

Then one reason your original script was not working is because

`Quaternion worldRot = Quaternion.LookRotation(Vector3.forward, Vector3.left);`

should have been

`Quaternion worldRot = Quaternion.LookRotation(transform.forward, transform.up);`

which is the same as just doing `Quaternion worldRot = transform.rotation;`. Then your second snippet would have worked.
> -1 votes

---
Tags: unity, camera, quaternion
---


title: Sprites lose quality when in Unity

text:
# Question
Title: Sprites lose quality when in Unity
Whenever I drag a sprite sheet into unity, it, for whatever reason, distorts. Is there any way to remedy this?

Original

Distorted

# Answer
> 1 votes
Click on your texture, the texture import settings appear in the inspector window.... look for Filter Mode... bilinear, trilinear, point. Try changing it to Point(no filter) and that should eliminate any distortion. And what do you exactly mean by distortion? It seemed fine for me when I imported with point filter mode. Anyway let me know if it worked.

# Answer
> 2 votes
Click on the image asset in your "Project" tab and check its import settings in the "Inspector" tab. For pixel art you usually want the following settings:

* Texture Type: Sprite (2D and UI)
* Filter Mode: Point
* Compression: None

---
Tags: unity, sprites
---


title: Spritebatch drawing the other way

text:
# Question
Title: Spritebatch drawing the other way
I am drawing a rectangle using a emptytexture (1x1) and I use the following:

```
spriteBatch.Draw(EmptyTexture, new Rectangle((int)MyPosition.X + MyTexture.Width / 2, (int)MyPosition.Y + MyTexture.Height / 2, 100, 2000), null, Color.Red, MyDirection + MathHelper.ToRadians(180), new Vector2(0, 0), SpriteEffects.None, 0.0f);

```

which does this:

But now I am trying to make another rectangle next to that one which looks like this:

But when you rotate the ship it rotates like this:

I've done this by the following:

```
spriteBatch.Draw(EmptyTexture, new Rectangle((int)(MyPosition.X + MyTexture.Width / 2) + 100, (int)MyPosition.Y + MyTexture.Height / 2, 100, 2000), null, Color.DarkRed, MyDirection + MathHelper.ToRadians(180), new Vector2(0, 0), SpriteEffects.None, 0.0f);

```

But what I am trying to do is to make the point of rotation of the 2nd one at the middle of the ship like the other one but it's drawn the same.

# Answer
> 0 votes
**Solved**

```
spriteBatch.Draw(EmptyTexture, new Rectangle((int)(MyPosition.X + MyTexture.Width / 2) + 100, (int)MyPosition.Y + MyTexture.Height / 2, 100, 2000), null, Color.DarkRed, MyDirection + MathHelper.ToRadians(180), **new Vector2(0, 0)**, SpriteEffects.None, 0.0f);

```

I had to change the origin

new Vector2(0, 0) to new Vector2(1, 0)

I have no clue why though

---
Tags: c#, rotation, monogame, spritebatch
---


# Question
Title: Orbital mechanics: orbit as a function of time. Universal variable formulation?
I am trying to model a two dimensional orbit for a two body Kepler problem but have gotten stuck when introducing the time variable.

For a satellite with known semi major axis (a), eccentricity (e), and true anomaly (theta), I have:

```
r = a*(1-e**2)/(1+e*cos(theta))

```

How can I calculate theta as a function of time using the Wiki suggested Universal variable formulation method? I have no idea how to implement (am using Python but any algorithm advice much appreciated!)

Alternatively, how do I calculate r as a function of time?

Note: All other orbital elements and masses are available. Also I am trying to come up with a general solution for elliptical, hyperbolic and parabolic orbits.

Cheers!

# Answer
I calculated true anomaly as function of time, for planetary motion , in c# , in this way:

1. Compute mean anomaly (time: current time , G: newton grav.connstant, M: planet mass or the sum of the two orbiting objects , a: semi major axis)

```
        //M = nt
            double n = Math.Sqrt((G * (M)) / (a * a * a));
            double Mt = n * time;

```
2. Compute the eccentric anomaly E by solving Kepler's equation:

```
     //For orbits with ε > 0.8, an initial value of E0 = π should be used.
        if (eccentr>0.8)
            E = NumApprox(150, Math.PI,Mt, 10E-15);
        else
            E = NumApprox(150, Mt, Mt, 10E-15);

```
3. true anomaly (angle)

true\_anom = 2.0 * Math.Atan2(Math.Sqrt(1.0 + eccentr) * Math.Sin(E / 2.0), Math.Sqrt(1.0 - eccentr) * Math.Cos(E / 2.0));
4. distance from planet

d = a * ((1.0 - eccentr * eccentr) / (1.0 + eccentr * Math.Cos(true\_anom)));

Finaly Numerical approximation of inverse problem:

```
private double NumApprox(int intr, double prev,double Mt, double  err)
    {
        double ret = prev;
        double retprev = prev;
        for (int i=0 ; i<intr; i++){
            retprev = ret;
            ret = ret - (ret - eccentr * Math.Sin(ret) - Mt) / (1.0 - eccentr * Math.Cos(ret));
            if ( Math.Abs(ret - retprev) < err)
                break;
        }
        return ret;
    }

```

EDIT: **calculate Position and Velocity**

What we done is half of the work in getting Cartesain Orbit Elements from kepler Orbit Elements where :

```
    //some kepler Orbit Elements:
    public double d;
    public double true_anom;
    public double eccentr;
    public double a;
    public double E;
    public double w=0; //small omega ω :  Argument of periapsis (in rad)

    //Cartesain Orbit Elements:
    //Position Vector
    private double x;
    private double y;
    private double z; //2d :not used
    //Velocity Vector
    private double vx;
    private double vy;
    private double vz; //2d :not used

```

as final step we can calculate position and velocity vectors as :

```
//Position
x = d * Math.Cos(true_anom);
y = d * Math.Sin(true_anom);
//apply ω
double xx = x * Math.Cos(w) - y * Math.Sin(w);
double yy = x * Math.Sin(w) + y * Math.Cos(w);
x = xx;
y = yy;

//Velocity
double v = Math.Sqrt(G * M * a) / d;
vx = -v * Math.Sin(E);
vy = -v * Math.Sqrt(1.0-eccentr*eccentr) * Math.Cos(E);

```

EDIT: **references**

Orbital elements

Kepler's equation

True anomaly

Eccentricity vector

Argument of periapsis

Newton's method for numerical approximation

The Kerbal Space Program (KSP) Physics Documantation (pdf)
> 7 votes

# Answer
Retro orbit function, also can be adapted to static-node elements (ap,ma) ... this is the math. result error +- 0.08 degree from VSOP.

```
function skyUpdate3(id) {
/// Using timed Elements - delivered in radians.
var e = id.e, n, E, r, v, o, x = [0,0,0];
var ap = id.lp - id.o;
var M = toNormalRange(id.ml - id.lp);
  E = SolveKepler(M,e);
  r = IDS(au2km(id.a)) * (1.0 - (e * Math.cos(E)));
  v = 2.0 * Math.atan(Math.sqrt((1.0 + e) / (1.0 - e)) * Math.tan(E / 2.0));
  v = (PI2 + v + ap) % PI2; /// True Anomaly
  o = id.o;
  e = Math.sin(v);
  v = Math.cos(v);
  n = Math.sin(o);
  o = Math.cos(o);
  M = Math.cos(id.i);
  x[0] = r * (o * v - (n * e * M));
  x[1] = -r * e * Math.sin(id.i);
  x[2] = r * (n * v + (o * e * M));
  x = popmatrix(orbitmatrix,x);
  return x;
}

```

Here's the rest and the proof in 3 method comparison- plus Walker's table and Azimuth. http://innerbeing.epizy.com/charts/orbital.html Look no further.

if you just want Gravity:

```
//2D
function gravitate(i) {
  var p = [,] /// old pnt
  var v = [,] /// old velocity;
  var cxy = [cx,cy]; /// Center
  var dv = subv2(cxy,p);
  var f = Math.pow(dv[0],2) + Math.pow(dv[1],2);
  f = Mass / (f * Math.sqrt(f));
  cxy = multv2(dv,f); v = addv2(v,cxy);
  newvel = v;
  newpnt = addv2(p,v);
}

```

One more thing, if your planet moved, orbiters need to be updated first. addv(orbiterpoint,subv(new,old)) - gravitate() assumes stationary center.
> 0 votes

---
Tags: physics, mathematics, game-design, game-mechanics, orbit
---


# Question
Title: Problems with gravity and box colliders in Unity 3D
I have a game character that can jump or roll in order to avoid obstacles. He is able to roll while on the ground and he can also roll while he is in the air after jumping. Everything was working fine when I made him roll. I want to make it so that when he rolls while he's in the air after jumping, he would fall at a faster pace than if he was just falling normally. So I did this in my c# script:

```
IEnumerator IncGravAcc()
{
    Physics.gravity = new Vector3(0, -50f, 0);
    yield return new WaitForSeconds(2f);
    Physics.gravity = new Vector3(0, -9.8f, 0);
}

```

I call this coroutine in the function that runs when the down arrow is clicked. Everything is working fine. When he rolls while in the air, he falls at a faster than normal rate. However he doesn't land properly and he just falls right through the platform like it's not even there. Here's a video to show what I mean: https://youtu.be/sirc4L3MnqM

I have a box collider, not set to isTrigger, on the player (you can see it, the green box, right underneath him in the video) and the player's also a rigidbody. The platforms don't have rigidbodies on them but they do have box colliders set to trigger. You can see the platform's box collider in the relation to player's box collider in the picture provided (the platform's box collider is the larger one of course)

How do I get it so that the character doesn't fall through? Please let me know if there's anything else you need to know about the project. Thank you for helping me!

# Answer
In your video, I notice that on the RigidBody your Collision Detection is set to discrete. This means there will only be a collision if during a physics frame there is an actual intersection between its collider and another collider.

At the higher speeds you provide, it is quite easy for colliders to miss (or 'step over') each other.

If you set the Collision Detection to Continuous Dynamic, fast moving objects will analyze the whole path their collider takes, and anything that intersects it along it. Mind you, if it intersects with OTHER RigidBodies, it will only work properly if those have their Collision Detection set to (at least) Continuous.

Generally, here's your rule of thumb:

* **Discrete**: This isn't going to be moving much, or be hit by anything moving much.
* **Continuous**: This won't be moving very fast, but could potentially collide with something that does.
* **Continuous Dynamic**: This object will move fast, and needs precise collision detection or risk clipping.
* **Continuous Speculative**: This object is kinematic, or you have so many Continuous RigidBodies that it is causing performance problems. It is cheaper, but less precise.
> 0 votes

---
Tags: unity, game-mechanics, platformer, collider
---


# Question
Title: Sorting layer issue with multiple sprites and a Tilemap in Unity
I have a particle system that draws a blood splat. I have a Tilemap that represents terrain. However, the blood splats, which are on a sorting layer in front of the terrain, are somehow rendered both in front of and behind the terrain.

I have encountered similar problems before where the particles had some different Z value than the terrain, but that is not the case this time (3D view):

Here are the Inspector panels for these objects.

First terrain:

The renderer for the upper (in Y) blood particle system:

And for the lower (in Y) system:

And finally my sorting layers, where Base is behind Foreground:

What might cause this behavior and how can I fix it?

Edit: Here is the entire BloodSplat prefab:

# Answer
> 1 votes
Well I got a few tips for you to try to get it working :

1. I'm not really sure what the exact issue is. I think it might might actually be a bug in Unity. Anyways, it deals with the SpriteRenderer and the order in which it is applied to the gameobject (relative to the Particle System).Try to remove the SpriteRenderer, and then add it (or just create a whole new gameobject and add the Particle System first). After doing this, You Should be able to change the sorting layer of the particle system. Another workaround would be to create a separate particle system gameobject and attach it (as a child) to the main gameobject.
2. Alternatively, you can specify when your particle system has to be rendered. You can check the particle systems rendering order in frame debugger and if you want to push it front, you can increase renderqueue value by increasing the Custom Render Queue value.

---
Tags: unity, sprites, sorting
---


title: Character bobs when moving

text:
# Question
Title: Character bobs when moving
Whenever I try to move a character in unity, the character kind of, like, bobs around when walking. Is there any way to remedy this? I have tried the trick of putting the inputs into update and the outputs into fixedupdate, if that's any consolation. Also please ignore the fact that I've used the arrow keys instead of getaxis.

using System.Collections.Generic;
using UnityEngine;

public class MovePlayer : MonoBehaviour
{

    public bool upArrow = true;
    public bool downArrow = true;
    public bool leftArrow = true;
    public bool rightArrow = true;
    public float speed;
    public bool test = false;

    void Update()
    {
        if (Input.GetKey(KeyCode.UpArrow))
        {
            upArrow = true;
        }
        else
        {
            upArrow = false;
        }

        if (Input.GetKey(KeyCode.DownArrow))
        {
            downArrow = true;
        }
        else
        {
            downArrow = false;
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            leftArrow = true;
        }
        else
        {
            leftArrow = false;
        }

        if (Input.GetKey(KeyCode.RightArrow))
        {
            rightArrow = true;
        }
        else
        {
            rightArrow = false;
        }

    }

    void FixedUpdate()
    {

        if (upArrow == true)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y + speed, 0);
        }

        if (downArrow == true)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y - speed, 0);
        }

        if (leftArrow == true)
        {
            transform.position = new Vector3(transform.position.x - speed, transform.position.y, 0);
        }

        if (rightArrow == true)
        {
            transform.position = new Vector3(transform.position.x + speed, transform.position.y, 0);
        }

    }

    void OnTriggerEnter2D(Collider2D bump)
    {

        if (bump.gameObject.tag == "Wall")
        {

            test = true;

        }
        else
        {

            test = false;

        }

    }

}
```
</code></pre>

# Answer
Firsly, use FixedUpdate only when using movement via physics systems,(i.e. if you're using rigidibody to move it via adding a force or by changing it's velocity), since you're doing neither it's good to move the player in the update itself.

```
void Update()
{
    if (Input.GetKey(KeyCode.UpArrow))
    {
        transform.position = new Vector3(transform.position.x, transform.position.y + (speed * Time.deltaTime * 10), 0);
    }
    if (Input.GetKey(KeyCode.DownArrow))
    {
        transform.position = new Vector3(transform.position.x, transform.position.y - (speed * Time.deltaTime * 10), 0);
    }
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        transform.position = new Vector3(transform.position.x - (speed * Time.deltaTime * 10), transform.position.y, 0);
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        transform.position = new Vector3(transform.position.x + (speed * Time.deltaTime * 10), transform.position.y, 0);
    }
}

```

The reason I multiplied by speed with Time.deltaTime is to normalise it and make it frame rate independent.

And also it is not a preferred way to move your player using transform, if you're particular about collisions, changing the position using transform.position can cause tunnelling into objects, I suggest you to move the player using Rigidbody and changing it's velocity.

Try doing something like this in FixedUpdate for a smoother rigidbody movement : `rigidbody2D.velocity = new Vector2(Mathf.Lerp(0, Input.GetAxis("Horizontal") * Speed * Time.fixedDeltaTime, 0.8f), Mathf.Lerp(0, Input.GetAxis("Vertical") * Speed * Time.fixedDeltaTime, 0.8f));`
> 0 votes

---
Tags: unity, c#, visual-studio
---


# Question
Title: Why can't I create a D3D12 Device with the highest performance adpater retrieved by EnumAdapterByGpuPreference?
```
    IDXGIAdapter* higher_performance_adapter;
    dx_result = dxgi_factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
                                                         __uuidof(IDXGIAdapter),
                                                         (void**)&higher_performance_adapter);
    if(SUCCEEDED(dx_result))
    {
      UINT output_index = 0;
      IDXGIOutput* output;
      while(higher_performance_adapter->EnumOutputs(output_index, &output) != DXGI_ERROR_NOT_FOUND)
      {
        DXGI_OUTPUT_DESC output_description = {0};
        output->GetDesc(&output_description);

        ++output_index;
      }

      ID3D12Device* device;
      dx_result = D3D12CreateDevice(higher_performance_adapter,
                                    D3D_FEATURE_LEVEL_12_1,
                                    __uuidof(ID3D12Device),
                                    (void**)&device);
      if(SUCCEEDED(dx_result))
      {

          ...

```

I'm trying to create a D3D12 device selecting the GPU with the higher performance because passing null to the adapter parameter at D3D12CreateDevice gets the first adapater from EnumAdapters, which is the Intel integrated GPU. But, when I got a IDXGIAdapter object of my dedicated GPU, the EnumOutputs function failed, as well as the D3D12CreateDevice. Why is that? Why these functions fails when using the dedicated GPU, which in my case is a NVIDIA, ?

The returned dx\_result is "0x887a0004 : The specified device interface or feature level is not supported on this system. "

That don't makes sense, since my system supports DirectX12.

# Answer
Ok, I found the issue. I just opened my task manager to see information about my NVIDIA GPU. On DirectX verison it saids 12 (FL 11.0) which I realized that FL stands for Feature Level, which is exactly the seconds parameter for D3D12CreateDevice. I Just changed D3D\_FEATURE\_LEVEL\_12\_1 to D3D\_FEATURE\_LEVEL\_11\_0 and it works.

Now, I don't get it why the EnumOutputs failed. I mean, no outputs were found, event with the index 0.
> 0 votes

---
Tags: directx12
---


# Question
Title: intersection of primitive in a unit wrapping 3D space
is there people good enough for a math problem (for a shader)? I want to write an algorithm that would **intersect** primitives (triangles, squares, circle, sphere, cube, cylinder) inside a unit wrapping space, **no raymarching**, at least axis aligned.

The goal is to write a shader. The benefit, is that, since it's analytic, I can do trick by passing parameters with the texture per pixel.

I already do this by abusing simpler variants of of interior design, by cranking the space between side low, and get dense (simple) foliage and grass for free, or brick walls, or any greebles. **Except I'm confined to simple convex shapes with interior style shader**, with this I could have more interesting parallax to abuse **artistically**. I use the flow of the polygon surface to create interesting shapes, and UV texture to break pattern artistically. Work wonder for low specs machine!

I figure out how to do it with a single point at the boundaries of the space, using the planet alignment problem (akin to the two clock hand overlap problem). But I failed to generalized it.

This problem is similar to this math problem https://amininima.wordpress.com/2013/05/27/the-laser-gun/

But without the reflection.

Other potential benefits is that it have a period we can find mathematically, we could probably infer an analytical "overdraw", by "discarding depth" have a "traversed thickness", if we generalized the, such as we can also shift the position of the primitive at each "jump", we could probably find a consistent "integral 3D noise", which would made cloud noise in convex volume much cheaper than marching.

> *Optionally* "the graal" would be at least 1 period coil repeated on axis aligned. But we can't intersect cosine "cheaply", I tried using x² approximations but my math melted. A unit coil being an unwrap unit cylinder diagonal, was the next step explored, ie to intersect axis aligned cylinder then find on its surface the diagonal:  the idea above is, taking the perpendicular going through the cylinder center, we observe that the tracing "regularly" step through it, using that stepping and the slope of the ray, we can infer point on the wrapping surface of the cylinder, the entire idea is to find the step pattern so we can intersect the diagonal within a certain distance.

EDIT: While talking below in the comment, I realized that I probably could shift the 1D wrapping space to the 2D projection of the ray direction, then find the period of the primitive's "axis" projected on that line, and since I already found the case for 1D, use that to infer the remaining intersection. Just an idea not developed yet. Should make a drawing to show what I mean, it's not clear yet in words.

# Answer
> 1 votes
**I haven't found a proper implementable solution yet**, but I think I'm getting very close, at least solving it visually, I just can't make the jump to the final implementation, I'm not good at math at all...

Initially I tried to simplify the problem to a point at the corner of the 2d grid. This essentially collapse the problem to 1d problem, if we project boundaries intercept of the ray on one of the axis, it turn into a series of points at regular interval, the solution is to find when one of these points overlap the corner position, basically it's like having two beats at different frequency and guessing when they play at the same time. Since we are now in 1d, I can assimilate the wrapping space to a circle, and suddenly the problem looks like the clock hands overlap problem (or the planet alignment problem)... TO WHICH google have some ready made solution for me, so by using the grid size as a rate and the ray delta as another we get a solution.

**Points being infinitely small it's not very useful** yet, it was just about finding insight. That insight came in realizing that the solution is basically scaling the grid size by the step size to find a common period an, and dividing it by the difference of rates between the delta and the grid size, so grid size can be assimilate to a rate or period, the whole grid is basically a frequency.

That solution also looked an awful lot like a DDA used in raycasting old wolfenstein level (cell size/ray step). That's the second insight, that the DDA itself can be interpreted as a specific implementation of the recurrent primitive intersection problem, except that recurrent primitive is an axis aligned plan, we basically compute the recurrent intersection of the planes in the direction of the ray casted. And also we ONLY need to compute the set of primitive in the direction of the ray.

The intercept solution for a single sphere is to project the sphere center to the ray casted line, then use that point to compute a length to compare to the radius size, if the length is bigger we miss, otherwise it's a hit. In our case, the variation of that length across the grid should be the delta needed to compute the period of hit and miss, **ideally**.

When we look at the schema, the first insight is that ALL projection lines are parallel, and perpendicular to the ray, that evoke thales theorem a lot, and it seems to hint that the solution could be along simple trigonometry. However the inconsistent integer stepping of the "DDA" make it hard to generalize.

Up until I realize one thing that turn the whole thing much simpler, I only need to unwrap the space in the direction of the major axis, as it collapse the DDA to a single line using the wrapping of the ray casted, which mean we also have a new period of the vertical wrapping of the ray, everything become close to a 1D problem again ...

First observation is that all projections lines (pink lines) are basically all the same, they have the same direction and goes through the same points in unwrap space. That mean they are all constant and can be reduce to a constant interval within the cell space, so we have 3 nested intervals: the cell size itself, the boundaries intercepts of the projection lines and the projected radius range along the projection line.

As noticed the ray boundaries intercepts define a constant range, BUT that range isn't synced to cell size and it's nested ranges. Also the ray range have varying offset relative to the cell position.

The solution lie in the delta of the recurrent intersection of the ray relative to the projection line. Basically since everything is linear, the delta SHOULD be constant, and therefore a simple stepping along the projection line distance. Basically dividing that distance (from the first hit on that line) by the computed delta, assuming the direction of the stepping also wrap nicely along the projection line (in the infinite unwrapped space the projection line does not).

It's basically like finding when the intersection get into the projected radius ranges. HOWEVER **a simple division don't define when the step JUMPS over the interval, I have no idea how to handle that specific case yet ...**

There is still an awful lot of thales and trigonometry looking structures, I just hasn't figured out how to properly find the relevant one yet ...

I'm almost there, the math don't look complicated, I just don't have the education to figure it out yet :(

---
Tags: mathematics, fragment-shader, raytracing
---


# Question
Title: (LibGDX) Set actor to fixed position on TiledMap
How can I set an actor to an absolute / fixed position on my TiledMap, such that it does not follow the camera when I pan around?

Currently my code looks like:

```
camera = new OrthographicCamera();
rootGroup = new Group();

castleMap = new TmxMapLoader().load("castleMap.tmx");
isoMapRenderer = new IsometricTiledMapRenderer(castleMap, 1/32f);

...

final FitViewport fitViewport = new FitViewport(worldWidth, worldHeight);
stage = new Stage(fitViewport);
rootGroup.setSize(stage.getWidth(), stage.getHeight());
stage.addActor(rootGroup);

barracks = new Barracks(barracksIcon, self);
rootGroup.addActor(barracks);

```

From there, whether I try to position the barracks actor using

```
barracks.setPosition(x, y);

```

or using

```
Vector2 vector = new Vector2(x, y);
vector = stage.screenToStageCoordinates(vector);
vector = rootGroup.stageToLocalCoordinates(vector);
barracks.setPosition(vector.x, vector.y);

```

I get the same result.

I emphatically do not want to use Tables.

Thanks in advance!

# Answer
> 0 votes
This seems too silly to be correct, but I achieved the desired result with the following:

In the method that handles the camera moving...

```
stage.addListener(new DragListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }
        @Override
        public void touchDragged(InputEvent event, float screenX, float screenY, int pointer) {
            final float x = Gdx.input.getDeltaX() * .05f;
            final float y = Gdx.input.getDeltaY() * .05f;

            camera.translate(-x,y);
            camera.update();

            final float destinationX = rootGroup.getX() + x;
            final float destinationY = rootGroup.getY() - y;

            rootGroup.setPosition(destinationX, destinationY);
            stage.act();
            stage.draw();
        }
    });

```

Rather than "setting" the object (or in this case, it's parent Group()) to a fixed position on the map, I dynamically move the entire group relative to the camera in real-time.

---
Tags: java, libgdx, scene2d
---


title: Multiple events based on in-game timer?

text:
# Question
Title: Multiple events based on in-game timer?
I've been thinking about how Zelda: Majora's Mask manages all its character events during the day and thinking about the best way to implement this. Initially I thought of each character entity polling the timer, or the timer sending out events to subscribers of it, but both of these seem wasteful. What are some approaches to solving this?

# Answer
You're overthinking this. Polling the in-game time each frame is *nothing* compared to the other things your CPU does each frame. You would need **millions upon millions** of entities to see the a performance impact (think about it, your CPU runs on **Giga**herz speed. That means billions of operations each second). Just check each frame if the time is what the entity expects and then act on it:

```
if getGameTime() == timeOfDay("12:00"):
    ...

```
> 2 votes

# Answer
You can also have a master "Schedule" that acts as a priority queue. This automatically sorts the next item to occur so that it's the first item in the collection (often more cheaply than sorting the whole collection on every addition).

Each thing that needs to happen can register its next occurrence in the schedule along with a payload of what to do at that time - like setting a trigger/flag variable or firing an event or calling a callback method.

Each frame, your scheduler checks the timestamp of the next item in the queue against the current time. If it's still in the future, it leaves it alone. Otherwise, it pops it out of the queue and executes its payload. It keeps popping scheduled items out of the queue until it hits an item that still belongs in the future, and at that point returns back to the main game loop until next frame's schedule update.

This reduces the workload from being proportional to the number of events to being proportional to the number of events that occur/schedule themselves on a single frame.

If your schedule is unchanging, you can instead just make one sorted list, and keep track of your current index in the list, advancing the index (and wrapping around for the next day) rather than popping items from the priority queue.
> 2 votes

# Answer
If you want to retain separation of concerns in an object-oriented system, and want a high amount of flexibility in how objects react to time, this would be a good use case for the Observer Pattern and the Reactive Extensions for your chosen programming language. (Although the pattern can be implemented without the extensions, it does handle some of the plumbing.)

The advantage of the observer pattern for your use case is that you can have one object that is a "clock" that all other objects can observe. The clock only ticks; it generates observable events at a set cadence (which can and should be independent of frame rate, as all game logic should be in most situations). Other objects that care about time can observe these ticks, which could be a payload with any amount of information (current in-game time, for example). This allows you to reuse the functionality among multiple classes and have one central "clock".

From there, you can wire up your observer classes. The Clock Tower can be wired up to the clock to display the time, and each other object that needs to react to time-based events can observe the central clock and react accordingly. This keeps behaviors associated with their owning classes and allows for the clock to be swapped out for any other compatible Observable (which eases testing, as you can make clocks for specific tests and your classes won't know the difference). This will ensure that every object knows exactly what time it is according to the central clock and stays in-sync.
> 0 votes

---
Tags: events, timer, time
---


# Question
Title: How can I fix the "fisheye" distortion in my raycast renderer?
I've just started making a 'raycast' engine, a pseudo 3D FPS engine similar to Wolfenstein/Doom. I haven't done much reading so my implementation is likely very naive.

My current working prototype has a 'fisheye' distortion \[2nd image\] which makes sense because the middle of the wall is closer than the far edges, but this is not how Doom looks.

What's the right way to do this? an orthogonal projection seems wrong because you would lose the foreshortening.

# Answer
You need to use the *range* instead of the *distance* when you cast the ray. The range is the length of the projection of the ray onto the camera plane.

See this source.

Though IMHO some amount of fisheye distortion is kind of cool to keep around.
> 8 votes

# Answer
Typically, you wouldn't space your rays at even angles. This is the source of the distortion. See this answer for details: https://gamedev.stackexchange.com/a/156853
> 3 votes

---
Tags: 3d, raycasting, 2.5d, raytracing
---


# Question
Title: How to rotate and move an object in precise time frame
My task is to rotate and move an object into a new position and rotation in a given time. Say I have to move a cube from `(0,0,0)|(0,0,0)` to `(1,1,1)|(0,90,0)` in 5 seconds. Could anyone explain to me please how to achieve that?

My experiment is:

```
private IEnumerator DoMove(/*float time, Vector3 targetPosition*/)
{
    foreach(WayPoints wp in tposes)
    {
        float counter = 0;
        float duration = wp.timeStamp;
        while (counter < duration)
        {
            counter += Time.deltaTime;
            Vector3 curpos = cube.transform.position;
            Quaternion crot = cube.transform.rotation;
            float time = Vector3.Distance(curpos, wp.position.position) / (duration - counter) * Time.deltaTime;
            cube.transform.position = Vector3.MoveTowards(curpos, wp.position.position, time);
            cube.transform.rotation = Quaternion.Lerp(crot, wp.position.rotation, time);
            yield return null;
        }
        Debug.Log("Reached position: " + wp.position.position + " in time: " + Time.time);
    }
}

```

The cube gets to its position in time, but rotation is late. The end position of the cube should be `(2,2,2)|(0,120,0)`, but it stops moving at `(2,2,2)|(0,~110,0)`.

There are two positions I want the cube to be in:

* `(1,1,1)|(0,90,0)` in 5 seconds
* `(2,2,2)|(0,120,0)` in next 4 seconds

# Answer
> 0 votes
Answer was found. I forgot to calculate time steps for rotation as well. Now code looks like:

```
 private IEnumerator DoMove()
    {
        foreach(WayPoints wp in tposes)
        {
            float counter = 0;
            float duration = wp.timeStamp;
            while (counter < duration)
            {
                counter += Time.deltaTime;
                Vector3 curpos = cube.transform.position;
                Quaternion crot = cube.transform.rotation;
                float time = Vector3.Distance(curpos, wp.position.position) / (duration - counter) * Time.deltaTime;
                float rtime = Quaternion.Angle(crot, wp.position.rotation) / (duration - counter) * Time.deltaTime;
                cube.transform.position = Vector3.MoveTowards(curpos, wp.position.position, time);
                cube.transform.rotation = Quaternion.RotateTowards(crot, wp.position.rotation, rtime);
                yield return null;
            }
            Debug.Log("Reached position: " + cube.transform.position + "|" + cube.transform.rotation.eulerAngles +" in time: " + Time.time);
            Debug.Break();
        }

    }

```

One row did the stuff:

```
float rtime = Quaternion.Angle(crot, wp.position.rotation) / (duration - counter) * Time.deltaTime;

```

Thank you for the comments

---
Tags: unity, c#, rotation, motion
---


# Question
Title: Is it better to create a scene in blender or in unity?
First of all, I am really new to all of this. This is my first time so its really confusing me if it's better to create a scene and then import it into Unity or is it better to just create objects like chracters, chairs in blender and scenes in Unity? I just want to recreate a scene of my school and include it in my final project as a Unity game where it will have no function other than walking around and some jumping and fighting? Because my project is not based on the game, it will just help it.

# Answer
> 3 votes
There's nothing wrong to creating your scene in blender and then importing it to Unity, in fact you can directly import the blender file and get the lighting just as you did in blender, but the way unity and blender renders the scene is different, so none of the post processing effects will get transferred to unity, and you'll have to tweak a lot of stuff in unity to get the look you want, I suggest you to make your assets in Blender if you feel it's faster to work with, and then export it to unity and setup the rest as per your preferences. It can be a bit of confusing at first but it all comes down to your personal preferences.

Here are a few tips:

* Split objects wisely in Blender Keep different .blend files or at least .fbx files for each object Keep your objects at the center of space, their scales applied (scale of 1), and rotation applied (rotate -90 degrees around the x-axis then Ctrl-A apply rot to fix the Blender --\> Unity axis issue: you can rotate back 90 degrees so that in Blender it has a 90 degree rot around x-axis but be oriented correctly) Remember materials in Blender are only used to create the material NAME in Unity (and bake out textures)
* DO NOT overwrite materials in Unity -- just adapt the blank materials imported from Blender

Example: You are working on a simple scene that has a room with a table, chair and character. So in Blender create and save a file with a complete room model (without the furnishings). Next, make and save a table file with a table model with all the details (perhaps a couple knives, forks, and plates). Make and save a chair .blend and then a separate character .blend...this continues until you are done with objects needed for your scene. Of course, all of these would be saved in a "room scene" folder (outside of your Unity project). Export all the models as .fbx files. Finally, import these into Unity with their (named) materials and import your textures...put the objects together in our scene and setup lighting, cameras, particle FX...

Example 2: You are working on a game that programmatically generates levels (ie. dungeons, mazes). The best thing to do for this type of game is to create modular components that get generated by scripting. These components would be something like a hallway piece, a room piece, a turning hall etc.. To make these, model a base for the wall and floor maybe structural details (windows, doors...), then save that as a file and of course export to an .fbx for Unity. Make some detail objects like mentioned in example 2 then import the models into Unity. Create prefabs for hallway, room...by parenting the details to the base, then instantiate the prefabs from a script.

# Answer
> 0 votes
As mentioned in the comments, there's no perfect way and depending on your project and its design, either might work.

However, I immediately had to think about a YouTube video: In the **Boundary Break** episode about Telltale Games's **The Walking Dead Season 1** one of the original developers speaks a bit about their experiences of creating whole scenes for the game on a 3D editor rather than their game engine:

https://www.youtube.com/watch?v=plA5DFv7VcU

# Answer
> 0 votes
If this is a project that other people will eventually work on, there's a good reason to create individual assets in Blender but assemble the scene in Unity: this is likely to make the project more accessible for other developers who have Unity experience but not Blender experience. The Unity Editor is targeted at game designers, level designers, and developers. Blender is targeted at 3D artists. Many Unity developers who are comfortable assembling scenes, setting up materials, etc in the Unity Editor may not have any idea how to use Blender and may struggle with learning its more complex user interface and material settings. Team members who are learning Blender for the first time may get frustrated with online tutorials, as the Blender team has completely redesigned the entire UI several times and it's extremely difficult to follow older tutorials in the newest interface.

---
Tags: unity, game-design, blender, scene
---


# Question
Title: Detect a collision between a CharacterController and a 3D Object?
I am making an XR game, and I am stuck with a part. Does anyone know a function that would detect this? `OnCollisionEnter` and `OnTriggerEnter` don't appear to work with a CharacterController. Can anyone help?

# Answer
`OnCollisionEnter` and `OnTriggerEnter` require both objects to have colliders and at least one of the objects to have a Rigidbody. You might also try `OnControllerColliderHit`, which is documented here.
> 0 votes

---
Tags: unity, c#, gameobject, character-controller
---