# Question
Title: How do I draw a world rectangle as a GUI
I would like to draw a perspective green rectangle that glows (=it constantly changes its alpha between 0 an 1).

I already achieved this, but not as a GUI element, but as a real 3D object.

In order to show this rectangle in front of everything else, I have to turn this into a GUI element. And I don't know how I would draw a perspective rectangle that constantly changes its alpha on the GUI.

I do not only mean the math behind it, but also how to do it exacetly: Do I use actual materials, or do I use an image in the size of the green box?

Thank you.

Edit:

This is what I'm trying to rebuild:

# Answer
I recommend always asking about your goal, rather than the method you think might help you achieve your goal. ie. "How can I draw a rectangle over 3D content that's in front of it in HDRP?" rather than "How do I draw a world rectangle as GUI?"

This avoids the X/Y problem, helping you get the outcome you want without distractions or unnecessary constraints. You'll often get solutions much easier than the way you thought of so far.

Here, I think using the GUI is a red herring. We can do this much more easily using shaders.

Create a new unlit shader (the old way - we don't need a shader graph to work with HDRP if we're not using lighting for this effect), and modify it like so:

```
// I called mine "Always in Front"
Shader "Unlit/AlwaysInFront"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        // Add a color tint parameter so you can get your desired green.
        _Color ("Color", color) = (1, 1, 1, 1)
    }
    SubShader
    {
        // Add the transparent queue to render after the opaque objects.
        // You can use "Queue"="Transparent+100" if you need to get in front
        // of other stuff in the transparent queue, like a worldspace Canvas.
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        LOD 100

        // Turn off the depth test, so we don't hide occluded fragments.
        // And also disable Z writes so we don't muck up the depth buffer.
        ZTest Off
        ZWrite Off
        // Enable alpha blending for transparency. You could use premultiplied
        // alpha here if you want to tint and glow with one pass.
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            // I stripped out the fog sections since I don't expect to need them.
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            // Add color parameter.
            fixed4 _Color;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Tint the texture using our color.
                fixed4 col = tex2D(_MainTex, i.uv) * _Color;

                return col;
            }
            ENDCG
        }
    }
}

```

Here's the result in the HDRP test scene. The green quad is actually behind the workbench, and parallaxes as you'd expect for an object at that position, but renders over the opaque 3D objects in front of it. I also added a worldspace canvas with a gun sprite on it, in front of the workbench, to show we can render over worldspace GUI too, even when our quad is behind it.

Screenspace GUI can still layer on top of this for drawing your "E" / "6" markers on top. The "always on top" behaviour applies only to depth-tested objects in the 3D scene drawn before this material in the queues.
> 4 votes

---
Tags: unity
---


# Question
Title: Parsing "pick up" action in a text-based RPG
I’m coding a text-based RPG and I have my controls working: I have a string checking what you write in against an array of `if` statements.

It can get it right with everything other than my pick up action.

My if statements are set out as follows:

```
int game_main() {

    string PlayerOption;

    //I have a few lines of cout statements just for my gui/hud

    cin >> PlayerOption;

    if (PlayerOption == "look") {
        //it’s then just calling a script from a separate header file
    }
    else if (PlayerOption == "pick up") {
        //another script from that header
    }

```

My look command and all my others work but I don’t know how to set it up right.

I've tried putting it like `"pick up"`, I tried it like `"pick"" ""up"` and a couple other ways but I don’t know how to properly write the expression.

Even then my problem might be with my string and not my if statement so any suggestions would be greatly appreciated.

And I think @DMGregory might be right about the word boundaries because even with that command if I make it accept "pick" it works it’s only when I ask it for two words it really breaks

Is there any way I could get around that?

# Answer
> 2 votes
Using `cin` by itself is not going to work in all cases because it automatically stops at whitespace. It will be much easier to grab the whole string at once and parse it into "commands" and "arguments":

```
#include <algorithm>
#include <string>
#include <utility>
#include <vector>

std::vector<std::string> Split(const std::string& string, char delim = ',', bool skip_empty = true) noexcept;
std::pair<std::string, std::vector<std::string>> ParsePlayerOption(const std::string& playeroption);
void Pick(const std::vector<std::string>& args);
void Look(const std::vector<std::string>& args);

std::vector<std::string> Split(const std::string& string, char delim /*= ','*/, bool skip_empty /*= true*/) noexcept {
    std::size_t potential_count = 1 + std::count(string.begin(), string.end(), delim);
    std::vector<std::string> result;
    result.reserve(potential_count);
    std::string curString;

    std::stringstream ss;
    ss.str(string);
    ss.seekg(0);
    ss.seekp(0);
    ss.clear();

    while(std::getline(ss, curString, delim)) {
        if(skip_empty && curString.empty()) continue;
        result.push_back(curString);
    }
    if(!skip_empty && ss.eof() && string.back() == delim) {
        result.push_back(std::string{});
    }
    result.shrink_to_fit();
    return result;
}

std::pair<std::string, std::vector<std::string>> ParsePlayerOption(const std::string& playeroption) {
    const auto first_space_pos = playeroption.find_first_of(' ');
    std::string command = playeroption.substr(0, first_space_pos);
    std::string args_list = playeroption.substr(first_space_pos);
    auto args = Split(args_list, ' ');
    return std::make_pair(command, args);
}

void Pick(const std::vector<std::string>& args) {
    if(args.front() == "up") {
        std::vector<std::string> item_list{args.begin() + 1, args.end()};
        DoPickUp(item_list);
    } else { //Not a "pick up" command. Could be like "pick flower".
        DoPick(args);
    }
}

int game_main() {

    string PlayerOption;

    //I have a few lines of cout statements just for my gui/hud
    std::getline(std::cin, PlayerOption);

    const auto [command,args] = ParsePlayerOption(PlayerOption);

    if (command == “look”) {
        //Do look command
        Look(args); //Trivial to implement
    } else if (command == “pick") {
        //Do partial "pick" command.
        Pick(args);
    }
}

```

# Answer
> 0 votes
Another option: use single word tokens.

Instead of using `pick up` for your command, use `pickup`.

And do the same for the parameters.

This will simplify the parsing, the processing, the documentation, etc. of the game.

---
Tags: c++, input, text-based
---


title: Interpolate and collisions

text:
# Question
Title: Interpolate and collisions
Lets take the simple example of a ball bouncing off a wall. The physics is separated from the display. The physics is set to run at say 20 frames per second and the display is running faster than this (usually something like 60 fps).

In order to have smooth rendering, the render function gets a parameter called alpha that is a percentage (float/double value between 0 and 1) of time elapsed for frame (ie. alpha = accumulator / time\_per\_physics\_frame). And we interpolate using this value:

```
position = currentPosition * alpha + previousPosition * (1 - alpha)

```

This works well when moving from one position to the next. For example, if x = 2 and we moving at dx = 4 at high fps the ball gets rendered at x from 2 to 6.

Now say the ball has x = 2, dx = -4 and there is a wall at x = 0. The physics simulator updates the ball to x = 2, dx = 4 (Collision retains all energy and no elastic properties). So using the above interpolate there is no rendering of the ball hitting the wall.

How can the interpolate function handle things like wall collisions?

# Answer
> 2 votes
I had a similar problem regarding visual interpolation. In my case, I visually predicted physical movement inbetween the current and the next frame using object speeds. The problem was that objects were allowed to visually pass through solid obstacles before the physical simulation got there. There was a simple solution. Instead of trying to predict physical movement, I let my display actually FOLLOW physical simulation. In my case, it was as simple as this:

```
visualPos = actualPos - speed * (1.0 - alpha)

```

While this was my previous interpolation method

```
visualPos = actualPos + speed * alpha

```

That way, collisions were displayed properly.

However, this doesn't seem to provide a solution to your problem. I guess what I'm trying to say is: As long as you're interpolating, your results will never be perfect. In your specific case, I'd suggest increaing physics FPS - 20 seems really low.

# Answer
> 1 votes
Since your physics system presumably generates velocities for objects in addition to positions, you could use a Hermite spline for interpolation rather than just using linear interpolation. The Hermite spline accepts tangent vectors for the beginning and end of the spline, where you can put in the object's velocity.

This should help your example because when the ball goes from x = 2, dx = -4 to x = 2, dx = 4, the cubic spline will have it moving toward the wall then reversing velocity and returning to its original position. It won't quite look like a collision because it will *smoothly* reverse velocity over the duration of the timestep, kinda like a spaceship firing its thrusters to veer away from the wall, rather than hitting the wall and bouncing off - which is a pretty much *discontinuous* change in velocity. However, it's probably still better than the ball just staying in place.

# Answer
> 1 votes
This question still comes up on Google and I came up with a neat way to solve interpolating the location during a collision, so I am posting here in hopes it will help someone else stumbling here.

This is based on a physics system as explained in the Gaffer on games blogs, where you have an accumulator and interpolate positions between the steps.

Essentially what you need to do is interpolate either

A) Between the point before the collision and the point of the collision B) Between the point of the collision and the reflected location.

Whichever you choose is based on if the accumulator is behind or ahead of the collision time.

Here is the complete interpolation code

```
float alpha = physicsSpace.Accumulator / PHYSICS_HZ;
body& body = physicsSpace.Bodies[i];
v3 interpolateFrom = body.PreviousState.Position;
v3 interpolateTo = body.State.Position;
if (body.CollisionCount > 0) {
    collision firstCollision = body.Collisions[0];

    if (alpha <= firstCollision.Time) {
        // Time is the from 0.0f to 1.0f over the hz
        float remainder = firstCollision.Time;
        alpha /= remainder;
        interpolateTo = firstCollision.Point;
    } else {
        float remainder = 1.0f - firstCollision.Time;
        alpha = (alpha - firstCollision.Time) / remainder;
        body.PreviousState.Position = firstCollision.Point;
        body.PreviousState.Velocity = body.State.Velocity;
        interpolateFrom = firstCollision.Point;
    }
}
body.InterpolatedPosition = ((1.0f - alpha) * interpolateFrom) +
                            ((alpha) * interpolateTo);

```

# Answer
> 0 votes
What you're experiencing is a very, very common problem with physics engines. Basically, your object is falling between the cracks that your framerate provides. First it's approaching the wall and then it's inside of the wall, without registering a collision!

There are two solutions to this problem:

* Ducktape it - Use a smaller timestep, which is effectively a higher framerate. If you up the framerate to 60 fps, there are now 6 frames between "before the wall" and "inside the wall". Why is this a ducktape solution? Because your framerate might still not be high enough and you can't up it forever.
* Fix it properly - Don't base your physics on just the current position.

