# Question
Title: How to implement C# methods that automatically get called in the game loop, like Unity's Update() etc.?
I've been working on my own game engine for some time, I ideally need a way to create global function implementations to make it easy to do things within the game loop.

Heres an example:

```
void Start()
{

}

```

This one is pulled from Unity, as you can see there is no need to override any methods.

The current method I have is just to implement a base class, say `Loop` and then have all classes that want to implement loop override the functions, like `Render()` and `Init()`, the problem with this is that you instantiate an Instance of the class when you implement it, meaning there may be multiple game loops running simultaneously and out of sync. Also since it's a class instance you have to start it somehow:

```
internal static class Loop
{
    public static void Start()
    {
        Init();

        Load();

        while (!Glfw.WindowShouldClose(WindowManager.Window))
        {
            Update();

            Render();
        }
    }

    public static void Init();
    public static void Load();
    public static void Update();
    public static void Render();
}

```

(By the way that code doesn't actually work)

See the normal game loop is in a seperate class that gets started when the application opens as you can see below:

```
internal abstract class Game
{
    protected int InitialWindowWidth { get; set; }
    protected int InitialWindowHeight { get; set; }
    protected string InitialWindowTitle { get; set; }

    public Game(int initialWindowWidth, int initialWindowHeight, string initialWindowTitle)
    {
        InitialWindowWidth = initialWindowWidth;
        InitialWindowHeight = initialWindowHeight;
        InitialWindowTitle = initialWindowTitle;
    }

    public void Run()
    {
        if (InitialWindowTitle == string.Empty)
        {
            InitialWindowTitle = $"{Application.AppName} {Application.AppVersion}";
        }

        Init();

        WindowManager.CreateWindow(InitialWindowWidth, InitialWindowHeight, InitialWindowTitle);

        Load();

        while (!Glfw.WindowShouldClose(WindowManager.Window))
        {
            Time.DeltaTime = (float)Glfw.Time - Time.ElapsedTime;
            Time.ElapsedTime = (float)Glfw.Time;
            Update();
            Glfw.PollEvents();
            Render();
        }

        WindowManager.CloseWindow();
    }

    protected abstract void Init();
    protected abstract void Load();
    protected abstract void Update();
    protected abstract void Render();
}

```

However this method also requires overrides, and also requires you to initialize or start it through 'public void run'.

So how can I make something similar to Unity's. I'm pretty sure Unity does it through external dlls or c++, but that's okay, I can also work slightly with c++ and creating dlls.

# Answer
The key idea is that each class with game loop event/message methods does not implement its own game loop.

Instead, the engine core implements **one central game loop**. Then each component that needs to be updated goes through a **registration** process to add it to the **collection** of objects that get updated in that central game loop.

In Unity, this happens under the hood when you call `AddComponent()`, `Instantiate()`, or `GameObject.CreatePrimitive()` — and it's part of why component behaviours don't work correctly when you try to create them directly with a `new` constructor — they miss out on this registration step.

Here's a sketch of how we could implement this in a single pure C# assembly:

(This is *far* from the most optimal implementation — just keeping things simple to show the core concept of registering collections of objects that need to get certain method calls at certain times)

```
public class MyComponent : Component, IUpdatable, IRenderable {
    public void Update() {
        // TODO: Updating code here.
    }

    public void Render() {
        // TODO: Rendering code here.
    }
}

public interface IRenderable {
    void Render();
}

public interface IUpdatable() {
    void Update();
}

public partial class GameLoop {

    List<IUpdatable> _toUpdate = new();
    List<IRenderable> _toRender = new();

    public void Register(Component component) {
        var updatable = component as IUpdatable;
        if (updatable != null} _toUpdate.Add(updatable);

        var renderable = component as IRenderable;
        if (renderable != null) _toRender.Add(renderable);
    }

    public void Unregister(Component component) {
        _toUpdate.Remove(component);
        _toRender.Remove(component);
    }

    public void LoopUntilQuit() {
        while (!ShouldQuit()) {
            UpdateTimeStep();

            foreach (var updatable in _toUpdate)
               updatable.Update();

            foreach (var renderable in _toRender)
               renderable.Render();

            FinishFrameAndWaitForNext();
        }
    }
}

```

Unity doesn't work quite like this, since the core engine is written in C++, and it loads the managed assembly. In that process, it can inspect your types to figure out which ones have `Start()` / `Update()` / etc. methods without explicit interface markup. It can do this just once, at start-up, and cache function pointers to those methods so it can call them directly without going through as much indirection/type-checking as the naïve sketch above. And it can sneak past pesky public/private access control, which is why in Unity you don't have to declare these methods as public.

This past Q&A goes into some more detail about the kind of under-the-hood data you can get when inspecting a loaded managed assembly and how you can use it for this purpose.
> 4 votes

# Answer
You can create event handlers, that components can subscribe to; and that are called when that event occurs. This pattern is most suitable when you have multiple "subscribers" that "attach" (and maybe detach).

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-publish-events-that-conform-to-net-framework-guidelines

Or you can use a Delegate or Action, which is simpler to use for a single callback.

https://learn.microsoft.com/en-US/dotnet/csharp/programming-guide/delegates/using-delegates

https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=net-8.0
> 1 votes

---
Tags: c#, software-engineering, game-loop
---


# Question
Title: Why are my angle calculations not working properly?
I am using this code:

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

public class HARcieveAngleChanger : MonoBehaviour
{
    private float ha;
    private float HAZ;
    public ConfigurableJoint CJ;
    public Vector3 newanchor;
    public Vector3 newaxis;

    public void OnValueChangedHA(float newValue)
    {
        ha = (HAGrab.HAUpdate);
        UnityEngine.Debug.Log("ha WHAT YO DOING = " + ha);
        HAZ =(float)0.8 * (Mathf.Tan(ha))  ;
        UnityEngine.Debug.Log("HAZ WHAT YO DOING = " + HAZ);
        transform.position = new Vector3(0,0, HAZ);
        newanchor.y = (float)-8;
        newanchor.z = -HAZ;
        newaxis.y = (float)8;
        newaxis.z = HAZ;
        CJ.connectedAnchor = newanchor;
        CJ.secondaryAxis = newaxis;

    }

}

```

From the `debug.log(ha)`, I am getting 45 when I enter a 45 value into the input UI. The `HAGrab` code gets this. However, the value outputted for `HAZ` always comes out incorrect (i.e. using trig TOA, `tan(angle)*length` of alternate side = opposite side, with a 45 degree angle it should come out as 0.8)...

Does anyone have any ideas for why this is the case?

# Answer
> 0 votes
To convert degrees to radians, you need to multiply the angle in degrees by Mathf.PI / 180.0f.

```
HAZ = (float)0.8 * Mathf.Tan((ha * Mathf.PI) / 180.0f);

```

---
Tags: unity, c#, trigonometry, angles
---


# Question
Title: Circle to Polygon & Circle to Circle Velocity Resolution
I am working a 2d physics engine.

Polygon to polygon collision and velocity resolution works without issue, but I am struggling to get working circle to circle and circle to polygon velocity working as expected.

Here is a video the current version: https://www.youtube.com/watch?v=jVHN9Or9b1g.
As shown in the video, the angular velocity of the circles does not change upon collision.

Here is what should happen upon collision:

Assistance would be much appreciated.

# Answer
One answer is too short to cover all the concepts. So to maybe help you gather your thoughts...

This answer will represent the use of 2D vector cross and dot products to extract the two vectors that represent imparted linear and angular forces from a calculated collision vector at the point of collision.

There are subtle differences between 3D and 2D solutions, I will assume you are wanting a 2D solution. Most of this answer applies to both 2D and 3D, but a 3D problem needs to be simplified to a 2D solution before it can be solved and is not included.

## Simplify

You show 3 illustrations and your language implies you see them as three different solutions. However you can see them as 3 examples of the same problem. A problem we can ultimately simplify to three points, two vectors, and two scalars.

Lets' assume that the

* collision is at a single infinitesimally small instance of time,
* that there is a single infinitesimally small point of contact between the two objects,
* that both objects have a velocity vector **v** and angular velocity **w**.

I will use v and w as subscripts for algebraic representations.
* that the points **A** and **B** (See Fig1) are at the center of mass of the two objects
* That the mass of both objects are equal (or are substituted with the unit value 1)
* that the problem is 2D

**Note** You say in the comments *"...circle has no angular velocity..."* There is no reason to make a special case for zero angular velocity.

To help visualize the problem see the following illustration fig1.

## A collision between two objects

fig1

* **Av** **Bv** linear velocities
* **Aw** **Bw** angular velocities
* **Avw** derived surface velocity (missing Bvw)

All motion is relative, the above image is from an outside perspective, however we will reduce the problem to objects' **A** point of view.

## Vector math

The most important details you make no mention of in your question, the point **C** (point of contact) and the Normal (along the line from **A**s' center of mass and the point of contact) and Tangent (At 90deg to the normal) vectors

I will assume you are familiar with vectors but not practiced. The **Normal** and **Tangent** are vectors onto which we will project the various relevant vectors derived from the problem (namely **Av**, **Bv**, **Awv** derived from **Aw** and **Bwv** (not illustrated) derived from **Bw**.

In fig2 we remove the objects and show the tangent and normal vectors. We have an arbitrary vector **V** that will be projected onto the normal and tangent vectors.

The orientation of the vectors are irrelevant as shown in the inset fig2 (rotates all vectors to align the tangent with the x Axis)

fig2

## Dot and Cross

These two algebraically operation should become second nature to game programmers, they represent much more than is illustrated in this answer.

#### Dot

We use the dot product of two vectors to project the second vector onto the first (See fig2 **V** projected as **Vi**)

Dot product is written algebraically as A⋅B where A is the **tangent** and B is the vector **V**

As pseudo code (unknowns as `?`)

```
A = {x: ?, y: ?}   // 2D Vector
B = {x: ?, y: ?}   // 2D Vector
dot = A.x * B.x + A.y * B.y  // Scalar value

```

#### Cross

We use the cross product of two vectors to project the second vector onto the vector at 90 deg from the first (See fig2 **V** projected as **Vj**)

Cross product is written algebraically as A⨯B where A is the **tangent** and B is the vector **V** the result is the projection of **V** onto the **normal**

As pseudo code (unknowns as `?`)

```
A = {x: ?, y: ?}   // 2D Vector
B = {x: ?, y: ?}   // 2D Vector
cross = A.x * B.y - A.y * B.x  // Scalar value

```

#### Scalar results

The dot and cross product return a single value (not vectors) and represent the relative length of the project vector along the resulting axis. Kind of but more (Area of Parallelogram created by the two vectors, sin and cos of angle between the two vectors (if both are normalized), and more abstract values)

## Applying forces

From fig1

* the **Tangent** vector represents the direction of the forces that apply rotational acceleration.
* the **Normal** vector represents the direction of the forces that apply linear acceleration.

We will create a single vector representing all the velocities (thus forces) involved.

Which we will call **Cv** the result of adding **Av** \+ **Bv** \+ (**Awv** at point **C**) + (**Bwv** at point **C**)

**Note** that **Awv** and **Bwv** will be the along the tangent vector at **C**.

Now we have one vector **Cv**

**Note** to simplify the explanation I will normalize the **Tangent** and **Normal** vectors. From here on they represent unit vectors along the tangent (**Tv**) and normal (**Nv**). In practice there is no need to normalize, operations that would increase code source complexity and CPU load.

#### Change in linear velocity as a vector

To calculate the amount of force as a vector that will change the linear velocity of **A** we will scale the vector (**Nv**) by the cross product of **CvTv** to get a result vector as **C1v**

#### Change in angular velocity as a scalar

To calculate the amount of force as a vector that will change the angular velocity of **A** we will scale the vector (**Tv**) by the dot product of **CvTv** to get a result vector as **C1wv**

We add **C1v** to **Av**

We convert **C1wv** to angular velocity **C1w** and add it to **Aw** (you must account for distance **C** is from center of mass)

(Sorry for collisions I use an unconventional alignment (i hat along tangent))

## Done?

No not by a long shot. However the basics are there. The use of dot and cross product to extract the linear and rotational force vectors from a single collisional vector is the fundamental part of the solution.

Getting the collision vector will depend on mass, friction/s, etc... applying the resulting linear and angular values will also depend on inertia, restitution, and more

## References

For more and detail information some wiki links.
> 0 votes

---
Tags: 2d, physics, movement, collision-resolution, physics-engine
---


# Question
Title: Adding a function call to a prefabbed button in Unity
For each of my scenes, I have an empty GameObject `_Manager` that stores my scripts for setting up the level, keeping track of variables, etc.

On my main screen, I have a play button that isn't instantiated; I simply dragged it into the editor. In my script `Main.cs` I have a function `Play()` which calls `LoadLevel("Game")`. To get my play button to call the Play function, I dragged `_Manager` into the onClick slot and selected the function. This worked fine and I have a functional play button.

Unfortunately, this is not working for the prefabbed buttons I need to instantaite in my Game scene. In `Game.cs` I have a function `LayoutButtons()` which is both public and returns void, yet I am unable to drag `_Manager` into the slot on my prefabbed button. Even if I do it before converting the button to a prefab, it simply disappears once it becomes a prefab.

I've managed to work around this by putting my `LayoutButtons()` function in a new script which I attached directly to the prefab, but I'd like to keep the function within `Game.cs` and attached to my manager object if that's possible.

# Answer
You want to Setup play as a public void Play() so when you drag the manager to the click event you can see Play() on the list.

Edit: If you are using a prefabbed button you want to also use a prefabbed manager and drag that into the button click event to work properly.

```
public void Play()
{
     LoadLevel("Game");
}

```
> 1 votes

# Answer
If you instantiate the button you can get a reference to it, like `GameObject _Button = Instantiate(_ButtonPrefab)` and then you can call `_Button.AddListener(//A Method on this script)` to add a new method to the button, which just does the same as clicking on the plus, dragging in a game object and choosing a method.

I don't know if this is still helpful for you or not, but it's better to use `SceneManager` to load scenes, instead of `LoadLevel`, because `LoadLevel` is old.
> 1 votes

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