I'm not going to bother explaining the first solution, it's simple enough. If that works for you, great! Many games have shipped with that solution in place.

However, I really want to explain the second solution.

Let's say we have the following situation:

Here, the red ball wants to bounce off the wall. We can see its direction denoted by the blue line. However, this isn't its direction, but its *velocity*, which is `direction * speed`. So, what we have here is the ball's current position and the ball's *future* position, which would be `position + (direction * speed)`.

Now we can deflect our ball using the wall's surface normal:

The important thing to note here: the ball hasn't moved yet. As far as the ball is concerned, it is still in front of a wall.

The code should now look this:

* Ball updates its direction and speed, if necessary.
* Ball calculates its velocity from direction and speed.
* Ball calculates its future position from position and velocity.
* Scene uses Ball's position and future position to determine that Ball will collide with Wall.
* Wall reflects Ball's velocity over its surface normal to create a new future position, a new direction and a new speed for Ball.
* Ball sets its position to future position and updates its direction and speed.

Now your Ball can never fall through the cracks. Even better: multiple objects can collide with Ball and it will hopefully all resolve to 1 future position. However, this will require multiple passes of collision resolving by the Scene.

For further reading, look for "sweep test".

---
Tags: collision-detection, physics, game-mechanics, rendering, interpolation
---


# Question
Title: Representation of trains on a simplified rail grid
I'm working on a hobby game, basically about train dispatcher's job.

(stack: Typescript, phaser.js)

My map is based on a grid, each tile can hold 1 rail tile (well, except junctions, but we can simplify it for now, since junctions are just multiple tiles, from which only one is active).

Example (black is grid, white is rail):

As you can see, we have basically three different tiles: straight rail, 45 degree turn and diagonal rail (which can be also considered straight rail). I don't plan to add more tiles, as you can already build pretty complex setups from these tiles.

On these rails, trains would drive. Each carriage has two "wheels" - positions, where it snaps to a track. This may be seen on the following example from my prototype:

However the existing system (see below) has some issues:

* when a train travels diagonally, sometimes it's x and y coordinates fit in a field than it should (example: traveling from 1|1 to 2|2, but at one point the train's coordinates correspond to the field 1|2 or 2|1).
* axles sometimes get closer or futher away from each other. This has almost no effect on resulting simulation (as the carriage is centered between those two axles), but may cause carriages to be closer or futher away from each other (this effect is visible on the prototype as weell)
* moving the train in a certain direction is handled by a big chunk of code that essentially lists all possibilities of directions and handles it. I'm interested if there's a better way to do it, so I could simplify the code.

I decided that I would improve the core. I'm wondering, what would be the best way to do this?

What I am looking for:

* how to save the rail pieces on the map?
* how to move train (I know it's x, y, speed and acceleration)?
* how to have the train continue to the next piece on the grid?

Current solution (broken in some edge cases, also not ideal):

* each rail piece has it's class (`CurvedRail`, `StraightRail`)
* each rail piece class has method `movePoint`, that accepts `x`, `y`, `direction` and `distance` and returns new point (that is `distance` away from the original point, but also considering track turns). It may also return `delta`, if the movement reached edge of the tile and it needs to be moved futher (on another piece). This is handled by a separate class, that finds the following rail piece and calls `movePoint` with the `delta` instead
* it has issues, because sometimes trains passing diagonal connection don't exactly follow the diagonal, so they instead of ending up on the next diagonal piece, they end up on neighboring horizontal or vertical piece and derail.

One of the issues I may be facing is that tiles are 32x32 pixels, so it's hard to travel exactly in the "middle" of the piece, because it's "between two pixels", and although I'm using decimals, it may be a problem. Is it better to have a grid from odd-sized tiles?

# Answer
> 5 votes
**On tracking**

Your current simulation behaves pretty well, I would say. Because a rail wagon that is halfway a sharp bend, will indeed exhibit the behaviour that the wagon's center is no longer above the track, but next to the track.

**Center of the tile**

Traveling over the exact middle of a 32x32 tile: This is easily accomplished if you were to draw the rails with 2-pixel wide lines. (And the trains as 4 pixel or 6 pixels wide.)

**Encoding**

Encoding the tiles... You need to make a choice on whether your network is directional or not. If all tiles can be traversed in both directions, then there is no distinction between entrances and exits to the tile.

An entry/exit point can fall on any of the four tile corners, or any of the four tile edges.

You can then define a tile with an 8-bit value where a one-bit means a gate is present, and a zero-bit means there is no exit/entry for that location.

If you consider only single-track per file, not all 8-bit values would be valid, only the ones that have 2 bits set to one, and of those, only if the turn is not too sharp.

Take, e.g. the tile below. It would have encoding `00010010b` which is decimal value 34.

In the example network you provided, you would filter out the cases where the turn is too acute. So if there is a gate at bit 1, you only allow the other gate at 4, 5 or 6.

This gives you `( 8 * 3 ) / 2` possible encodings, so just 12 of them. Or 24 if you define your tracks to have a direction (explicit entrance and exit.)

possible encodings:

```
 // 3 cases with gate at 0:
 00001001
 00010001
 00100001

 // 3 cases with gate at 1:
 00010010
 00100010
 01000010

 // 3 cases with gate at 2:
 00100100
 01000100
 10000100

 // 2 remaining cases with gate at 3:
 01001000
 10001000
(00001001) duplicate

 // 1 remaining case with gate at 4:
 10010000
(00010001) duplicate
(00010010) duplicate

```

You could chose to store the tile pattern as this 8-bit value `[0..256)` or as a case number `[0..12)` if you prefer.

**Train Travel**

To move a train (or wagon) between tiles, you would need to keep track of a '*from*' tile and a '*to*' tile. Let's call them tile\_fr and tile\_to.

And then keep a parameter `0 <= t <= 1` that records where on the track the train is.

At t==0, the tail of the wagon is at the start of tile\_fr. At t==q, the nose of the wagon is at the end of tile\_fr, at t==1, the tail of the wagon is at the start of tile\_to.

If `q <= t <= 1` then the wagon is occupying both tile\_fr and tile\_to partly.

When t has reached 1, you need to swap the tiles. Tile\_fr is set to the old tile\_to value, and tile\_to will be assigned the next tile.

**Axle Travel**

As you stated, when consider positions of wheels (axles, really) it gets easier. You track a progression parameter for the rear-axle, and one for the front-axle.

To deal with differences in track-lengths per tile, you can modulate the speed at which you move the axle parameters along the track.

If you define the straight-track piece as having unit length, then you can determine lengths L₁ for the bend, and L₂ for the diagonal track across a cell.

When an axle position parameter is moved along the track, you divide the speed by the track length, so use (v / L₁) to move the parameter along the cell with a bend.

The rationale: On longer pieces of track, you need to take more time to progress from value 0 to value 1, so that you get the same distance per unit of time.

**Alternative Grid**

Let me conclude with describing the approach I used in my train simulation. First off, my tiles are hexagons, not squares. Next, my tracks are splines, not line segments. Last, my tracks are directional, meaning there is an entrance edge (0..5) and an other edge as exit, which MUST NOT be a neighbour of the entrance edge. This gives me 6\*3 or 18 different cases. Each track goes either L, R or S. A nice bonus is that the splines in all three cases (L,R,S) has pretty much the same length, which is not the case in your square-crossings.

Using splines means that there will be no sharp corners, which may or may not be something you want. If you do, look into Hermite Splines, for example.

---
Tags: javascript, grid, typescript
---


# Question
Title: Hidden copies of the environment in an entity component system
For reasons outside the scope of this question, my game has several full copies of the game environment running asynchronously. At any one time, only one of these is rendered.

This is trivial to support in a traditional, object-oriented architecture. Instantiate a few copies of the environment, run each one in its own thread (I actually use a parallel task system for cases where there are more environments than CPU cores), and only call call `draw()` on the one you want rendered.

The time for large refactorings has come, and I'm considering converting to an entity component system such as Entt. What would be the best way to achieve this same functionality?

The best I've come up with is each environment being a self-contained ECS, managed by an object-oriented system (which would also handle things not replicated, such as UI). The render system would be disabled in all environments except the one being rendered.

I don't like that solution though. I don't want the render system for the game environments to be separate from that of the UI, etc. I also don't like the idea of mixing ECS and object-oriented architectures.

Is there a better solution?

# Answer
I presume since you want a system similar to Entt you're writing in C++.

## Environment Rendering

One of the simplest solutions you may find for the rendering system would be a simple boolean property on the environment class something like IsSelected or IsActive to represent which one is selected for render.

The relevant class handling your environments would then simply need an if statement encapsulated in a for each statement to evaluate whether or not to render based on that properties state as well as any other logic you want executed differently based on states of the object such as disabling the render system. You may want to use Events or perhaps even a more simple approach execute this on the set accessor when the relevant properties change values.

# ECS

The use of a common abstract base class or interface perhaps named something like IRenderObject would be effective here to have a common type to use for both Game Objects/Entities and the UI alike. I think you may prefer the interface pattern here as from what you said it seems like you want to get around the limitations of class inheritance in an object oriented environment.

```
public sealed class Entity : IRenderObject
{
  EntityComponent[] Components { get; } // Could use List<T> here as well or implement IList<T>
}

public abstract class EntityComponent {}

public abstract class UIElement : IRenderObject {}

```

By looking at your question I can tell you're probably going to have to put a lot of thought into class versus structure. As you can see from my example here it is possible to efficiently write ECS in an object oriented environment.

Based on what you said you may want to use structure which is also why I suggested an interface for IRenderObject as I'm sure you're aware structs don't support inheritance however they can implement interfaces.

So in your environment/environment manager classes you'd want to use IRenderObject as a parameter often to support both UI and GameObject/Entity (whatever you're calling it). As stated on page 22 of C++ Succintly

> The difference between a class and a structure in C++ is simply that a structure’s members default to public whereas a class' members default to private. That's it. They are otherwise the same. There is no value-type versus reference-type distinction as there is in C#.

If you are writing this in C# structures would likely save RAM at the cost of excessive CPU time for defining entity. Structures versus Classes is a debate I've seen in various places. That one is of course going to be up to you to decide what's appropriate for how you're doing it. I hope the information I provided above will help you choose what's right for you scenario though.
> 1 votes

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


# Question
Title: The doors lock system is working fine but how can I avoid changing the colors all the time in the Update?
I want it to change the doors lock state but also the colors of the doors Red = locked Green = unlocked either in editor mode or in runtime. But if the method that change the doors colors is not called in the Update it will not work at all. And calling it in the Update seems wrong.

The editor script :

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

[CustomEditor(typeof(DoorsManager))]
public class DoorsLockManagerEditor : Editor
{
    private SerializedProperty _doors;
    private SerializedProperty _globalLockState;

    private bool shouldOverwrite;

    private void OnEnable()
    {
        _doors = serializedObject.FindProperty("Doors");
        _globalLockState = serializedObject.FindProperty("_globalLockState");
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        serializedObject.Update();

        shouldOverwrite = false;

        // Begin a change check here
        EditorGUI.BeginChangeCheck();
        EditorGUILayout.PropertyField(_globalLockState);
        if (EditorGUI.EndChangeCheck())
        {
            // overwrite only once if changed
            shouldOverwrite = true;
        }

        for (int i = 0; i < _doors.arraySize; i++)
        {
            var door = _doors.GetArrayElementAtIndex(i);

            // if door == null the script itself has an error since it can't even find the SerializedProperty
            if (door == null)
            {
                EditorGUILayout.HelpBox("There was an error in the editor script!\nPlease check the log", MessageType.Error);
                Debug.LogError("Couldn't get door property", target);
                return;
            }

            if (door.objectReferenceValue == null) continue;

            var serializedDoor = new SerializedObject(door.objectReferenceValue);

            var lockState = serializedDoor.FindProperty("doorLockState");

            serializedDoor.Update();

            if (lockState == null)
            {
                EditorGUILayout.HelpBox("There was an error in the editor script!\nPlease check the log", MessageType.Error);
                Debug.LogError("Couldn't get lockState property", target);
                return;
            }

            // HERE OVERWRITE
            if (shouldOverwrite)
            {
                lockState.boolValue = _globalLockState.boolValue;
            }
            else
            {
                EditorGUILayout.PropertyField(lockState, new GUIContent("Door " + i + " Lockstate"));
            }

            serializedDoor.ApplyModifiedProperties();
        }

        serializedObject.ApplyModifiedProperties();
    }
}

```

The Doors Manager script :

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

[ExecuteAlways]
public class DoorsManager : MonoBehaviour
{
    [HideInInspector]
    public List<HoriDoorManager> Doors = new List<HoriDoorManager>();

    // The global state
    [SerializeField] private bool _globalLockState;

    // During runtime use a property instead
    public bool GlobalLockState
    {
        get { return _globalLockState; }
        set
        {
            _globalLockState = value;

            // apply it to all doors
            foreach (var door in Doors)
            {
                // now you would need it public again
                // or use the public property you had there
                door.doorLockState = _globalLockState;
            }
        }
    }

    private void Awake()
    {
        var doors = GameObject.FindGameObjectsWithTag("Door");
        Doors = new HoriDoorManager[doors.Length].ToList();

        for (int i = 0; i < doors.Length; i++)
        {
            Doors[i] = doors[i].GetComponent<HoriDoorManager>();
        }
    }
}

```

And the HoriDoorManager script :

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

[ExecuteAlways]
public class HoriDoorManager : MonoBehaviour
{
    public List<DoorHori> doors = new List<DoorHori>();
    public bool doorLockState;

    private void Awake()
    {
        if (transform.parent != null)
        {
            Transform parent = transform.parent;
            var children = parent.GetComponentsInChildren<Transform>();

            if (children != null)
            {
                foreach (Transform door in children)
                {
                    if (door.name == "Door_Left" || door.name == "Door_Right")
                        doors.Add(door.GetComponent<DoorHori>());
                }
            }
            ColorDoors(Color.red, Color.green, doorLockState);
        }
    }

    void OnTriggerEnter()
    {
        if (doorLockState == false)
        {
            if (doors != null)
            {
                for (int i = 0; i < doors.Count; i++)
                {
                    doors[i].OpenDoor();
                }
            }
        }
    }

    private void Update()
    {
        //ColorDoors(Color.red, Color.green, doorLockState);
    }

    private void ColorDoors(Color red, Color green, bool state)
    {
        List<Transform> children = new List<Transform>();

        for (int i = 0; i < doors.Count; i++)
        {
            foreach (Transform child in doors[i].GetComponentsInChildren<Transform>())
            {
                if (child == doors[i].transform)
                    continue;

                var renderer = child.GetComponent<Renderer>();
                renderer.sharedMaterial.shader = Shader.Find("Unlit/ShieldFX");

                if (state == true)
                {
                    renderer.sharedMaterial.SetColor("_MainColor", red);
                    LockState(true);
                }
                else
                {
                    renderer.sharedMaterial.SetColor("_MainColor", green);
                    LockState(false);
                }
            }
        }
    }

    public bool GetLockState
    {
        get { return doorLockState; }
        set { doorLockState = value; }
    }

    private void LockState(bool state)
    {
        var collider = gameObject.GetComponent<BoxCollider>();

        if (state == false)
        {
            collider.size = new Vector3(2.3f, 2.736307f, 2.5f);
            collider.center = new Vector3(0, 1.378154f, 0);
            collider.transform.localPosition = new Vector3(-1.57f, 0, -2.98f);
            collider.isTrigger = true;
        }
        else
        {
            collider.size = new Vector3(2.3f, 2.736307f, 3);
            collider.center = new Vector3(0, 1.378154f, 0);
            collider.transform.localPosition = new Vector3(-1.57f, 0, -2.98f);
            collider.isTrigger = false;
        }
    }
}

```

The DoorsManager script is attached to one empty GameObject. The HoriDoorManager is attached to each door.

The problem is in the HoriDoorManager :

```
private void Update()
        {
            //ColorDoors(Color.red, Color.green, doorLockState);
        }

```

If I'm not using this line in the Updaye it will not work either in editor mode and runtime. If I will use this line it will work in both editor and runtime.

The question is if it's fine to call this method in the Update all the time ? Or somehow to call this method only when changing the door/s lock state either in editor mode or runtime mode ? And how to do it ?

# Answer
> 1 votes
Your intuition is correct. Looping through all the doors every single frame is a lot of unnecessary work.

You need to have an event driven logic here. A door's lock is not something that changes constantly or by itself (unlike an HP value for example), so there's no need to check lock states constantly. You just need to run the `ColorDoors` function when a door is locked or unlocked.

Even better, you can modify your script to run the door its on and give it to all the doors instead of having it in a central door manager script. Then, you won't even have to loop through the doors, the doors themselves will take care of their locks.

You can use the event system to send messages to doors if necessary. Just call the function of the door from somewhere else. You don't ever need a list of doors unless you need persistent storage for their states, which is what a save system would be in place for.

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


# Question
Title: How to script sequential events in GameMaker?
I am wondering if there is an elegant way to script sequential events in GameMaker 2.

In Godot 3.1, it is very easy to chain events together using `yield()` and signals. You just start doing something, yield until it emits a signal that it's done, and then continue your code. I am wondering if there is anything similar in GameMaker 2.

In Godot, for example, if i wanted to spawn an explosion cluster which consisted of 10 explosions, each starting 50 milliseconds after each other, I could do something like this.

```
func create_explosion_cluster(x, y):
    for x in range(10):
        create_explosion(x, y)
        timer = Timer.new()
        add_child(timer)
        timer.wait_time = 0.05
        timer.start()
        yield(timer, "timeout")
        timer.queue_free()

```

I used this method for complex boss behaviors as well. For example,

```
func boss_attack():
    animation_player.play("intro_to_attack")
    yield(animation_player, "animation_finished")
    animation_player.play("attack")
    for x in range(10):
        create_projectile(x, y, vector_to_player)
        timer = Timer.new()
        add_child(timer)
        timer.wait_time = 0.05
        timer.start()
        yield(timer, "timeout")
        timer.queue_free()
    animation_player.play("outro_to_attack")
    yield(animation_player, "animation_finished")`

```

In fact, I use this technique all over the place when I want certain events to follow other events (in transitions, cutscenes, enemy behaviors, etc.)

**Is there a way to script sequential events in GameMaker with similar flexibility as you have in Godot?**

If there is a general design pattern to solve this kind of problem without `yield()`, co-routines, and so on, I'd love to know it.

# Answer
The most portable way to do this in languages without coroutines is to convert the code into a state machine.

For every yield you make a new state. Then you write code that starts from each yield point and executes the code through all paths up until the next yield. And you have to make sure that every variable that needs to persist across a yield does so. Then you can put all of those bits of code in a bit switch statement and add a `state` variable on which you switch:

So taking your `boss_attack`:

```
func boss_attack():
    //start in state 0
    animation_player.play("intro_to_attack")
    yield(animation_player, "animation_finished") //state 1
    animation_player.play("attack")
    for x in range(10):
        create_projectile(x, y, vector_to_player)
        timer = Timer.new()
        add_child(timer)
        timer.wait_time = 0.05
        timer.start()
        yield(timer, "timeout") //state 2
        timer.queue_free()
    animation_player.play("outro_to_attack")
    yield(animation_player, "animation_finished") //state 3

```

This becomes in C-ish pseudocode.

```
//persistent variables.
state = 0;
x = 0;

func boss_attack(){
    switch(state){
    case 0:
        animation_player.play("intro_to_attack");
        state=1;
        onAnimationFinished(boss_attack);
        break;
    case 1:
        animation_player.play("attack")
        x = 1;
        create_projectile(x, y, vector_to_player)
        state = 2
        onTimer(0.05, boss_attack);
        break;
    case 2:
        x = x + 1;
        if(x<=10){
            create_projectile(x, y, vector_to_player)
            state = 2
            onTimer(0.05, boss_attack);
        }else{
            animation_player.play("outro_to_attack")
            state=3;
            onAnimationFinished(boss_attack);
       }
       break;
    case 3:
       state = 0;
       //don't reschedule but prep for next run through.
       break;
    }
}

```

This can be quite a bit more work but is much more flexible
> 1 votes

# Answer
This is so far my idea of handling multiple projectiles/effects shortly after each other.

Perhaps it's not the same flexibility, but I think this can work similair.

Create:

```
defaultTimer = 0.05;
timer = defaultTimer;
defaultAmount = 10;
amount = defaultAmount;

```

Step:

```
if (amount > 0)
{
    if (timer > 0)
    {
        timer -= (1/room_speed)
    }
    else
    {
       //create explosion here
       Instance_Create(/*explosion object*/);
       amount -= 1;
       timer = defaultTimer
    }
}
//setting amount to 10 will set the explosions off again.

```

I can't find anything related to a script timeout in GMS2, I'd love to know though.
> 0 votes

---
Tags: architecture, game-maker, design-patterns, godot
---


title: OpenGL object load in reverse

text:
# Question
Title: OpenGL object load in reverse
I am trying to load a model and it is loading it in reverse. When I am trying to rotate it 180 degrees it changes the lightning as well. I am not sure what I need to do to change the position that eh model is facing when is being loaded.

This is the object loader:

```
if (!submarineShader->load("BasicView", "glslfiles/basicTransformations.vert", "glslfiles/basicTransformations.frag"))
{
    cout << "failed to load shader" << endl;
}
glUseProgram(submarineShader->handle());  // use the shader

glEnable(GL_TEXTURE_2D);

cout << " loading model " << endl;
if (objLoader.loadModel("submarine_/submarine v2/submarine5.obj", model))//returns true if the model is loaded, puts the model in the model parameter
{
    cout << " model loaded " << endl;

    model.calcVertNormalsUsingOctree();

    model.initDrawElements();
    model.initVBO(submarineShader);
    model.deleteVertexFaceData();

}
else
{
    cout << " model failed to load " << endl;
}

```

# Answer
> 0 votes
I fixed the problem by editing my model and with 3dsmax and change it's position.

---
Tags: opengl, c++, rotation, lighting, model-loader
---


# Question
Title: How to handle multiple events in SDL2 and C++?
I'm working on an entity component based game and I ran into this problem. I've got a component called PlayerControlComponent:

```
void PlayerControlComponent::HandleInput() {
    SDL_Event event;
    while(SDL_PollEvent(&event) != 0) {
        if(event.key.keysym.sym == SDLK_RIGHT) {
            Entity->MoveRight();
        }
        else if(event.key.keysym.sym == SDLK_RIGHT) {
            Entity->MoveLeft();
        }
        else {
            Entity->Stay();
        }
    }
}

```

and I've got a GameManager class that handles the input for the window, like if you hit escape it will quit:

```
void GameManager::HandleInput() {
    SDL_Event event;
    while(SDL_PollEvent(&event) != 0) {
        switch(event.key.keysym.sym) {
        case SDL_QUIT:
        case SDLK_ESCAPE:
            Quit();
        }
    }
}

```

After I put everything in my main function, it looks like this:

```
while(GameManager::GetInstance().IsRunning()) {
        //Inputs
        GameManager::GetInstance().HandleInput();
        player->GetComponent<PlayerControlComponent>()->HandleInput();
        //Update, Draw, etc..

```

My problem is that wich ever I put first gets executed only. So in this example the player won't handle inputs. If change it up and put the player first like so:

```
while(GameManager::GetInstance().IsRunning()) {
            //Inputs
            player->GetComponent<PlayerControlComponent>()->HandleInput();
            GameManager::GetInstance().HandleInput();
            //Update, Draw, etc..

```

..my player will move but than the window won't quit if I hit escape. For some reason wich ever input handling function is called first, gets executed. I figured out it has something to do with `SDL_PollEvent()`. So I created a global SDL\_Event variable and changed up the code a bit so there is only 1 `SDL_PollEvent()` call wich happens in main:

```
while(GameManager::GetInstance().IsRunning()) {
        //Inputs
        while(SDL_PollEvent(&event) != 0) {
            GameManager::GetInstance().HandleInput();
            player->GetComponent<PlayerControlComponent>()->HandleInput();
        }
        //Update, Drawing, etc..

```

So as I said, the `event` variable is now global and both `GameManager` and `Player` uses the (only) same `event` variable.b Now everything works fine, but is that really the only option? (If so, than I don't know why would they allow us to declare multiple `SDL_Event`s.) So my question is:

**Is there a way around this, can I handle multiple input events?**

# Answer
> 8 votes
When you run your while loop in each of your HandleInput functions, you're burning through the entire event queue up to that moment in time. So yes, whichever event handler you call first will eat all of the events.

There are a few ways to handle this problem, but obviously, paramount to every possible solution, is the removal of your destructive SDL\_PollEvent while loops every time you want to handle input. The solution most similar to your current implementation would be of this nature:

```
std::vector<SDL_Event>& GetFrameEvents()
{
    static std::vector<SDL_Event> frame_events;
    return frame_events;
}

// main loop
while(running)
{
    SDL_Event event;
    while(SDL_PollEvent(&event) != 0)
    {
        GetFrameEvents().push_back(event);
    }

    // other main loop stuff...

    GetFrameEvents().clear();
}

```

Just loop through frame\_events, which you can retrieve via the global function GetFrameEvents, in your HandleInput functions instead of your while loops on SDL\_PollEvent.

# Answer
> 9 votes
Another (albeit a little more complicated) thing you could do is have your components register for specific event types:

```
class EventHandler {
public:
  using EventCallback = std::function<void(SDL_Event const&)>;

  void register(SDL_EventType type, EventCallback callback) {
    _registeredCallbacks[type].push_back(callback);
  }

  void handleEvents() {
    SDL_Event event;
    while (SDL_PollEvent(&event) != 0) {
      for (auto& cb : _registeredCallbacks[event.type]) {
        cb(event);
      }
    }
  }

private:
  std::map<SDL_EventType, std::vector<EventCallback>> _registeredCallbacks;
};

class GameManager {
public:

  void registerWithEventHandler(EventHandler& handler) {
    handler.register(SDL_KEYUP, [this](SDL_Event const& event){
      if (event.key.keysym.sym == SDLK_ESCAPE) {
        Quit();
      }
    });
    handler.register(SDL_QUIT, [this](SDL_Event const& event){
      Quit();
    });
  }

}

```

And then call `handleEvents()` once per game loop execution. This example uses some C++11-specific features, but you can basically do the same with '03 if you use (member) function pointers or something similar. And with a little more work, you could also register callbacks for single key presses.

# Answer
> 1 votes
You are polling all the events the first time you handle them and not using all cases at that time. That will leave some untouched. Instead of having multiple event polls, have it all processed in one function. (Preferably in your main class or somewhere able to access all things needed to be updated by events)

# Answer
> -1 votes
To handle multiple events, you need to cache them, so they can be dealt with once per frame.

You need an abstraction of a controller, such as a keyboard:

```
class Keyboard
{
private:
    bool pressedBuffer[256];
    bool heldBuffer[256];
public:
    void handleEvent(SDL_Event const& e)
    {
        if (e.type == SDL_KEYDOWN)
        {
            m_pressedBuffer[event.key.keysym.sym] = true;
        }
        else
        {
            m_pressedBuffer[event.key.keysym.sym] = false;
        }
    }
    KeyState getKeyState(Key key)
    {
        if (m_pressedBuffer[(int)key] && !m_heldBuffer[(int)key])
            return KeyState::Pressed;
        if (m_pressedBuffer[key] && m_heldBuffer[key])
            return KeyState::Held;
        if (!m_pressedBuffer[key] && m_heldBuffer[key])
            return KeyState::Released;
        return KeyState::None;
    }
    void update()
    {
        for (int i = 0; i < 256; ++i)
        {
            if (m_pressedBuffer[i])
                m_heldBuffer[i] = true;
            else m_heldBuffer[i] = false;
        }
    }

};

```

Then, in your basic loop:

```
while( SDL_PollEvent( &event ) )
{
    m_controller.handleEvent(event);
}

```

And in your update cycle:

```
App::update(float delta)
{
    if (m_controller.getKeyState(Key::A) == KeyState::Pressed
    && ... //repeat for as many keys as you want)
    {
         //Do something
    }
    m_controller.update();
}

```

The basic idea, is to parse events, and store them as the *state* of the controller.

Then the engine/game can query the state, and make changes to the game state. In this way, you can handle as many different combinations of keypresses, mouse motion etc as you want.

I prefer this approach, as opposed to function callbacks, as it lends itself very well to scripting. But this is just my own personal opinion.

---
Tags: c++, sdl2
---


# Question
Title: UE4.23 - Cast of child of GameUserSettings fails
I've derived GameUserSettings to add a bunch of custom properties to it. I tried making accessible in blueprint by creating a static method that returns the current GameUserSettings cast to my Child Class.

```
 Custom_Settings * Custom_Settings::GetCustom_Settings() {
     return Cast<Custom_Settings>(GEngine->GameUserSettings);
 }

```

Unforunately, the cast fails and returns null, which leads to UE complaining about trying to access none in blueprint (naturally). There was a similar question here, but that led me nowhere, since I've already set DefaultEngine.ini to use my custom settings

```
 [/Script/Engine.Engine]
 GameUserSettingsClassName=/Script/MyGame.Custom_Settings

```

I've checked whether GEngine can fetch the Settings, and it appears it can. Does anybody have an idea why the cast might be failing?

# Answer
After trying all manner of things, deleting the .vs, Binaries, Intermediate, Saved and .sln, rebuilding the VS Files and building the project from there turned out to solve this problem.
> 0 votes

---
Tags: c++, unreal-4
---


# Question
Title: How do I build the dependency graph on ECS?
ECS is excellent at decoupling: you split your game logic into multiple pieces, and every system is responsible for dealing with a specific piece. However, I don't know if each system should be aware of the rules of my whole game or if it should only care about its own little domain and be as unaware as possible of the general game rules.

For example, let's say I start building a game where initially entities have position and can move. So I create a `Position` component and whenever I want an entity to move, I assign a `Movement` component to it and let a `MovementSystem` do the job. The movement system will then iterate through all entities with position and movement, do some checking e.g. if movement is inside the entity map's bounds, and calculate the path for the destination. If everything is fine, it'll advance an entity's position a little bit given a delta time. And this process repeats each frame.

Later at some point, I decide to add a `StatusEffects` component which holds the multiple status effects an entity can have such as `Freeze`. Naturally, since an entity is not supposed to be frozen forever, I also add a `StatusEffectSystem` that'll be in charge of updating and removing expired status effects. *Conceptually* speaking, the movement system should know nothing about an entity status effects since all it cares about is movement. But how do I stop an entity from moving when it's frozen?

The naive answer would be to simply remove the `Movement` component whenever a `Freeze` status effect is assigned to an entity. However, that would only stop the ongoing movement, and as long as the player pressed a mouse button to move the entity again, another `Movement` component would be created by the input system thus disregarding the entity's status effects. Of course, we could have an intermediary system for removing `Movement` components of entities with a given status effect so that if any other system created a movement, an status effect remover system would take care of that, and the core update logic would be similar to:

```
void update(dt) {
    InputSystem.update(dt);
    StatusEffectRemoverSystem.update(dt); // removes Movements if needed
    MovementSystem.update(dt);
    StatusEffectSystem.update(dt);
}

```

However, I think this is bad because if the number of systems is large - and it tends to be -, then it can quickly become unmanageable and bugs can be difficult to spot.

Another approach would be to add a `Movable` component and assign it to entities capable of movement, and whenever we wanted to remove the movability of an entity, we'd remove such a component. The status effect system would then remove the movable component of a frozen entity, and when the frozen status expired, it would add it back. The movement system would also be changed so that it now iterates through entities with position, movement, *and* movable. Everything is fine, right? Not quite.

What would happen if another part of my game logic, maybe a new system, also wanted to add and remove the movability of an entity? Say for example I add an inventory system that allows the player to store their items, but they shouldn't be able to move when they're managing their inventory. Well, I could remove the `Movable` component from the player's entity when they open their inventory, and add it back when they close it. And here's where things get messy. Because if the player happen to have a frozen status (maybe they're opening their inventory to use a potion?), then closing their inventory is all it takes to make them movable again and dismiss their status. Or conversely, if their frozen status ends before they close their inventory, they'll be able to move with their inventory open, which is incorrect behaviour.

Given such considerations, it seems to me that the most straightforward approach for such an issue is to detect if the player has a `Freeze` status in the movement system, in which case the movement would be ignored. Something like:

```
void MovementSystem.update(dt) {
    foreach (entity with Position and Movement) // forget about "Movable"
    {
        if (entity has StatusEffects and has Freeze)
            continue; // or maybe remove Movement

        ...
    }
}

```

I like it for two reasons. First, it clearly shows the precondition for every movement; no need for such status effect remover system or the like. Secondly, since everything movement-related would be in one place, it's easier to find if something is not behaving as expected. However, it makes the movement system dependant on any changes or feature/component addition I make on my game, which would make each system aware of my whole game rules, which boils down to the question: is this aligned with the ECS pattern? Because I can see how this could be a problem for e.g. a game engine aiming to be extensible.

# Answer
> 3 votes
Make a `Immovable` component that contains a set※1. The idea is that when this set is empty the entity can move.

We can do this by having The `MovementSystem` check, however that would imply iterating over entities that are set to not move. Ideally the `MovementSystem` would not have to do that※2.

---

So, for example, your `Immovable` component has a set of strings, and when the character is frozen, then `StatusEffectSystem` can add the "frozen" string to that set. When the `MovementSystem` checks, it sees it is not empty, and thus it does not move. If you need to debug why... well, you look at the set, and it says "frozen". Eventually the status goes away, and that item can be removed from the set by the `StatusEffectSystem`.

Similarly, the inventory system or whatever other system you need to restrict movement can add and remove items from the set in the `Immovable` component. As long as they only remove items they added, there should be no problem.

This way, you know that a system will not accidentally remove a restriction to movement imposed by another system.

---

※1: A set of what? If you plan on allowing third parties to add system to your game, the `enum` is not an option. Otherwise, an `enum` would work. It is not that system has to add themselves to the `enum`, it is that you add them. If `enum`s are not an option, you can use strings... if conflict is really a problem (you are developing the game, you should know what strings you are using), you can always prefix the strings with the name of the system, assuming you do not have two systems with the same name (which I consider a reasonable assumption) that would solve conflicts. Consider also start the development using strings and switching to `enum`s when the set of systems of your game has been fully decided.

※2: Right, so, we can have `Immovable` and `ImmovableReason`. Where `Immovable` is empty and `ImmovableReason` has the set. Then an intermediary system that runs on changes of `ImmovableReason` and adds or removes `Immovable`. Then `MovementSystem` can query on the absence of `Immovable`. This is, of course, contingent on whatever or not your ECS supports notifications on change of components.

# Answer
> 2 votes
Entity movement can be influenced by a variety of sources such as local player, network, or even AI so this is why I often find it easier to treat it as state that is mutated across multiple systems.

Lets take this component structure:

```
struct Movement
{
  // -1/+1 implies move either direction along given axis, 0 implies no movement
  short x, y, z;
}

```

If your entity has a `PlayerComponent`, there would be an associated `PlayerControllerSystem` that would read the input captured by the `InputSystem` and translate that input into actions. Typically the controller would maintain a map of key\<-\>action mappings that would allow a game to be customized allowing the player to setup keybindings as they wish.

In this example, lets assume that WASD are all mapped to their generally accepted movement bindings of forward, left, back, and right respectively.

It would be the job of the `PlayerControllerSystem` to review the input captured and based on key presses, it would update the `Movement` component's x, y, and z values accordingly to indicate that the player wishes to perform some movement in that direction.

You would then have your `StatusEffectSystem` that checks to determine whether the entity happens to be frozen during this frame. If the player is frozen, this system would then set the `Movement` component's x, y, z all to 0 for this frame. If the player is not frozen, no component changes occur.

After all systems that influence movement have had a chance to contribute their interpretation of entity state, your `MovementSystem` then iterates all entities that contain a `Movement` component and based on the values in x, y, and z; that direction gets turned into a movement vector based on interpolation and then gets applied to the entity.

The benefit here is there is no need for any other special component, you avoid cache misses in the `MovementSystem` all together. You treat each system as either one that simply mutates current state or reacts to current state; e.g. a pipeline.

Also in order to avoid coupling between systems, I mentioned querying input above to see if keys are pressed; this can be handled by moving that state into a component as well. In my implementation, we have a concept (which Overwatch also uses) called Singleton components. The idea is that there are certain components that the World maintains a reference to because there is only ever 1 instance and therefore it makes more sense for systems to query that component's state rather than having to know about a system that manages said state.

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


# Question
Title: How to convert from OpenGL to OpenGL ES?
I need to convert code from OpenGL to OpenGL ES 1.1, I found that the GLUT library is missing in that. Can anyone tell me what do I do to replace `glRasterPos3f` in OpenGL?

# Answer
> 3 votes
You don't just convert from OpenGL to OpenGL ES, as OpenGL takes shortcuts which are not implemented in ES. As Sam points out, glRasterPos\* for instance has no equivalent, because it is not very useful. I doubt glRasterPos3f() is the only function missing to port you project from GL to ES, and you *won't* find function-to-function replacements for most of them.

I'll advise you to learn what is OpenGL ES actually before starting anything. It is easily portable to OpenGL (the other way is NOT true), and will teach you some good habits (do not use glVertex\*(), use object buffers, don't change states all the time, etc). But porting bare GL to ES ? Forget it.

# Answer
> 2 votes
This Qt4 example has some information about porting from OpenGL to OpenGL ES:

https://doc.qt.io/archives/qt-4.8/qt-opengl-hellogl-es-example.html

---
Tags: opengl-es
---


# Question
Title: Rotating a parent rectangle to align child with target
My beautiful drawings will explain better than many words (or at least I hope):

The structure:

* The black rectangle is a GameObject (my weapon sprite).
* `A` and `B` are also GameObjects (children of black rectangle): `StartShotPoint` and `ShotPoint` used for the direction of my projectile.
* `C` is the first hypothetical target

In this situation my sprite will be rotate of 0 degree.

In this second image there is the question. I want to find the rotation of my sprite (-10 degree in the example) knowing the `Vector2` destination `D` and of course all the coordinates of the 3 GameObjects.

The situation is simple as long as the player rotates the weapon, but in this case is the AI (after finding the player at the point `D`) must turn the weapon in the right direction. I know how to find the direction between one point and another, but between two decentralized points and a third one messed up my brain.

I really don't know which "direction" to take.

Thanks for your help.

# Answer
Okay so the goal is to be able to rotate a rectangular, which I'll call `sprite`, to line up with an arbitrary point in 2D space, which I'll call `target`.

Rotating `sprite` to line up with `target` can be achieved through the `Transform.LookAt` method provided by Unity, however this alignment will be based upon `sprite`'s center, and we would rather have the target aligned with an arbitrary point within the `sprite`. We'll call this point `firepoint`, as in the case of a gun or cannon sprite, where projectiles need to be fired from a specific point and not just the center of the sprite.

Basically the `Transform.LookAt` nearly gives us the correct rotation, we just need to translate it. Currently it is aligning `sprite` center with `target`, and instead we want `firepoint` aligned with `target`.

To align `firepoint` and `target` we can calculate an `offset target`, that is offset from the `target` position by the same amount that `firepoint` is offset from the `sprite` center. Now, using `offset target` for the `sprite` to `LookAt`, we line up the center point and `offset target`. This ends up aligning `firepoint` and `target` since the difference between both targets and both points is `offset`.

This can be illustrated using the diagrams you provided:

Looking at the diagram above, imagine that we have been given our `target` as point C. To align `firepoint` and C, we need the `sprite` to `LookAt` D, the point that exactly `offset` away from `C`.

Looking at the above diagram, which I have shoddily modified, we have a `target` D, also I have added an `offset target` E below point D by amount `offset`. By `LookAt`'ing the rect towards `offset target` E we will end up lining up `firepoint` with the `target`.

Further information can be found in the Unity Docs on LookAt, as well as in this Unity forum thread where users discussed how to recreate or use the `LookAt` function effectively in a 2D context.
> 1 votes

---
Tags: unity, mathematics, rotation
---


# Question
Title: Should calculations be done on the CPU or GPU?
I'm currently learning OpenGL and it's become obvious that I can do most calculations on the CPU or the GPU. For example, I can do something like lightColor * objectColor on the CPU, then send it to the GPU via a GLSL uniform. On the contrary, I can send them separately and have GLSL perform the calculation.

Is there a best practice on where graphic calculations should be performed? My thoughts are that the GPU might be optimized for matrix or vector calculations. However, I'm also thinking that the CPU might be a better place for it since the GPU might have better things to do.

# Answer
A few rules of thumb around this, if the calculation only needs to be done once and applies to the entire object, then you will get best bang for buck calculating it prior to loading onto the GPU. IF though the calculation does change then you also need to consider where in the GPU pipeline it should be calculated. For instance, if you can calculate the value prior to pixel shader, say in the vertex shader then this in itself is an important optimisation.

Where you can relieve pressure on the most heavily used parts of the GPU pipeline also is also useful to consider. You have the right thought process on questioning where and when.

For Matrices, in my experience, sometimes you need to pass the individual Rotation/Translation matrices into the GPU rather than premult them (if you are using instancing). But you can also use tricks like deriving the rotation component by casting your 4x4 to a 3x3 (this is very helpful when you are calculating face normals).

But questioning everything is the best way to improve.
> 2 votes

# Answer
The CPU could perform the calculations in a faster rate than a GPU due to higher clock frequency. However, the GPU can do a lot more calculations in parallel. If you are working on a large data set, where you operate on each item in the same way, the GPU can be a lot more efficient, however it requires some setup, like uploading data to the GPU, executing a shader, maybe downloading data from GPU.

In a game rendering example, you will usually precompute what you can on the CPU, like multiplying view and projection matrices, so the vertex shader can do only one matrix multiply of vertexpos * viewProjectionMatrix instead of two. But you wouldn't want to precompute the matrix transform for each vertex on the CPU, that would be more efficient in the GPU vertex shader.

In your example, lightColor\*objectColor makes more sense to do in the pixel shader if you are doing per pixel lighting, or in the vertex shader if you are very old school. :)
> 0 votes

# Answer
If the data is not expected to change between gpu threads, then it should be performed on the CPU, and sent to the shader via a uniform. Examples of this include:

world to screen transform (sometimes called MVP transform). It is computed by multiplying the model (or world) matrix by the view matrix and then the result by the projection matrix like so:

```
mat4 mvp = projection * view * model;

```

It would then be sent the shader as a `uniform mat4`.

Normal matrix, eye position and light data all fall into this category.

You *can* do mvp computation on the GPU, but it is wasteful.

For each data, ask yourself: Can I compute this once and use many times? If the answer is yes, do it on the cpu, and set it as a uniform.

If you expect the data to vary between vertices or fragments, then compute it on the GPU.
> 0 votes

---
Tags: opengl, mathematics, vector, matrix, gpu
---


title: Good taunt attack design

text:
# Question
Title: Good taunt attack design
I'm making a turn based rpg and I have an attack allows for a party member to draw an enemy's focus towards it for a set number of turns. I feel an attack that draws all aggression from enemies is very strong, so I am unsure how to balance it.

Should taunted enemies get bonus attack stats to make up for the temporary loss of their AI and the ability to target weaker party members? Or is a party member being the focus of attacks something that should be rewarded, and the party member should be given temporary healing or defence to compensate for the risk they took?

# Answer
> 2 votes
Whether a special ability is too strong or too weak depends on how it interacts with everything else in the game, and even on what inputs the player has to use to cause it to happen. Maybe you find that your taunt attack is so strong the party member never wants to use any other ability again once they learn it. Sure, if after testing you find that's what happens, you could nerf the taunt attack by having it give taunted enemies bonus attack stats... but maybe you actually like the strategies that come about when you're trying to protect your one taunter from an endless barrage of angry monsters, in which case the thing you should actually do is make it easy for the player to just declare that that party member should automatically taunt every turn instead of navigating through menus each time to repeat their taunt.

If it turns out the taunt is so weak players almost never have a good reason to use it, then you can certainly buff the ability by giving them bonus defense stats while using it.

Basically, it's hard to balance things in that much detail without testing, so just make sure your ability framework is tweakable and start adjusting abilities when you find some strategies are too powerful or too useless for your liking.

# Answer
> 2 votes
> I **feel** an attack that draws all aggression from enemies is very strong

Unfortunately our feelings are often very misleading when it comes to game balance. The only way to find out if our feelings are warranted or not is to collect some data through **playtesting**. So I would recommend you to implement that feature in a provisoric way, try it in different scenarios and see what happens. Possible results could be:

* It is completely overpowered because it allows the player to draw all enemy damage output on one party member which can then be made almost immune to that damage.
* It makes almost no difference. Maybe the player already got enough tools at their disposal to control what units the other side can and can not attack. Maybe it isn't even that relevant in your game which character in particular tanks the enemy attacks.
* It is almost always a mistake to use that ability, because no player-unit is capable of surviving a turn where the whole enemy team focuses their damage output on them.

But the only way to find out is through playtesting.

OK, so what if we find out that your intuition was correct and the ability is indeed overpowered? What can we do about that?

We could limit its use. Add a cooldown so the player can only use it every other turn. Or we could make it only usable a limited number of times per-combat or per-dungeon. Or we could have it consume some resource which is hard to replenish.

Or we could introduce a counter to it. Some enemies might be able to ignore it. Some enemies might even hit extra hard when they are taunted. Some enemies might be able to negate the taunting-state of the character so the other enemies can attack normally. That way the player might be able to win *some* battles using the taunt strategy, but has to find a different strategy in those battles where a counter is present.

I am looking forward to playing your game.

---
Tags: game-design
---


# Question
Title: Is ETC2 Texture Compression available in OpenGL ES 2.0?
I have an ES 2.0 app and would like to use ETC2 texture compression if it is available (i.e. I am running on a device that supports ES 3.0 standard). Is it possible to use ETC2 in ES 1.1/2.0, and if so how can I query if a device supports it? For most forms of texture compression, there is an extension I can query for, but there is no extension for ETC2 since it is built in.

# Answer
There are a bunch of GL extensions related to ETC2 support:

```
OES_compressed_ETC2_RGB8_texture
OES_compressed_ETC2_sRGB8_texture
OES_compressed_ETC2_punchthroughA_RGBA8_texture
OES_compressed_ETC2_punchthroughA_sRGB8_alpha_texture
OES_compressed_ETC2_RGBA8_texture
OES_compressed_ETC2_sRGB8_alpha8_texture

```

The ES3 compatibility extension aggregates those (and a few others). You can query for these extensions to check support, presumably.
> 3 votes

# Answer
Pretty late to the show but this is the top google hit for ETC2 on GLES2, and I think the accepted answer isn't really complete.

I think you ought to be querying compressed texture format support rather than extensions. Something like this:

```
    GLint iNumCompressedFormats = 0;
    glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &iNumCompressedFormats);
    if (iNumCompressedFormats > 0)
    {
        GLint *pCompressedFormats = new GLint[iNumCompressedFormats];
        glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, pCompressedFormats);
        for (int i = 0; i < iNumCompressedFormats; i++)
        {
            switch (pCompressedFormats[i])
            {
            case GL_COMPRESSED_RGBA8_ETC2_EAC:
                printf("GL_COMPRESSED_RGBA8_ETC2_EAC supported\n");
                break;
            ... etc ...
            }
        }
        delete[] pCompressedFormats;
    }

```

The relevant ETC2 formats you might want to check are: `GL_COMPRESSED_R11_EAC`, `GL_COMPRESSED_SIGNED_R11_EAC`, `GL_COMPRESSED_RG11_EAC`, `GL_COMPRESSED_SIGNED_RG11_EAC`, `GL_COMPRESSED_RGB8_ETC2`, `GL_COMPRESSED_SRGB8_ETC2`, `GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2`, `GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2`, `GL_COMPRESSED_RGBA8_ETC2_EAC`, `GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC`.
> 1 votes

---
Tags: opengl-es, opengl-es2
---


# Question
Title: Race condition implementing World Boss System in Web Browser MMO using PHP
I am trying to create a world boss system using PHP. But I am having a problem with how to account for all the damage while updating the health of the boss in real-time.

The current damage process is as follows:

1. Get boss' current HP from database.
2. Reduce the HP based on the calculated damage.
3. Update the boss' HP to database.

Example:

* Player 1 (P1) attacks the boss. Calculated damage is 10.
* The boss' current HP is saved to variable $boss\_hp which is 100.
* It will now be $boss\_hp -= 10. Which is 90.
* The boss' HP in database is then updated.

Now, imagine two player attack the boss simultaneously...

* P1 attacks the boss. Calculated damage is 10.
* The boss' current HP is saved to variable $boss\_hp which is 100.
* It will now be $boss\_hp -= 10. Which is 90.
* Before P1 updates the boss\_hp in database, P2 also damages the boss.
* P2 saved the boss' current HP to his/her own $boss\_hp variable which is 100 at the moment.
* P2 also performs step 2. $boss\_hp -= 10. Which is also 90.
* P1 now updates the boss\_hp in database (=90).
* P2 also updates the boss\_hp in database (=90).

The boss\_hp should be 80 but the damage of P1 has been neglected since P2 updates the boss\_hp last.

How to avoid this problem?

# Answer
> 1 votes
You could either use "SET boss\_hp = boss\_hp - 10" directly in a MySQL query if your damage calculation is simple enough to be expressed by a simple subtraction. Or look into some of the locking statements supported by MySQL https://dev.mysql.com/doc/refman/8.0/en/sql-syntax-transactions.html

Edit: Sorry, I can see transactions does not handle locking the same way I thought. Here is an example of transactions http://www.mysqltutorial.org/php-mysql-transaction/ your implementation could look something like:

```
while(true)
  start_transaction(read_write)
  $cached_hp = select hp from boss
  // calc hp after hit
  try
    // verify that boss has not been changed
    select boss where hp = $cached_hp
  catch
    rollback;
    // retry this again
    continue;
  update boss hp -= damage
  commit;
  break;

```

The $cached\_hp will not be guaranteed until the commit; But you are guranteed that all three queries will be executed atomic, so by verifying that the $cached\_hp is still equal to the boss hp in database, you guarantee that no hit will be accepted while another is processed.

EditEdit: Yes this means that if it fail it will retry the hit calculations. If this happens too often, you should probably switch to an event driven system instead.

(Personally I would do these kind of calculations from a server supporting multiple connections to a single instance (nodejs is easy to get started with), and only use php as the presentsation layer for the client, sending damage events to the backend server, and let the backend handle the synchronization. I am not sure how easy this would be to do for php, as the language is not designed for real time interaction between users.)

# Answer
> 0 votes
I think maybe Redis could solve this. Redis is fast and even if there are hundreds of simultaneous requests, redis will work out. Example (its javascript, you can convert this into PHP)

```
// you query database, calculate random damage etc in this method, to have a final damage.
var player_damage_dealt = calculate_player_damage()

// boss health atomicly reduced, dont need any validation, lock, transaction, wont fail.
$redis.incrby('boss_health', player_damage_dealt * -1);

var left_health = $redis.get('boss_health')

// check if boss is still alive, if not, do database updates accordingly
update_database_if_boss_died(left_health)
return left_health;

```

---
Tags: multiplayer, php, mysql
---


# Question
Title: Is it a good idea to use high-level API's in order to develop game engines?
I have been looking around the internet finding articles that talk about what you should learn to develop a game engine. Something that I keep hearing in many articles is that you should learn low-level graphics API's such as OpenGL or D3D11 (great article for example: https://www.haroldserrano.com/blog/how-to-become-a-game-engine-developer) for graphics rendering for instance.

NOTE: I will be using graphics rendering as an example for my question since it makes the most sense to me here.

This got me thinking. Is it really necessary to re-invent the wheel by creating your own framework for just rendering graphics? Isn't it sufficient to learn a library like babylon.js for graphics rendering on the web? If the main goal of creating a game engine is to lay a software framework to build video games, then spending time on developing an entire framework for graphics shouldn't be an issue if others have solved the problem for you via their graphics libraries.

# Answer
> 0 votes
Sure, using libraries other people created in your engine can save you a lot of work. But this can also cause a couple problems.

You are now adding another abstraction layer (your engine API) on top of an already existing abstraction layer (the library). And the user of your engine is likely to add another abstraction layer on top of yours.

A common saying in software architecture is "There is no problem which can not be solved by adding another layer of abstraction, except having too many layers of abstraction". Every layer of abstraction hides certain features of the layer below it. Every layer of abstraction also has a performance penalty. So the more layers of abstraction you have between the end-developer and the underlying graphic hardware, the more performance overhead you end up with and the more features get inaccessible.

And then there are the problems you always have when you add 3rd party dependencies to a software projects:

* Bugs the maintainers don't get around fixing
* Missing features the maintainers refuse to add
* Updates which break your code in unexpected ways
* Missing or incorrect documentation
* Compatibility issues with other dependencies
* License issues
* The whole library being discontinued

So you might really want to consider if it wouldn't be appropriate to have your engine call OpenGL directly.

# Answer
> 1 votes
You raise an interesting question, for which there is no definite answer.

The idea of designing an engine is for ease of re-use, and to make it easier for others to use to make games quickly.

With that in mind, an easy to use, high level API is desirable.

Think about a power drill: I do not want, or need, to know how it functions. I Only need to know what it can do, and that it does it quickly, and efficiently.

Engine API's are the same. Someone who is not familiar with graphics programming, but is good at designing games, does not care *how* a thing gets rendered, just that it does. Thus we take a whole load of DX/OpenGL low level code, and hide it behind `RenderObject(Object& o)`, or we abstract the operating/file system, or the scripting system, or any other number of math/tech heavy subsystems, that a user may only have notional knowledge of.

An engine is a set of tools for making games. Each tool has a lot of work gone into it, and it is complex under the hood.

We create a high level API for each tool, in order for the tools to easily and smoothly interact with one another, and for a user to control easily.

As an engine programmer, it is your job to make your *client's* (anyone using your engine, including yourself) job that much easier and faster.

---
Tags: architecture
---


# Question
Title: Unity3D - How to "force" rotation over the X axis
When I click to left or right, up or down, I'd like my airplane to rotate over the x-axis, to loop, and at some point over the z-axis in order to end up with the y-axis pointing up (world up).

Let me show you what it looks like right now, and draw what I'd like the end result to be like.

Up and down: https://photos.app.goo.gl/HFqRychpR9W8oFq59

Right and left: https://photos.app.goo.gl/BcPyQvu2TFpG763aA

This is what I'd like to happen:

Here is how the axis are setup

Here is the code that is currently rotating the airplane

```
    void Update()
{

    if (Input.GetMouseButton(0))
    {
        worldposition = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 57));
        worldposition.z = 25;
        relativePos = worldposition - transform.position;
    }

    Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
    transform.localRotation = Quaternion.Lerp(transform.rotation, rotation, RotationSpeed * Time.deltaTime);

    transform.Translate(Vector3.forward * Speed * Time.deltaTime, Space.Self);
    transform.position = new Vector3(transform.position.x, transform.position.y, 25);

}

```

I have played around with Rotation and Quaternions for a few days already and I am unable to accomplish what I need.

Any suggestions would be greatly appreciated. Thank you.

# Answer
The flight maneuver you are describing is an Immelmann Turn followed by a descent back to the original flight level. This maneuver has 5 distinct phases:

1. pitch 180° up
2. roll 180°
3. pitch 30° down
4. fly forward for a short time
5. pitch 30° up

As you can see, this is a multi-step process where each step performs a different rotate motion. So you can not implement it with a single rotation.

If you insist on using a code-based solution, then you will have to use a state-machine. Have your update-method keep track of which phase of the maneuver it is in and then perform the action relevant for that phase.

However what I would recommend instead is to use the animation system. The system can do a lot more than just moving the legs of character models. You can create animations which manipulate (almost) every property of every component of a game object over a timeframe, including position and rotation. That means you can describe the motion you want your game object to perform using curves in a visual editor. This even allows you to tweak the animation in real-time.

The Unity animation system is a really powerful tool, but it is also complex. Describing it from the beginning would be far too long for the scope of this answer. But it shouldn't be hard to find some basic tutorials or to learn it from the documentation I linked above.
> 1 votes

---
Tags: unity
---


title: Pivot not updating programmatically

text:
# Question
Title: Pivot not updating programmatically
I have a canvas. It has an empty game object as a child. That object has a RectTransform component. The RectTransform pivot value is set to 0.4, 0.5 (x, y). In some code I wanted to update the pivot value using the following:

```
Debug.Log(((RectTransform)transform).pivot);  // logs: (0.4, 0.5)
((RectTransform)transform).pivot.Set(0.3f, 0.8f);
Debug.Log(((RectTransform)transform).pivot);  // logs: (0.4, 0.5)

```

I don't know why the set command is not working. The tooltip for `Set` is: "Set x and y components of an existing Vector2"

# Answer
> 1 votes
You need to use:

```
((RectTransform)transform).pivot = new Vector2(0.3f, 0.8f);

```

The tool tip for `.Set` is correct that it mutates the Vector2. But the `.pivot` is a getter and because Vector2 is a struct it means `.pivot` returns a **copy** of the Vector2, not a reference.

If you wanted to use `.Set` then you'd need to use:

```
var new_pivot = ((RectTransform)transform).pivot.Set(0.3f, 0.8f);
((RectTransform)transform).pivot = new_pivot;

```

---
Tags: unity
---


title: Coroutine only partially executing

text:
# Question
Title: Coroutine only partially executing
I have a Coroutine that I use to pull and spawn an enemy in my game. This coroutine works perfectly fine, with the exception of the very first call. I am fairly certain this is because I am probably loading something before it is ready, but I don't know enough to know where.

This is my code (Note the Debug.Log entries). I have removed whatever I think is irrelevant code.

1. EnemyHandler.cs

```
public class EnemyHandler : MonoBehaviour
{
public int mob_id;
IEnumerator LoadMob()
{
    Debug.Log("Checkpoint 1");

    WWWForm form = new WWWForm();
    form.AddField("mob_id",mob_id);
    WWW www = new WWW("my-url-here",form);
    yield return www;
    Debug.Log("@@@@@@ Checkpoint 2 @@@@@@");
    string[] webResults = www.text.Split('\t');

    int returncode = int.Parse(webResults[0]);

    switch (returncode)
    {
        case 0:
        //Mob Loaded Successfully
        //Mob variables are set here
        Debug.Log("@@@@@@ Checkpoint 3 @@@@@@");
        break;

        default:
        Debug.Log("Error!");
        break;
    }

}

 public void CallMobLoad(int requested_mob_id)
 {
     mob_id = requested_mob_id;
     StartCoroutine(LoadMob());
     Debug.Log("Coroutine called! Checkpoint 0");
 }
}

```

2.GameManager.cs (This is my primary class)

```
public class GameManager : MonoBehaviour
{
    public GameObject spawnManager;
    public static EnemyHandler thisenemy;

    void Start()
    {
     thisenemy = spawnManager.AddComponent<EnemyHandler>();
     thisenemy.CallMobLoad(1);
    }
}

```

CallMobLoad is called once at Start, and every time a monster dies. It never works when called in Start(), but always works after that.

Furthermore, the first call only calls the first 2 Debug.Logs "Checkpoint 0" and "Checkpoint 1", none of the other checkpoints are hit. Every subsequent call works correctly and hits all checkpoints.

I really want to learn how/why this happens, Any help is greatly appreciated!

**EDIT:** I have fixed this by turning Start into an IEnumerator, and adding a `yield return` to `thisenemy.CallMobLoad(mobloadtemp);`

Still not sure if this is the best way to do this, so please do advise.

# Answer
> 2 votes
I have fixed this by turning the function I use to initialize the Coroutine into an IEnumerator, and adding a `yield return` to the call.

(The same effect can be achieved by changing `Start` from `void` to `IEnumerator`, if the Coroutine is initialized in `Start`).

I don't know if this is the best solution, but this solves the problem completely.

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


# Question
Title: how can I transform a skewed line to a vertical line?
So, I have a line:

And I skewed it with `x += y * cos(angle)`

and got something like:

My question is, if I have another line segment with that same skew, how can I transform it so that it is pointing up again like:

I tried just applying a rotation (reverse of the skew angle) to the line's x,y coordinates, but that did not seem to give me the effect I am going for.

How can I do this?

**EDIT**

So, if I start with a rectangular like:

and I apply:

```
x1 = x1 + (y2 - y1) * cos(angle);
x2 = x2 + (y2 - y1) * cos(angle);

```

I get:

I am not quite clear why my x1 is wrong? (as you can see, it extends outside of the rectangle)..

But, regardless of that, this still is not the direction I am trying to skew by... What I really want is something that looks like this:

# Answer
> 2 votes
---

## Skew

So, you say you have applied this transformation:

```
x += y * cos(angle)

```

That is:

```
x = x + y * cos(angle)

```

This means that if you have a line that goes from `(x1, y1)` to `(x2, y2)`...

After transformation it goes from `(x1 + y1 * cos(angle), y1)` to `(x2 + y2 * cos(angle))`.

**Note**: I am assuming `angle` is a paramater of the transformation.

---

There are two things to notice here:

* Only `x` is affected.
* The transformation depends on `y`.

This means that:

* To reverse it, you must only affect `x`.
* You must have `y` into account to reverse it.

---

## Reverse Skew

We can figure out the inverse function... first, let us label `old_x` and `new_x`:

```
new_x = old_x + y * cos(angle)

```

Solve for `old_x`:

```
new_x = old_x + y * cos(angle)

=>

new_x - y * cos(angle) = old_x

=>

old_x = new_x - y * cos(angle)

```

That is your inverse function:

```
x = x - y * cos(angle)

```

---

We can check by reversing `(x1 + y1 * cos(angle), y1)` to `(x2 + y2 * cos(angle))`.

We get `(x1 + y1 * cos(angle) - y1 * cos(angle), y1)` to `(x2 + y2 * cos(angle) - y2 * cos(angle))`.

Which is just `(x1, y1)` to `(x2, y2)`.

---

## Skew with a fixed point

Now, if we are trying to keep a point fixed, the usual approach is to translate it to the origin.

Thus, if we want the point `(x1, y1)` to be fixed, we will use the following transformation:

```
x = x - x1
y = y - y1

```

So that `(x1, y1)` gets transformed into `(0, 0)`. Then we do the transformation we want. Followed by the inverse of the translation above, so that `(0, 0)` is `(x1, y1)` again.

Alright, that means that if we want to do `x = x + y * cos(angle)` while keeping `(x1, y1)` in place, we do:

```
x = x - x1
y = y - y1
x = x + y * cos(angle)
x = x + x1
y = y + y1

```

We can inline this transformation like this:

```
x = ((x - x1) + (y - y1) * cos(angle)) + x1

```

Simplify:

```
x = x + (y - y1) * cos(angle)

```

The alternative approach is to apply the inverse transformation for the fixed point. That is:

```
x = x + y * cos(angle)
x = x - y1 * cos(angle)

```

In a single line:

```
x = x + y * cos(angle) - y1 * cos(angle)

```

Simplifly:

```
x = x + (y - y1) * cos(angle)

```

That is the same result.

---

## Reverse Skew with fixed point

We, of course, can figure out the inverse function for this transformation. Label your `old_x` and `new_x`:

```
new_x = old_x + (y - y1) * cos(angle)

```

And solve for `old_x`:

```
new_x = old_x + (y - y1) * cos(angle)

=>

new_x - (y - y1) * cos(angle) = old_x

=>

old_x = new_x - (y - y1) * cos(angle)

=>

old_x = new_x + -(y - y1) * cos(angle)

=>

old_x = new_x + (-y - -y1) * cos(angle)

=>

old_x = new_x + (-y + y1) * cos(angle)

=>

old_x = new_x + (y1 - y) * cos(angle)

```

---

Finally, you have a transformation that keeps `(x1, y1)` fixed:

```
x = x + (y - y1) * cos(angle)

```

And its inverse, which, of course, also keeps `(x1, y1)` fixed:

```
x = x + (y1 - y) * cos(angle)

```

---

## Rotate

If you only have lines, for each one the skew will be equivalent to a rotation and a scaling. *This is no longer true once you have 2d shapes.*

A rotation looks like this:

```
x = x * cos(rotation_angle) - y * sin(rotation_angle)
y = y * cos(rotation_angle) + x * sin(rotation_angle)

```

Scaling looks like this:

```
x = x * scale_factor
y = y * scale_factor

```

Combined:

```
x = x * cos(rotation_angle) * scale_factor - y * sin(rotation_angle) * scale_factor
y = y * cos(rotation_angle) * scale_factor + x * sin(rotation_angle) * scale_factor

```

We are trying to parametrize the combination, such that:

```
x = x + y * cos(angle)

```

That is:

```
x + y * cos(angle) = x * cos(rotation_angle) * scale_factor - y * sin(rotation_angle) * scale_factor

```

Break it by variables:

```
x = x * cos(rotation_angle) * scale_factor
y * cos(angle) = - y * sin(rotation_angle) * scale_factor

```

Two equations and two unknowns, we can do this...

Clearly `cos(rotation_angle)` and `scale_factor` must cancel out (because `x = x`). Thus

```
scale_factor = 1/cos(rotation_angle)

```

Which means:

```
y * cos(angle) = - y * sin(rotation_angle) * 1/cos(rotation_angle)

```

By trigonometric identity, that is tangent:

```
y * cos(angle) = - y * tan(rotation_angle)

```

Solve for `rotation_angle`:

```
y * cos(angle) = - y * tan(rotation_angle)

=>

- y * cos(angle) = y * tan(rotation_angle)

=>

- y * cos(angle) / y = tan(rotation_angle)

=>

- cos(angle) = tan(rotation_angle)

=>

atan(-cos(angle)) = rotation_angle

=>

rotation_angle = atan(-cos(angle))

=>

rotation_angle = -atan(cos(angle))

```

Replace in `scale_factor = 1/cos(rotation_angle)`:

```
scale_factor = 1/cos(rotation_angle)

=>

scale_factor = 1/cos(-atan(cos(angle)))

```

By `1/cos(-atan(cos(θ)))` in Wolfram|Alpha:

```
scale_factor = 1/cos(-atan(cos(angle)))

=>

scale_factor = sqrt((cos(angle * 2) + 3) / 2)

```

This means that if you rotate a point by `-atan(cos(angle))` and scale by `sqrt((cos(angle * 2) + 3) / 2)` it's `x` will end in the same place as if you had done `x = x + y * cos(angle)`.

Thus, if you want to undo the rotation (and keep the scaling), you can rotate by `atan(cos(angle))`.

---

## Rotate with fixed point

And of course, if you want to keep a fixed point while rotating, you can do the thing where the point is translated to the origin and then back.

So you do this:

```
x = x - x1
y = y - y1
x = x * cos(rotation_angle) - y * sin(rotation_angle)
y = y * cos(rotation_angle) + x * sin(rotation_angle)
x = x + x1
y = y + y1

```

Inline:

```
x = (x - x1) * cos(rotation_angle) - (y - y1) * sin(rotation_angle) + x1
y = (y - y1) * cos(rotation_angle) + (x - x1) * sin(rotation_angle) + y1

```

---

And, of course, since the `rotation_angle` you want is `atan(cos(angle))` you do:

```
x = (x - x1) * cos(atan(cos(angle))) - (y - y1) * sin(atan(cos(angle))) + x1
y = (y - y1) * cos(atan(cos(angle))) + (x - x1) * sin(atan(cos(angle))) + y1

```

*You can ask Wolfram|Alpha for alternatives for this trigonometric combos if you want to.*

---
Tags: mathematics, geometry, lines
---


title: Easing towards stepped value

text:
# Question
Title: Easing towards stepped value
I'm currently developing this rhythm game in lua (on top of a c++ engine) and I'm having trouble keeping a steady playhead position for the song currently playing.

The playhead position that the engine gives me updates in steps, so I get a fresh one every 2, 3 or 4 frames. But I need to have a steady one for sprites moving smoothly with the rhythm and stuff.

So I just keep track of my own playhead variable, which I initialize in 0 and then constantly add delta time to it. This variable eventually gets out of sync with the actual playhead, so every time I get a fresh playhead (or a "new step"), I correct my variable using the average between these two.

This however results in choppy movement.

I've seen many easing functions out there but I'm not sure which one would work in this case, nor when should I call it.

What would be the best way to ease my playhead variable into the stepped one?

This is the code I excecute every frame:

-- add delta to my own playhead variable

```
playhead = playhead + delta_time

```

-- if there's a new stepped\_playhead value, correct my playhead

```
if stepped_playhead ~= last_stepped_playhead then
    playhead = (playhead + stepped_playhead) / 2
    last_stepped_playhead = stepped_playhead
end

```

# Answer
In your code, the choppiness is coming from the fact that you are jumping every time there is a syncing frame. Jumping to the halfway point is a good idea, but if the displayed playhead is consistently moving away from the actual playhead (or vice versa), then it will constantly be jumping back slightly (or, alternatively, forward).

One way to smooth this out would be to adjust the speed of your displayed playhead at sync frames instead of adjusting the actual position:

```
frames_since_sync = frames_since_sync + 1

if stepped_playhead ~= last_stepped_playhead then
    sync_delta = (stepped_playhead - playhead) / frames_since_sync

    last_stepped_playhead = stepped_playhead
    frames_since_sync = 0
end

playhead = playhead + delta_time + sync_delta

```

The lines `sync_delta = (stepped_playhead - playhead) / frames_since_sync` and `playhead = playhead + delta_time + sync_delta` are main changes here.

Essentially, what we're doing is using the number of frames since the *last* sync frame as an estimate for the number of frames until the *next* sync frame. Then we divide the error between our two playheads by that number of frames. This new `sync_delta` is used to speed up or slow down the displayed playhead so that it should approach the correct position by the time the next sync frame comes around. At the next sync frame, the process is repeated, and the speed adjusted again to try and keep the two playheads near each other.
> 1 votes

---
Tags: c++, lua, easing
---


title: Character not collecting animated coins

text:
# Question
Title: Character not collecting animated coins
I am trying to make a simple game where the player jumps and collects animated coins. After collecting all the coins, the scene is supposed to change. For some reason, my character collects the coins but the scene doesn't change.

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

public class Coins : MonoBehaviour
{
    [SerializeField] private string newLevel;
    public int coinAmount;
    int coins ;

        void OnTriggerEnter2D(Collider2D other)
        {
        if (other.CompareTag("Player"))
        {
            coins += 1;

            Destroy(gameObject);
            addCoins();

        }
    }

    void addCoins()
    {
        coins++;

        if (coins == coinAmount)
        {
            SceneManager.LoadScene(newLevel);
        }
    }
}

```

This is a screenshot of the game:

# Answer
Since you have your `OnTriggerEnter2D` function in this script, it looks like this is the script you're placing on each individual coin.

That means that each individual coin has its own copy of the `coins` variable.

So you're not accumulating a total of how many coins are collected in your whole scene, you're just counting how many times *this* coin was collected.

To fix this, you can make the variable `static`, which makes it shared between all instances of the script. That might looks something like this:

```
public class Coin : MonoBehaviour {

    static int _coinsLeftToCollect = 0;

    [SerializeField]
    string _nextScene;

    // Keep a count of how many coins are still active in this scene.
    // Doing this in OnEnable/OnDisable ensures each scene starts from zero.
    void OnEnable() {
        _coinsLeftToCollect++;
    }

    // When the count hits zero, trigger the load.
    void OnDisable() {
        // You may want to add an additional condition to skip triggering
        // the next scene, if you're already unloading this scene for another reason.
        if(--_coinsLeftToCollect == 0) {
            SceneManager.LoadScene(_nextScene);
        }
    }

    void OnTriggerEnter2D() {
        if (other.CompareTag("Player"))
        {
            // This will call OnDisable as the script is destroyed.
            Destroy(gameObject);
        }
    }
}

```
> 1 votes

---
Tags: unity, character, scene
---