# Question
Title: Overshooting when traversing between two points with a set velocity
I'm creating a prototype for something I may make into a game and I've run into difficulty in creating a method to move a ship along a line between two points. While it reaches the end point, it either over/undershoots the end point on either the x or y. Applying a floor or ceiling arbitrarily won't work for all circumstances depending on what direction I'm travelling either.

I'm certain there must be a better way.

I've got the logic of creating a line between them using ArcTan2 but I'm finding that I will always get an over shot of the destination. I think I've been toying with it too long to arrive at a sensible solution that's not a kludge fixed with several conditional statements. I'm using C# but only while I'm at this stage.

A few definitions:

| Name | Type | Initial Value | Meaning |
| --- | --- | --- | --- |
| **xpos** | float | 4 | The current horizontal position of the ship |
| **ypos** | float | 12 | The current vertical position of the ship |
| **xhead** | float | 14 | The horizontal position of the destination |
| **yhead** | float | 7 | The vertical position of the destination |
| **speed** | float | 2 | The ship's speed, measured in position units per step |
| **dist** | float | 11.18034 | The current distance between the ship and its destination |
| **deltaX** | float | 10 | The signed offset from the ship to the destination, horizontally |
| **deltaY** | float | -5 | The signed offset from the ship to the destination, vertically |
| **angle** | float) | -0.4636476 | The angle the ship needs to travel, measured in radians counter-clockwise from the positive x axis |

Using the standard Euclidian distance between **xpos**,**ypos** and **xhead**,**yhead** I obtain the distance and then by using *Atan2* and the deltas I get the **angle** above.

here is my current code (ToPoint is an ext method turning xpos and ypos into a PointF as is Distance. headToPoint is **xhead**,**yhead** to a PointF):

```
        trail = new List<PointF>();
        steps = new List<PointF>();
        stepsIX = 0;
        float origDistance = (float)Math.Sqrt(Math.Pow(xhead - xpos, 2) + Math.Pow(yhead - ypos, 2));
        float segSize = origDistance / speed;
        float distance = origDistance;
        float lastdistance = distance;

        float deltaX = xhead - xpos;
        float deltaY = yhead - ypos;
        float angle = (float)Math.Atan2(deltaY, deltaX);

        steps.Add(this.ToPoint());

        while (distance >= 0)
        {
          PointF last = steps[steps.Count() - 1];
          lastdistance = (float)Math.Sqrt(Math.Pow(xhead - last.X, 2) + Math.Pow(yhead - last.Y, 2));
          float nx = last.X + (float)(speed * Math.Cos(angle));
          float ny = last.Y + (float)(speed * Math.Sin(angle));
          PointF np = new PointF(nx, ny);
          distance = np.Distance(headToPoint());

          if (distance > lastdistance)
          {
            break;
          }

          steps.Add(np);
        }

```

Output of **steps**:

```
START: {X=4, Y=12}
TARGET: {X=14, Y=7}
--Steps--
{X=4, Y=12}
{X=5.788855, Y=11.10557}
{X=7.577709, Y=10.21115}
{X=9.366564, Y=9.316718}
{X=11.15542, Y=8.422291}
{X=12.94427, Y=7.527864}
{X=14.73313, Y=6.633436}

```

Many thanks to anyone who reads this or has any ideas!

# Answer
> 0 votes
This can be done much more simply. We don't need trigonometry and angles where simple vector normalization and arithmetic suffices.

```
bool StepToward(
        ref float currentX, ref float currentY,
        float destinationX, float destinationY,
        float maxStepDistance
) {
    // Compute the offset from our current position to the destination.
    float dX = destinationX - currentX;
    float dY = destinationY - currentY;

    // Get our distance away (we could defer this square root, but the
    // majority of the time we have to do it anyway, so let's bite the bullet.
    float distance = (float)Math.Sqrt(dX * dX + dY * dY);

    // If we're within one step of our destination, reach it exactly,
    // and report back that we have arrived (true).
    if (distance <= maxStepDistance) {
        currentX = destinationX;
        currentY = destinationY;
        return true;
    }

    // Otherwise, get an offset vector in the direction of our destination,
    // clamped to the length of our maximum allowable step.
    // Use it to advance one step distance toward the destination.
    float scale = maxStepDistance / distance;
    currentX += dX * scale;
    currentY += dY * scale;

    // Report back that we still have farther to go.
    return false;
}

```

Your loop can then be something like:

```
// Log starting point.
steps.Add(ToPoint());

// Step until we reach the destination.
while (!StepToward(ref xpos, ref ypos, headX, headY, speed)) {
   // Recording each intermediate step we take.
   steps.Add(steps.Add(ToPoint());
}

// Log our arrival at the destination.
steps.Add(ToPoint());

```

---

You could also do this in one big batch:

```
// Compute the offset and distance from our start position to the destination.
float deltaX = headX - posx;
float deltaY = headY - posy;
float distance = (float)Math.Sqrt(deltaX * deltaX + deltaY * deltaY);

// Compute how many steps it will take to reach it at this speed.
float stepCount = distance / speed;
int wholeStepCount = (int)stepCount;

// Compute an incremental movement to apply with each step.
float scale = speed / distance;
float stepX = deltaX * scale;
float stepY = deltaY * scale;

// Add whole steps 0...n to our list.
for (int i = 0; i <= stepCount; i++) {
    steps.Add(new PointF(posx + i * stepX, posy + i * stepY));
}

// If there's any remainder, add our fractional step to arrive exactly.
if (wholeStepCount < stepCount) {
    steps.Add(new PointF(headX, headY));
}

```

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


title: Wrong uv parsed from obj

text:
# Question
Title: Wrong uv parsed from obj
I have written an obj parsing function and the result of his parsing can be drawn correctly. But if the uv is not generated by default by the modelling software, he will have problems with the uv. I looked at the obj file again and found something puzzling me. first,this is the obj file(the vn being deleted):

```
g default
v -2.211628 0.000000 2.211628
v 0.000000 0.000000 2.211628
v 2.211628 0.000000 2.211628
v -2.211628 0.000000 0.000000
v 0.000000 0.000000 0.000000
v 2.211628 0.000000 0.000000
v -2.211628 0.000000 -2.211628
v 0.000000 0.000000 -2.211628
v 2.211628 0.000000 -2.211628
vt 0.098901 0.197802
vt 0.401099 0.197802
vt 0.959707 0.080586
vt 0.098901 0.500000
vt 0.540293 0.500000
vt 0.959707 0.500000
vt 0.098901 0.802198
vt 0.540293 0.919414
vt 0.959707 0.919414
vt 0.401099 0.500000
vt 0.401099 0.802198
vt 0.540293 0.080586
s 1
g pPlane4
usemtl initialShadingGroup
f 1/1/1 2/2/2 5/10/3 4/4/4
f 2/12/2 3/3/5 6/6/6 5/5/3
f 4/4/4 5/10/3 8/11/7 7/7/8
f 5/5/3 6/6/6 9/9/9 8/8/7

```

I labeled these data on their corresponding images

the face1 is 1/1/n 2/2/n 5/10/n,it's mean that the triangle is v1,v2,v5 and the uv is t1,t2,t10, so why the v125 map to the green part?Isn't it supposed to be the brown part? It doesn't look like this is simply flipping the uv over. This may have something to do with the left and right hand coordinate system. uv's are created in maya and rendered in the Unreal engine. below is the image in my rendering,The problem seems complicated enough, if I need the parse code I will upload it, thanks

# Answer
> 1 votes
The Wavefront OBJ you are using has quads which presumably you need to convert to triangles. It's likely related to that code in your reader in terms of the exact winding you are using.

```
// Convert polygons to triangles
uint32_t i0 = faceIndex[0];
uint32_t i1 = faceIndex[1];

for (size_t j = 2; j < iFace; ++j)
{
    uint32_t index = faceIndex[j];
    indices.emplace_back(i0);
    if (ccw)
    {
        indices.emplace_back(i1);
        indices.emplace_back(index);
    }
    else
    {
        indices.emplace_back(index);
        indices.emplace_back(i1);
    }

    i1 = index;
}

```

In addition as you've hinted to yourself, the winding and view-orientation of the modeler does not necessarily match your rendering setup. This is why many exporters have options to flip the U (i.e. `U = 1 - u`), flip V (i.e. `V = 1 - v`), and/or flip the Z (i.e. `Z = -z`).

> See WaveFrontReader.h for some working code you can compare against. It handles some behavior as well like negative index values you should be aware of for your own reader.

---
Tags: directx, uv-mapping, obj
---


# Question
Title: How to save user progress and report on the server?
I'm developing a game that consists of many mini-games. We want the user username to be recorded and saved. Also, each time the user plays one of the mini-games, some reports for that specific mini-game played should be saved on the server referring to the username.

So, we now save user data on the server, but I think in a way that is too dirty.

On the first-time login, we get the username, I made a PHP file on my DirectAdmin server that checks if a posted username folder name already exists. If not, the PHP file will create a folder with that username.

Then, every time the player plays a mini-game, that specific report is uploaded to the user's folder that was previously created (the report for each mini-game played consists of its time length, number of correct answers, wrong answers and some other parameters like this).

What I now want, is to do some queries on user data, but with this kind of saving it's not possible. Even worse, when the number of users grows, the number of folders created will become too high, and I have performance concerns.

What is the solution to my challenge? Should I use some game backends like GameSparks or something?

# Answer
> 1 votes
Using some kind of database framework seems like the right approach. You could use SQL or something similar right in your own server, or interface with a database service like Amazon or Google. Using a third party service means fast and huge storage and less worry about low-level details, but you have to pay and have to learn a new API. Self hosting is complex and more time spent working on low-level tasks. But then you have more control and it’s probably cheaper.

Although as your storage/ access needs grow beyond a certain threshold the third party options might actually become cheaper.

As @DMGregory noted. Beware of storing sensitive info!

---
Tags: unity, databases, unity-networking
---


# Question
Title: Custom editor script not updating when values are changed from script?
I have a custom editor script which I have used to neatly arrange a huge group of variables into tabs. Some of these variables change in the script and it's very useful to see what they are without printing them to the console. Before I wrote my custom inspector the values would change at runtime as expected. However, after writing my custom inspector the values only update when I first click the object in the hierarchy.

**How would I go about making my editor script update whenever the values change?**

This is my stripped down code:

```
using UnityEngine;
using UnityEditor;

[CanEditMultipleObjects]
[CustomEditor(typeof(Car))]
public class CarEditor : Editor
{
    private SomeScript myTarget;
    private SerializedObject soTarget;

    private const string tab1 = "tab1";
    private const string tab2 = "tab2";
    private const string tab3 = "tab3";

    private SerializedProperty var1;
    private SerializedProperty var2;
    private SerializedProperty var3;

    private void OnEnable()
    {
        myTarget= (SomeScript)target;
        soTarget = new SerializedObject(target);

        var1 = soTarget.FindProperty("var1");
        var2 = soTarget.FindProperty("var2");
        var2 = soTarget.FindProperty("var2");
    }

    public override void OnInspectorGUI()
    {
        //DrawDefaultInspector();
        EditorGUI.BeginChangeCheck();

        myTarget.toolbarTab = GUILayout.Toolbar(myTarget.toolbarTab, new string[] { tab1, tab2, tab3 });

        switch (myTarget.toolbarTab)
        {
            case 0:
                myTarget.currentTab = tab1;
                break;
            case 1:
                myTarget.currentTab = tab2;
                break;
            case 2:
                myTarget.currentTab = tab3;
                break;
        }

        if (EditorGUI.EndChangeCheck())
        {
            soTarget.ApplyModifiedProperties();
            GUI.FocusControl(null);
        }

        switch (myTarget.currentTab)
        {
            case tab1:
                EditorGUILayout.PropertyField(var1, true);
                break;
            case tab2:
                EditorGUILayout.PropertyField(var2, true);
                break;
            case tab3:
                EditorGUILayout.PropertyField(var3, true);
                break;
        }
    }
}

```

# Answer
I just ran into this problem for the first myself... surprised there's no answer to be found anywhere.

After poking at it for a bit, I found a solution myself. Turns out, an inspector doesn't repaint unless you interact with it, even if the values it's displaying update runtime. You can force it to refresh once per frame by placing:

```
if (EditorApplication.isPlaying)
  Repaint();

```

At the bottom of your OnInspectorGUI override. I suspect this is what the default inspectors are doing behind the scenes.
> 3 votes

# Answer
Override `RequiresConstantRepaint()`: https://docs.unity3d.com/ScriptReference/Editor.RequiresConstantRepaint.html
> 3 votes

# Answer
Stacked with exactly the same problem.

What this code does is change the label above objects(in my case players) head. Inside **OnInspectorGUI**:

```
EditorGUI.BeginChangeCheck();

int currentScore = EditorGUILayout.IntField(...)

if (EditorGUI.EndChangeCheck())
{
    (sp.objectReferenceValue as Object).ChangeLabelAboveObject(currentScore);
    EditorApplication.QueuePlayerLoopUpdate();
    GUI.FocusControl(null);
}
```

Explanation: sp - SerializedProperty, Object - any MonoBehaviour you like.

But the main: everything goes ok when I added EditorApplication.QueuePlayerLoopUpdate.

Hope this will help someone, because I was looking for this for hours.
> 0 votes

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


# Question
Title: Unity: I need to edit my prefab but I can't move anything inside it!
I imported a character into Unity and turned him into a prefab. I couldn't get my custom "Look-At" script to work for the eyes, which are children of the prefab I imported. So I opened the prefab and discovered (to my *HORROR*) that I am unable to transform his eyes AT ALL, even in the prefab-view. It's like his body parts are made of stone, or something! I checked his eyes in the Blender scene and don't see any animation data attached to them. So how could this happen? How can I fix it?

The eyes ARE children of a bone called "root", which I don't think has any keyframes in any animation. Further, all my bones imported as empties.

# Answer
Right click the sub-object in prefab-view, choose "Unpack Prefab".

I ask a lot of questions with simple solutions but I didn't find any other questions describing this kind of problem. I will keep this up in case somebody else is having the same problem.
> 1 votes

# Answer
It appears that this character is set up with an Animator. This animator controls the transforms of all the sub-objects, which is why you can't change those manually. It is recommended that you control this characters individual parts using the animation system. But if you really don't want that, then you can find and remove the animator component. That should allow you to freely manipulate all the sub-objects.
> 0 votes

---
Tags: unity, animation, prefabs
---


title: Label text not updating every frame

text:
# Question
Title: Label text not updating every frame
So, I want to code something in Godot, but the `Label` text doesn't get updated every frame. Here's the script I attached:

```
extends Node2D

onready var SportVar = $Label
var counter = 0

func _ready():
    pass

func _process(delta):
    SportVar.text = (str(counter))

```

# Answer
I'm assuming your script is attached to a parent `Node2D` node, and **Label** is a `Label` child node.

Your script *is* updating the content of the Label. The reason you don't see updates is that the content itself isn't changing.

Adding the following line to the `_process()` function will update the text:

```
func _process(delta):
    counter += 1    # Increase value before updating text
    SportVar.text = (str(counter))

```

This is a continuous text update. If you want to update on value changed only, you can use signals instead.
> 3 votes

---
Tags: godot
---


title: Ray vs AABB (2D) reporting hits

text:
# Question
Title: Ray vs AABB (2D) reporting hits
I've been working a 2D ray versus AABB implementation. I worked it out on paper, then read about a popular "branchless" algorithm. I decied to try the branchless one, but it gives me completely wrong results when one of the components is zero. I used the "naive" version and it's still reporting bad hits. (The difference is the check for a zero component vs simply allowing 1.0-over-0.0 to turn into +/- infinity)

Example: https://tavianator.com/2011/ray\_box.html (adapted to C below):

```
#include <float.h>
#include <math.h>
#include <stdio.h>
typedef struct vec2_s { double x, y; } vec2_t;
typedef struct box_s { vec2_t min, max; } box_t;
typedef struct ray_s { vec2_t x0, n; } ray_t;

int intersection(box_t b, ray_t r) {
    double tmin = -INFINITY, tmax = INFINITY;

    if (r.n.x != 0.0) {
        double tx1 = (b.min.x - r.x0.x)/r.n.x;
        double tx2 = (b.max.x - r.x0.x)/r.n.x;

        tmin = fmax(tmin, fmin(tx1, tx2));
        tmax = fmin(tmax, fmax(tx1, tx2));
    }

    if (r.n.y != 0.0) {
        double ty1 = (b.min.y - r.x0.y)/r.n.y;
        double ty2 = (b.max.y - r.x0.y)/r.n.y;

        tmin = fmax(tmin, fmin(ty1, ty2));
        tmax = fmin(tmax, fmax(ty1, ty2));
    }

    return tmax >= tmin;
}

```

These don't work at all for me when one of direction components is zero. Consider the example below that used the method. This is an AABB from (-1,2) to (1,4). The ray is at (3,0) and goes up. Standard Cartesian coordinates.

**This returns true that there is an intersection. Clearly there is not. It seems to be ignoring the X-axis completely.**

```
int main() {
    box_t b;
    ray_t r;

    b.min.x = -1; b.max.x = 1;
    b.min.y =  2; b.max.y = 4;

    r.x0.x = 3;
    r.x0.y = 0;
    r.n.x = 0;
    r.n.y = 5;

    printf("Intersection? %s\n", intersection(b,r)? "yes" : "no");

}

```

I've worked it out on paper, and I came to the conclusion that when a component of the ray's direction vector is zero, then the test for that axis is reduced to a simple interval check. However, obviously, this requires quite a bit of "branching". Before I implement what I have on paper, can anyone explain to me what is going wrong here? I've read various implementations of the so-called "branchless" algorithm, and they all seem to do more or less the same thing and even mention that it correctly (?) handles cases when a component is zero -- but it's failing badly in my unit test. What am I missing?

# Answer
> 0 votes
The short answer is that the "branchy" code in the blog post is wrong, and my intuition is correct. The branchless does work correctly, as explained the blog post.

---
Tags: collision-detection, aabb, ray
---


# Question
Title: How do I handle a non-hierarchical, referential network of game data?
I've been using JSON to store a lot of my game's data. I love it compared to my previous workflow. Having a human-readable hierarchy of arbitrary information is a godsend. My needs have grown more complicated, however, and this solution doesn't work as well anymore.

I need my data entries to be able to reference each other. I devised the convention that any string prefixed with an "@" character described a relative or absolute path to another point in the JSON document. This worked when it was simple, but any time major reorganization was required all those references broke.

How does on accomplish this task? I'd love an editor that could jump to referenced data, or allow values to be edited where they are referenced, and would auto-update all those references for me when I change how they're organized. Frankly, forms work better for simple data entry tasks than text editors built for code. But then, I also want to work in a file format that's not going to fray my nerves to have to parse later when I'm bringing the file into my game, which is why I've preferred formats like JSON and CSV that are human readable and relatively simply.

What are the best practices for this scenario?

**Edit:** Some more information as requested in the comments:

I’d hoped to make my data outside my coding environment using a more appropriate tool, then to import it into my final project as a resource that could be compiled into the executable. At runtime it functions as a resource to be read from, but not written to. The data is referred to by runtime procedures that treat it as patterns for generating objects based on random weighted parameters. The generated objects are given references to the data and other objects they need to function. Anything that needs to be created, changed, or deleted lives in something generated, not the original data. The data referenced needs a network topology so that objects referencing its nodes can traverse the data by following the edges between those nodes in search of what they need.

All the necessary data exists in one big object, with no outside links to, for instance, the internet. Although, I will be treating generated objects similar to objects in my dataset as they in turn can be generated from and referenced. I suspect I’ll be wanting to reuse whatever solution I devise for my data to serialize a game state of complex, linked, arbitrary and non-homogeneous generated objects to the users hard drive between play sessions.

# Answer
Sounds like you need an SQL database. This allows you to reference other objects by keys. If you want it to be human readable you can build a system to save it to a text file or CSV yourself. Although if you're using a popular engine you might be able to find a prebuilt system that does something like this for you already.
> 0 votes

---
Tags: data-structure, databases, data
---


# Question
Title: How to create endless background in a 2d top down game?
I have a seamless background sprite, and I do not want the player to be able to reach the edge of the background.

Setting huge width and height in tiled drawmode doesn't sounds like a solution. How can I make something like this?

I want the background to appear outside the camera in the direction the player is moving.

I think instead of instantiating and destroying background panels every time I should once create them and then change their position.

# Answer
> 0 votes
Attached background sprite to camera and then used that shader

**Remember to set the sprite wrap mode to "repeat"**

---
Tags: unity, sprites
---


# Question
Title: Unity: Factory design pattern issues when respawning
I'm having an issue with the powerup system I've implemented in a 2D platformer I've been working on. The powerup system as it is currently implemented works for each of the three types of powerups on their own, but as soon as I include multiple powerups within a scene, I start to get issues. Also, if it helps, I'm pretty sure the design pattern I'm using here is an abstract factory. I'm not entirely sure, though. It's been a while since my last design patterns course in grad school.

The powerup system works as follows: There are three types of powerups that change some sort of player attribute (jump height, speed, and wall grip) when they're picked up. Upon colliding with the powerup, a countdown timer appears in the corner of the screen that indicates how long the effect will be active for. After the timer runs out, the normal player attributes are restored. The powerups will also respawn when the player dies.

I've ran a couple different test cases to determine what actions cause particular issues and here's what I've come up with so far:

* Everything works the way it should when only a single powerup is collected and the player dies. Powerup respawns properly.
* If I collect a powerup, and then collect another one, the first powerup does not respawn when the player dies. This happens regardless of whether or not the timer expires before collecting the second powerup.
* When a second powerup is collected, the timer does not reset properly and continues counting down from the current timer number from the previous powerup.

Here's the abstract powerup class:

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

[RequireComponent(typeof(Collider2D))]
public abstract class Powerup : MonoBehaviour
{
    [Range(1, 10)]
    public int duration = 10;
    public AudioManagerScript audioManager;
    public GameObject sceneAudioManager;

    public Image movementBoostImg;
    public Image jumpBoostImg;
    public Image wallGripImg;

    protected PlayerController player;

    private Timer timer;

    protected virtual void Start()
    {
        timer = Timer.Instance;
        sceneAudioManager = GameObject.FindWithTag("SceneAudio");
        audioManager = sceneAudioManager.GetComponent<AudioManagerScript>();

        movementBoostImg.rectTransform.sizeDelta = new Vector2(Screen.width, Screen.height);
        jumpBoostImg.rectTransform.sizeDelta = new Vector2(Screen.width, Screen.height);
        wallGripImg.rectTransform.sizeDelta = new Vector2(Screen.width, Screen.height);
    }

    protected virtual void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            audioManager.PlaySound(0);
            player = collision.GetComponent<PlayerController>();
            PerformCountDown(duration);
            timer.powerup = gameObject;
            StartPowerup();
            gameObject.SetActive(false);
        }
    }

    protected virtual void PerformCountDown(int duration) => timer.DoCountdown(duration, EndPowerup);

    protected abstract void StartPowerup();

    protected abstract void EndPowerup();
}

```

And here's an example of one of the more specific powerups:

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

public class MovementPowerup : Powerup
{

    public float fastMovementSpeed = 15.0f;
    public float normalMovementSpeed = 9.0f;

    protected override void StartPowerup() {
        player.movementSpeed = fastMovementSpeed;
        audioManager.PlaySound(6);
        movementBoostImg.DOFade(1, 1).OnComplete(() => movementBoostImg.DOFade(0, 1));
    }
    protected override void EndPowerup() => player.movementSpeed = normalMovementSpeed;
}

```

Additionally, the timer singleton is as follows:

```
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class Timer : Singleton<Timer>
{
    public GameObject holder;
    public Image image;
    public Sprite[] seconds;

    [HideInInspector] public GameObject powerup;
    public Action OnDone;

    public void DoCountdown(int start, Action OnDone)
    {
        this.OnDone = OnDone;
        holder.SetActive(true);
        StartCoroutine(CountDown(start));
    }

    private IEnumerator CountDown(int duration)
    {
        image.sprite = seconds[duration - 1];

        yield return new WaitForSeconds(1);

        if (duration >= 2) {
            StartCoroutine(CountDown(duration - 1));
        } else {
            OnDone?.Invoke();
            holder.SetActive(false);
        }
    }

    public void ResetTimer()
    {
        if (powerup == null)
            return;

        StopAllCoroutines();
        powerup.SetActive(true);
        holder.SetActive(false);
    }
}

```

I've had a few ideas as to how to approach this particular problem, but I'm not entirely sure what that best approach might be. I have a suspicion that the answer lies in the timer class. My first thought would be to implement logic that would check to see if a powerup is already active in the timer class and just call a function to restart the timer when a new powerup is collected, but I'm not sure if that's the ideal solution. Any thoughts would be much appreciated.

Also, as a side note, I've made a few posts on here over the past few years and I've been absolutely astounded by the unprofessionalism in some of the responses I've received. I will often include everything that I can immediately think of related to my issues, but I am not perfect and will sometimes inadvertently omit information that might prove useful in finding a solution. Don't be a jerk. Politely ask for whatever it is you think my original post should have included and I'd be more than happy to provide it under most circumstances. The elitist and outright rude attitudes, especially of some of the higher-ranking users, is absolutely disgusting and toxic. Please choose to be patient and kind to those of us with less experience in certain areas.

# Answer
I think thank problem lies on your timer class being a singleton. Meaning you only have one timer, but each power up should probably have its own timer.

I think this speaks to a general problem with your architecture.

Your power ups should probably be responsible for timing themselves. And also adding themselves to a list or something when expired so that they can be respawned.

I suggest having each power up, when collided with, call a method ApplyPowerup. That method also starts the timer. And also Calls AddSelfToRespawnList.

When the timer expires, it calls RemovePowerup.

Then when the player dies it fires an event that the RespawnSystem is listening for. And then it iterates through all power ups that added themselves to the RespawnList. and respawns them.

In general, you want to group behaviour that’s related into the same class. And keep unrelated behaviour separate. So it’s the powerup that times itself and then expires. It’s not the timer itself that cares about power ups. So you could have a Timer class (Not a singleton) and then each powerup uses an instance of that class to actually do the timing. But the timer should know nothing about the existence of power ups.

So in conclusion, I think it makes sense to have a Timer class that just times something maybe with a duration and a countdown. And then the Powerup class USES that timer to keep its time.
> 2 votes

---
Tags: unity
---


title: How to wait until the frame is done?

text:
# Question
Title: How to wait until the frame is done?
According to Google, `await ToSignal(GetTree(), "idle_frame");` should wait until the next frame. However, in Godot 4.0's current master branch (**mono build!**), this fails with:

```
Ready(): In Object of type 'SceneTree': Attempt to connect nonexistent signal 'idle_frame' to callable 'Node3D(SomeScript.cs)::SignalAwaiterMiddleman::idle_frame'.

```

It seems like the API changed in Godot 4.0. Do you have any ideas how to wait until either the next frame or until the current frame has finished?

# Answer
*Disclaimer: Mono Build? I haven't tried at the time of writing.*

This is the GDScript 2.0 you would be trying to mimic in C#:

```
await get_tree().process_frame

```

Thus, I believe in C# it should say:

```
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);

```
> 6 votes

---
Tags: c#, godot-4
---


# Question
Title: How to create a game app in Game Maker Studio for Chrome OS
There are multiple app types in Game Maker Studio you can export to. Which one would be for a Chromebook? I've tried to research the topic, but I haven't seen anything that clearly states if GMS can even create a game for use on a Chromebook. It seems there may be a lack of communication between me and the search engine, depending on if I know the correct terms for what I'm trying to look for. For example, there's macOS, Windows, iOS, etc. But I don't see Chrome OS or anything. What would be compatible with a Chromebook?

# Answer
> 1 votes
Chrome OS devices run on top of Gentoo Linux, but Google officially supports the installation of Android apps on Chromebooks. This means that you can install apps from the Play Store or sideload them from an external source.

Then, you can export your GMS project to Android. Your game should support both touch and mouse/keyboard input so that it'll work on most Chromebooks.

Once your `.apk` file is ready, you can install and use **ADB** on your Chrome OS device to install your game. If unsure about how to do it, you can find several guides, such as this one.

---

**EDIT** Apparently, in the Player settings, *Configuration* section under the *Other Settings* pane, you can choose whether your `.apk` shall run on any Android-based OS, only on mobiles/TVs, or only on Chrome OS devices. Also, an additional option for Chrome OS input simulation is available:

This may help you when developing a game for Chrome OS-only that you don't want to work on other Android devices instead.

---
Tags: game-maker, game-maker-studio-2
---


# Question
Title: Pixelart loses quality when rotated in unity
Sorry, still fairly new to the game here but my pixel art gets little ridges on it when I rotate it in unity. I'd like the pixels to rotate all together. Is this just because I need to make my pixels "bigger" in relation to the camera, or is there some other solution? I've attached a picture of the original and how it looks in-game rotated. Once again, sorry if this is a stupid question.

# Answer
Any image rotated will produce artifacts, filtering helps, see here some examples from @Philipp's commentary link:

What basically happens is that when you rotate a image, you're trying to rotate pixels, which are square based, see the example of rotated pixels without filters, it has unpleseant artifacts, scalling the sprite will not solve your issue.

Any image filtering will work and be the easiest solution, it will however make your sprite a little blurry.

The hard solution is to make other versions of your helicopter, drawing your object in the angles you need and calling for them at the times you need, I will try to find a example of what I am talking about:

There are a lot more complex solutions, but that would be overkill IMHO.

TLDR: Use filtering, it helps with image scalling and rotations, if you want the pure pixel look, either lower resolution and globally disable your rendering filters, or make your own rotations in like a sprite sheet.
> 3 votes

---
Tags: unity, 2d, rotation, pixel-art
---


title: How are Spot It cards generated?

text:
# Question
Title: How are Spot It cards generated?
**Spot It** is a card game 55 cards. Each card has exactly 8 symbols on it (though the total number of different symbols used in the 55 card set is 57). For any two cards in the deck, they share exactly one symbol. For example:

What is the algorithm behind building this deck? Intuitively I think there is a formula for creating a deck of `N` cards, with `I` symbols per card and using `J` total symbols.

For the life of me I cannot figure it out.

Can it be done?

# Answer
Stand-Up Maths did a great video about this, explaining how you can create a "mono-match" set of cards as points in a finite projective plane.

You can arrange your cards into a **square grid with a prime number of rows/columns**, and assign shared symbols to all the cards that lie in a line. I've taken a still from the video to draw some of these lines:

* Every card in the top row has a shared symbol (the lightning bolt)
    + Every card in the second row has a shared symbol (the anchor)
    + ...and so on for all 7 rows.

* Every card in the left column has a shared symbol (the cactus)
    + Every card in the second column has a shard symbol (the treble clef)
    + ...and so on for all 7 columns.

* Every card along the diagonal from the top-left to bottom-right card has a shared symbol (the car)
    + So does every card following a "down-one, right-one" path starting from the second card (the maple leaf)
    + ...and so on for every one of these down-right 45-degree lines. Note that these lines have to wrap around the square and come back in from the other side.

You can do this for every other diagonal - every pattern of "down one, right X" for some value of X. (In fact, the columns are just the pattern "down one, right zero", and the rows are kind of "down one, right infinity" )

Here's just a couple of lines with "down one, right three", since these get harder to follow in the diagram if we chart them all:

So that gives us \\$\left(\text{width of square} + 1\right) = (7+1) = 8\\$ sets of lines we can draw through the set, which means 8 symbols per card, one for each of these line slopes. Any two cards we choose must both lie on exactly one of these lines (either in the same row, the same column, or along one of the diagonals with a slope determined by their relative positions in the grid), and so must have exactly one of their 8 symbols in common.

We could stop there and have a playable game of \\$\left(\text{width of square}\right)^2 = 7^2= 49\\$ cards and \\$\left(\text{width of square}\right) \cdot \left(\text{width of square + 1}\right) = 7 \cdot 8 = 56\\$ unique symbols. But we can take a step further using projective geometry.

You might notice there's some extra cards sitting outside the grid. 8, in fact, corresponding to the 8 different sets of parallel lines we can draw through the grid. These correspond to the "points at infinity" where those "parallel" lines meet. The top right one is where the horizontal lines along the rows meet, and it has one symbol from every row. The bottom one is where all the vertical lines along the columns meet, and it has one symbol from every column. And so on for the diagonals.

That gives us 7 symbols on each of these cards which must match any given card we pick from the main 7x7 grid. (Every card is in *some* row or *some* column or *some* diagonal with slope m...) But if two of these infinity cards get drawn together, we also need a symbol common to them. So we add one additional symbol, the horizon joining the lines at infinity (the clown face), bringing them up to the same 8 symbols as all the other cards.

That gives us a total of \\$\left(\text{width of square}\right)^2 + \left(\text{width of square} + 1\right)= 7^2 + (7+1) = 49 + 8 = 57\\$ possible cards, using \\$\left(\text{width of square}\right) \cdot \left(\text{width of square} + 1\right) + 1 = 7 \cdot (7+1) + 1 = 7 \cdot 8 + 1 = 56 + 1 = 57\\$ unique symbols.

But you note that Spot It only has 55 cards. They left two out, as is mentioned in the Stand-Up Maths video. It's unclear why, but actually removing any number of cards doesn't break the guarantee that any two remaining cards have exactly one symbol in common. It just makes some symbols slightly less frequent than others, which might be of optimization interest if you were to become a highly competitive player. (For example, it's somewhat safe to look for the snowman last - there are two fewer of that symbol in the version shown in the video)

As mentioned, this construction works for squares whose width is **prime** \- that's the **order** of the finite projective plane we're using. Keeping it prime ensures any diagonal you pick will only cross each row/column once, so you don't double-up on matched symbols. The video mentions that finite projective planes also exist for orders that are *powers* of primes, but this construction won't work for them, and you'll need a different technique. (There is an example shown in the video for order 4, if that's of interest) No finite projective planes are known with orders that are *not* powers of primes, so there you might be out of luck.

But, if you want a number of cards that doesn't neatly fit the \\$n^2 + n + 1\\$ for prime \\$n\\$ pattern above, you can always bump up to the next \\$n\\$ that *does* let us use this neat construction, and then delete cards until you get down to your target number - trying to keep your deletions roughly balanced between the symbols so you don't unintentionally skew the appearance probabilities too wildly.

He also shows one other way of thinking about this problem, based on what's called a "cyclic difference set". You start by arranging the cards in a circle:

If you can find a set of cards to mark with one symbol, so that each possible spacing between them occurs exactly once, then you can place your next symbols by just rotating this set of positions by some number of steps n. The two patterns will then overlap on one and only one card.

Here are the positions to use for differing numbers of symbols per card from the video, though it doesn't give a means to calculate them for other numbers:

| Symbols per Card | Total Card Count | Position offsets |
| --- | --- | --- |
| 3 | 7 | 0, 1, 3 |
| 4 | 13 | 0, 1, 3, 9 |
| 5 | 21 | 0, 1, 6, 8, 18 |
| 6 | 31 | 0, 1, 3, 10, 14, 26 |
| 7 | N/A | No Solution |
| 8 | 57 | 0, 1, 3, 13, 32, 36, 43, 52 |
> 2 votes

---
Tags: mathematics, game-mechanics, card-game
---


# Question
Title: Unity C# XML How to load a saved position and a saved stage
I have a problem. I already figured out how to save the player stats (including the player position). But every time I load it back, the player ends up in the saved position but still within the open scene, not the saved scene. Nothing else got passed, no errors. Nothing happened except for the player ending up in the saved position, yet still within the open scene, not the saved scene. Here is the code:

```
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.SceneManagement;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;

    public class ReadWrite : MonoBehaviour
    {
        public string path;
        public PauseScreen ps;
        public SaveData activeSave;
        public bool hasLoaded;
        public PlayerController ball;

        void Start()
        {
            hasLoaded = false;
            ps = FindObjectOfType<PauseScreen>();
            ball = FindObjectOfType<PlayerController>();
        }

        public void SaveGame()
        {
            string dataPath = Application.persistentDataPath + "/" + "Save.txt";
            activeSave.unitName = SceneManager.GetActiveScene().name;
            SpawnPointChoice.SetSpawnPoint(activeSave.unitName);
            activeSave.score = ScoreSystem.score;
            activeSave.lives = LivesSystem.lives;
            var serializer = new XmlSerializer(typeof(SaveData));
            var stream = new FileStream(dataPath, FileMode.Create);
            serializer.Serialize(stream, activeSave);
            stream.Close();
            Debug.Log("Your game has been saved.");
            ps.Resume();
        }

        public void LoadGame()
        {
            string dataPath = Application.persistentDataPath + "/" + "Save.txt";
            if (!File.Exists(dataPath))
            {
                Debug.LogError("FILE NOT FOUND");
            }
            var serializer = new XmlSerializer(typeof(SaveData));
            var stream = new FileStream(dataPath, FileMode.Open);
            activeSave = serializer.Deserialize(stream) as SaveData;
            stream.Close();
            ball.transform.position = activeSave.transformPosition;
            SceneManager.LoadScene(activeSave.unitName);
            ScoreSystem.score = activeSave.score;
            LivesSystem.lives = activeSave.lives;
            Debug.Log("Your game has been loaded");
            hasLoaded = true;
            ps.Resume();
        }
    }

    [Serializable]
    public class SaveData
    {
        public Vector2 transformPosition;
        public int score;
        public int lives;
        public Scene unit;
        public string unitName;
    }

```

The line where I have a comment saying "Load saved scene" is where I need assistance. Any would be appreciated.

Edit: Now, right after the game was successfully loaded, it reloaded the start of the game.

Sincerely, Jay Burch

# Answer
`SceneManager.LoadScene("")` tries to load a scene with an empty name, which is not going to work. You likely intend to do `SceneManager.LoadScene(activeSave.unit.name)`, which is the variable where you saved the name of the current scene to.
> 1 votes

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


# Question
Title: Should I be worried about textures higher than 4K?
Upon developing a big project, it just happened that when stitching all the thousands of animations spriteframes of a **single character** together, the sprite sheet turned around to **2K by 13K texture!!**

(╯°□°)╯︵ ┻━┻

Some GPUs cannot display above 4K textures, and there's even some limitation in some engines that they will add blank spaces to fill the areas to make a power of two texture. To avoid these problems, I was currently designing a workflow to segment these textures to 4 or 6 different textures of no more than 4K resolutions, like 4096x4096 at max.

But then, is it worth at the end? ಠ\__ಠ My targeted platform is **desktop only** so I am not so much worried about VRAM, the compression I am doing is for video memory, and it reduces the VRAM quite a bit without too much quality loss. Also all the work is currently being done by a packing algorithm, so it shuffles the sprites based on their bounding box, so not a lot of manual work here, it's all automated.

What you guys think?

# Answer
You'll probably be fine with textures up to 16384x16384 on modern hardware as that's the limit in DX11. For older hardware (DX9 era), you probably want to set the limit at 2048x2048.

The reason that some engines want power of two sized texture widths and heights is that GPUs can't do mip mapping for non-power-of-two textures. Mip mapping is probably a good thing for your 2D sprites as it will give you better image quality when scaling them. Scaling will happen because PCs have variable screen resolutions, and you may also want to scale them for gameplay reasons.
> 2 votes

---
Tags: textures, graphics, optimization, texture-atlas
---


# Question
Title: How do I advertise a game about writing role play?
I head & develop a very niche game called "Verdict", which you can read about here. Basically, Verdict is a writing game. It has the mechanical elements of an RPG and the multiplayer elements of an MMO, but you can only gain experience by writing roleplay with other players.

It's pretty similar to MUDs/MUSHes, if you're familiar with those.

I've been wracking my head on how to advertise this, though. Advertising to MUDs is an option, but they're very old and not very popular- there are newer RP venues like GTA V RP or Neverwinter Nights, but I'm not familiar enough with the scenes to know how to "break in", if that makes sense.

# Answer
First of all, you need to figure out your target audience.

Is it freeform roleplayers / collaborative writers who are looking for a more gamified medium of expression? Or is it MMORPG players who are looking for a more roleplay-centric game?

The decision which one you choose would influence both *where* you present your product and *how* you present it.

In each case you would present it as "what you already know, but in the way you want it". When you target the freeform roleplayers, you would present it as a new platform for roleplaying, but with gamification features. When you target MMORPG gamers, then you would present it as a new MMORPG, but with a much larger focus on roleplay.
> 0 votes

---
Tags: mmo, rpg, online
---


# Question
Title: Isometric projection, calculate camera angle for specific tile height
I'm experimenting with different tile dimensions while rendering 3D assets for an isometric game (or dimetric to be exact). Everyone does a 2:1 ratio so the tiles in isometric view are 256wx128h, which requires a 30 degree down-angle of the camera. I'm trying to find out what angle my camera needs to be in order to produce a tile that is 256wx160h.

I suck at math so I found this link but it's giving me some questionable results https://c2isogame.wordpress.com/2017/02/10/how-to-get-height-level-of-tile-in-iso-view/amp/

According to the page, the formula for a tile 256wx128h is `atand(128/sqrt(256^2+256^2))`, which equals 19.47, and that's obviously not 30.

What is the general formula to find camera angle for any tile size in dimetric projection?

# Answer
> 3 votes
What we want to find here is an angle that foreshortens the depth axis of your plane to your target height:width ratio \\$\frac h w\\$.

If we chose the angle 0°, we'd be looking parallel to the depth axis, so it would be foreshortened down to 0%. We'd be looking at the tile edge-on, so it would have no height at all.

If we choose the angle 90°, we'd be looking straight down at the plane, so it wouldn't be foreshortened at all, and would be drawn at 100% the width of the unforeshortened horizontal axis.

So we have some function of angle that's 0 at 0° and 1 at 90° - sounds a lot like Sine!

Let's prove it. Looking down with an angle of \\$\alpha\\$ on a line of length \\$l\\$ The length of the projection in our image plane is \\$p\\$:

You'll notice that the two triangles are similar (same angles). So the ratios between their sides will match. Let's call the vertical rise \\$v\\$ and the hypotenuse of the bottom triangle \\$h\\$. Then we can write...

$$\begin{align} \frac p v &= \frac l h\\ p &= l \frac v h\\ p &= l \sin \alpha \end{align}$$

Which gives us \\$\alpha = \sin^{-1} \frac p l\\$

For the 2:1 dimetric projection, that's \\$\sin^{-1} \frac 1 2 = 30 ^ \circ\\$

And for your 256:160 target, that's \\$\sin^{-1} \frac {160} {256} = \sin^{-1} \frac 5 8 = 38.682... ^ \circ\\$

---
Tags: mathematics, isometric
---


title: How do I use a ball as a wheel?

text:
# Question
Title: How do I use a ball as a wheel?
I'm brand new(ish) to Unity with a strong programming background. I understand the basics of "how to roll a ball" in Unity, but I have a custom model I made in Blender which I have imported as a two objects. What I would like to do is roll the ball while keeping the top part (called "Carrier") fixed above it. It was exported from Blender as one mesh, but I have unpacked it to use in Unity.

My thinking so far is to use a Rigidbody on the ball as a sub-component of the top part, which also has a Rigidbody, and apply a ConfigurableJoint from the ball to the carrier. So far, nothing seems to stay where I want it. Can someone put me on the right track for configuring the joint? Or if I'm completely on the wrong track, plz halp?

Here's what I tried so far:

but the top just flops around (sticking upright, because I locked the X and Z rotations).

#### UPDATE:

I tried @Philipp's suggestion (thanks!), but the whole thing separates when the game starts:

I tried with and without a rigidbody on the carrier, as well as several configurations of parenting (including totally separate objects).

# Answer
> 1 votes
Instead of using joints, I would just use a simple follower script:

```
public class FollowOtherObject : MonoBehaviour {

    public Transform other;

    FixedUpdate() {
        if (other != null) {
            transform.position = other.position;
        }
    }
}

```
1. Make the ball and the carrier two separate game objects.
2. Assign the script above to the carrier
3. Assign the ball to the inspector-property "other" of the FollowOtherObject component of the carrier.

This will glue the following object to the center of the followed object. When you want to control the offset, then it is a good idea to place an empty game object at the exact same position as the followed object and make that the following object. Then attach the object you actually want to follow as a child of the empty object. That allows you to control the offset by changing the offset between parent and child.

---
Tags: unity, rigidbody
---


# Question
Title: Fire only the currently equipped weapon, not all weapons
I have two guns and two different functions for it.

I pick up the weapon by making weapon a child of the parent player.

When the player presses the "Fire1" button, I want only the current weapon the player has picked up to shoot.

Unfortunately, with the code below, both weapons shoot, even the one that was not picked up.

How can I correct this?

```
public class weapon : MonoBehaviour
{
    public Transform firepoint1; //this is a firepoint
    public Transform firepoint2; //this is a firepoint

    public GameObject bulletprefab;
    public GameObject f;
    public GameObject f1;

    // Start is called before the first frame update
    void Start()
    {
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        rb.constraints = RigidbodyConstraints2D.FreezeRotation;
    }

    void shoot()
    {
         Instantiate(bulletprefab, firepoint1.position, firepoint1.rotation);
    }

    void shoot1()
    {
         Instantiate(bulletprefab, firepoint2.position, firepoint2.rotation);
    }

    void OnTriggerStay2D(Collider2D trig)
    {
        if (f.gameObject != null && gameObject.tag =="player")
        {
            if (Input.GetButtonDown("Fire1"))
            {
                shoot();
            }
        }
        if (f.gameObject != null && gameObject.tag == "player")
        {
            if (Input.GetButtonDown("Fire1"))
            {
                shoot1();
            }
        }
    }
}

```

# Answer
> 1 votes
I would substantially refactor this code. A weapon's job is to shoot *when it is commanded to shoot*. Knowing which weapon is equipped, and interpreting player inputs into commands is not the job of the weapon, but of a player inventory & character control script.

That could look something like this `WeaponHandler` script you can attach to your player character object, to handle picking up & firing weapons:

```
public class WeaponHandler : MonoBehaviour {

    public Transform weaponSlot;
    public string fireButtonName = "Fire1";

    Weapon _currentWeapon;

    // We listen for input in just one place,
    // and send a command to the weapon script when we want it to shoot.
    // This shoots the single instance we have equipped, not all weapons.
    public void Update() {
        if (Input.GetButtonDown(fireButtonName) && _currentWeapon != null) {
            _currentWeapon.Shoot();
        }
    }

    // Since you haven't shown us your weapon pick-up code,
    // I'm going to make some simple guesses here.
    // Replace this with the weapon pick-up method you like.
    void OnTriggerEnter2D(Collider2D trigger) {
        if (trigger.TryGetComponent(out Weapon collidedWeapon)) {
            PickUpWeapon(collidedWeapon);
        }
    }

    public void PickUpWeapon(Weapon newWeapon) {
        // Throw away our old weapon, if we had one.
        if (_currentWeapon != null) {
            Destroy(_currentWeapon.gameObject);
        }

        // Attach the new weapon to our carrying slot,
        // and snap it to a standardized position/orientation.
        newWeapon.transform.parent = weaponSlot;
        newWeapon.transform.localPosition = Vector3.zero;
        newWeapon.transform.localRotation = Quaternion.identity;

        // Record this as our weapon to fire from now on.
        _currentWeapon = newWeapon;
    }
}

```

Then the `Weapon` class can be simpler, and just fire when it's told:

```
public class Weapon : MonoBehaviour
{
    // End of the weapon muzzle(s), where bullets should spawn.
    public Transform[] firePoints;
    public GameObject bulletPrefab;

    public void Shoot()
    {
         // Spawn a bullet at the end of each muzzle.
         // (Here we assume the bullet script applies its own velocity).
         foreach (var firePoint in firePoints) {
             Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
         }
    }
}

```

You can now configure two separate weapons (or more!) with different bullets and fire points, and the `WeaponHandler` on the player will equip and fire just one at a time.

This structure also helps set you up for...

* Local Multiplayer: each player can have their own `WeaponHandler` that listens to just their own input.
* New Input System: this centralizes your input-listening in one place (the player character), making it easier to switch to the New Input System package, which handles input maps as swappable assets rather than a single global map.
* AI Weapon Users: this allows non-player characters to also use weapons by calling their `Shoot()` method, without needing a separate class of AI-only weapons.

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


# Question
Title: What kind of math is used by this camera panning script?
I'm not fluent in English so I apologize in advance. I have found a source code in order to pan camera by touch - here it is:

```
public class CameraHandler : MonoBehaviour {

    private static readonly float PanSpeed = 20f;
    private static readonly float ZoomSpeedTouch = 0.1f;
    private static readonly float ZoomSpeedMouse = 0.5f;

    private static readonly float[] BoundsX = new float[]{-10f, 5f};
    private static readonly float[] BoundsZ = new float[]{-18f, -4f};
    private static readonly float[] ZoomBounds = new float[]{10f, 85f};

    private Camera cam;

    private Vector3 lastPanPosition;
    private int panFingerId; // Touch mode only

    private bool wasZoomingLastFrame; // Touch mode only
    private Vector2[] lastZoomPositions; // Touch mode only

    void Awake() {
        cam = GetComponent<Camera>();
    }

    void Update() {
        if (Input.touchSupported && Application.platform != RuntimePlatform.WebGLPlayer) {
            HandleTouch();
        } else {
            HandleMouse();
        }
    }

    void HandleTouch() {
        switch(Input.touchCount) {

        case 1: // Panning
            wasZoomingLastFrame = false;

            // If the touch began, capture its position and its finger ID.
            // Otherwise, if the finger ID of the touch doesn't match, skip it.
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began) {
                lastPanPosition = touch.position;
                panFingerId = touch.fingerId;
            } else if (touch.fingerId == panFingerId && touch.phase == TouchPhase.Moved) {
                PanCamera(touch.position);
            }
            break;

        case 2: // Zooming
            Vector2[] newPositions = new Vector2[]{Input.GetTouch(0).position, Input.GetTouch(1).position};
            if (!wasZoomingLastFrame) {
                lastZoomPositions = newPositions;
                wasZoomingLastFrame = true;
            } else {
                // Zoom based on the distance between the new positions compared to the
                // distance between the previous positions.
                float newDistance = Vector2.Distance(newPositions[0], newPositions[1]);
                float oldDistance = Vector2.Distance(lastZoomPositions[0], lastZoomPositions[1]);
                float offset = newDistance - oldDistance;

                ZoomCamera(offset, ZoomSpeedTouch);

                lastZoomPositions = newPositions;
            }
            break;

        default:
            wasZoomingLastFrame = false;
            break;
        }
    }

    void HandleMouse() {
        // On mouse down, capture it's position.
        // Otherwise, if the mouse is still down, pan the camera.
        if (Input.GetMouseButtonDown(0)) {
            lastPanPosition = Input.mousePosition;
        } else if (Input.GetMouseButton(0)) {
            PanCamera(Input.mousePosition);
        }

        // Check for scrolling to zoom the camera
        float scroll = Input.GetAxis("Mouse ScrollWheel");
        ZoomCamera(scroll, ZoomSpeedMouse);
    }

    void PanCamera(Vector3 newPanPosition) {
        // Determine how much to move the camera
        Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
        Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed);

        // Perform the movement
        transform.Translate(move, Space.World);

        // Ensure the camera remains within bounds.
        Vector3 pos = transform.position;
        pos.x = Mathf.Clamp(transform.position.x, BoundsX[0], BoundsX[1]);
        pos.z = Mathf.Clamp(transform.position.z, BoundsZ[0], BoundsZ[1]);
        transform.position = pos;

        // Cache the position
        lastPanPosition = newPanPosition;
    }

    void ZoomCamera(float offset, float speed) {
        if (offset == 0) {
            return;
        }

        cam.fieldOfView = Mathf.Clamp(cam.fieldOfView - (offset * speed), ZoomBounds[0], ZoomBounds[1]);
    }
}

```

But my main problem is this two line of code :

```
Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed);

```

What is this exactly? I mean, what science is behind this? Mathematics? If so, what kind of math? Vector projection? I don't need to know what `ScreenToViewport` is, I want to know what kind of science should I learn to do this by myself.

# Answer
```
Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed);

```

> What is this exactly? I mean, what science is behind this? Mathematics? If so, what kind of math? Vector projection?

This is **linear algebra**, also informally called "vector math".

`lastPanPosition - newPanPosition` is a vector subtraction.

`ScreenToViewportPoint` is scaling, possibly via a matrix multiplication like this:

$$\vec v\_\text{out} = \begin{bmatrix} \frac 1 {\text{screen width in pixels}} & 0\\ 0 & \frac 1 {\text{screen height in pixels}} \end{bmatrix}\vec v\_\text{in} $$

`Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed);` is a scalar multiplication, and a projection, which we could also express as a matrix multiplication:

$$\vec {\text{move}} = \text{pan speed} \begin{bmatrix} 1 &0& 0\\ 0 &0& 0\\ 0 &1& 0 \end{bmatrix}\vec {\text{offset}} $$
> 2 votes

---
Tags: unity, c#, mathematics, camera, terminology
---


# Question
Title: How can two people simultaneously edit one game project?
I've been looking for a workflow that allows two game developers to simultaneously work in real-time on the same project, much like Roblox Studio.

I tried using Unity, but out of the box its collaborating system is not what I am looking for.

I want to be able for both of us to work simultaneously, not one to upload its project and the other to download it every 5 minutes.

We have a preference for a workflow that lets us code in Python or C# (preferably Python).

How can we accomplish this?

# Answer
> 5 votes
You can take a look at SceneFusion for Unity, which is free for up to 2 users and a limited number of GameObjects in the scene. That should work well with your requirement of needing C#.

If you want something built-in, you can try Unreal's Multi-User Editing, but you'll need to find a way to use C# in that case.

---
Tags: editors, asset-workflow, teamwork, workflow
---


# Question
Title: How to make a sprite face the mouse while remaining upright, without negative scale?
In the game I'm creating I have a sprite that needs to constantly be facing the mouse, but the sprite also always needs to be facing "up".

Because of the Polygon Collider 2D and Shadow Caster 2D I cannot just flip the sprite. I used to set the localScale.y of the transform to -1 to keep it facing up, but now that's messing up my normal map for the sprite.

My best guess for how to solve this is to find a way to set the transform.eulerAngles.y to 180 when it needs to flip, but because of the Quaternion I use to keep the sprite "pointed" at the mouse, it's not working for me.

How can I solve this?

```
if (transform.eulerAngles.z > 90 && transform.eulerAngles.z < 270)
{
    direction = Vector2.down;
    antidirection = Vector2.up;
    transform.localScale = new Vector3(transform.localScale.x, -1, transform.localScale.z);
} else
{
    direction = Vector2.up;
    antidirection = Vector2.down;
    transform.localScale = new Vector3(transform.localScale.x, 1, transform.localScale.z);
}

if (isAccelerating) {
    helicopter.AddRelativeForce(direction * power);
}
if (isDeccelerating)
{
    helicopter.AddRelativeForce(antidirection * power);
}

var facing = Input.mousePosition-Camera.main.WorldToScreenPoint(transform.position);
var angle = Mathf.Atan2(facing.y, facing.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

```

# Answer
If you're going to use Euler angles anyway, and don't need arbitrary 3D rotations where gimbal lock is an issue, then you might as well just stick with Euler angles throughout.

```
var facing = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
var angle = Mathf.Atan2(facing.y, facing.x) * Mathf.Rad2Deg;

if (facing.x >= 0) {
    // If we're facing to the right, roll counter-clockwise to match.
    transform.eulerAngles = new Vector3(0, 0, angle);
} else {
    // If we're facing to the left, flip on the y axis, then roll clockwise to match.
    transform.eulerAngles = new Vector3(0, 180, 180 - angle);
}

// Since we're flipping on the y axis, not the x, we don't need to
// swap our directions when flipped anymore.
if (isAccelerating) {
    helicopter.AddRelativeForce(Vector2.up * power);
}
if (isDecelerating) {
    helicopter.AddRelativeForce(Vector2.down * power);
}

```
> 0 votes

---
Tags: unity, c#, 2d, rotation, transformation
---


# Question
Title: What should be an entity/component, and what shouldn't?
I've recently been reading the book Game Programming Patterns by Bob Nystrom, and one chapter I've found a bit hard to grip is the chapter about the Component pattern.

In the example he uses (which you can find by clicking the link) to demonstrate the pattern, he starts with a class for the playable character that contains render logic, input logic and physics logic all together. He then shows how you can pull each domain of logic into its own component class and thus completely ditch the playable character class and just have a general "component bag" in the shape of an `Entity` class.

Really impressed with how brilliant this pattern is, I fired up my code editor and started to incorporate the pattern into the little game engine library I've been working on while learning game development. After making a few little simple games trying to use this pattern, there are some problems and questions that keep appearing when I design the game logic around components.

# Should the game engine be completely built around entities?

Often when I read articles explaining the pattern, they start off by showing a messy game loop that manually updates and renders every object in the game, to then slowly transform it into an ECS-based game engine. What confuses me is how they make it seem like the entire game will just consist of a bunch of game entities. Surely that's not the case? A lot of systems in a game that needs to be updated are things that are not rendered and don't need any input, they simply need a call to their `update` function every frame. They don't have any physical representation in the game world, they are just things the game is keeping tabs on and changing. How are those systems supposed to work in an ECS-system? Are they supposed to be made into entities? If not, how will the game engine handle them?

# Should all logic and behavior for an entity be put into its components?

Let's say we want the playable character to have an inventory for items he collects. In what component would you put the logic for that inventory? None of the components in the example from the book seem appropriate for something like that. Or should the inventory be kept in some static class along with other player stats and data, that the entity then reports to? In that case, how would you design an inventory system for NPCs? Given how complex systems connected to entities can be, I don't understand how you design them around a "component bag"-class.

Thanks in advance!

# Answer
> A lot of systems in a game that needs to be updated are things that are not rendered and don't need any input, they simply need a call to their update function every frame. They don't have any physical representation in the game world...

That sounds like an entity that has no `Renderer` component (doesn't get rendered) and no `InputHandler` component (doesn't receive input) and no `Transform` component (no position/orientation in the game world) and no `Rigidbody` or `Collider` components (no physics representation) attached. It could have other components attached that get updated each frame.

The beauty of this approach is that it "just works" with the game loop and structures you already have for ticking components each frame. Even if there's only one of these, it saves you from writing one-off code into your game loop every time you want to add a new abstract thing that needs ticking. And any systems you have for finding/sharing references to entities/components, or spawning/destroying/enabling/disabling them, will all work with this new thing out of the box.

But also, it doesn't *have* to be an entity. You're allowed to also have plain old objects and structs that are not "entities" if that's simpler and easier for you to work with for this context. Or a static class for stuff that really should be global (though the usual cautions about mutable global state apply here).

> Let's say we want the playable character to have an inventory for items he collects. In what component would you put the logic for that inventory?

Myself, I'd put the logic for handling inventory slots and contents in a `PlayerInventory` component. I'd avoid a static class here, just in case I might want to add local multiplayer, where each player entity needs their own inventory, rather than a single global inventory. Here's an example of a simple inventory component written for Unity's component based approach.

Anything that logically "belongs" to some *thing* in your game - like a character, player, location, object, etc. - often works well as a component. But that's not everything. It would probably get excessive if you decided to implement keyboard input by making an entity for each key with a `Button` component attached.

---

The thing to keep in mind is that component-based approaches, and the Entity-Component-System paradigm, are just guidelines and patterns that other developers have found helpful. They're not rigid rules you must adhere to perfectly in order to make a working game. Use the pattern where you find it helps, and bend or break it when you find it's not helping you. If you later find a situation where using the pattern would help after all, you can refactor to implement it in a better way, now that you understand your situation more thoroughly.
> 9 votes

---
Tags: architecture, software-engineering, design-patterns, component-based, entity-component-system
---


# Question
Title: Finding rotation quaternion from orthonormal basis?
Given three 3D unit vectors \\$a\\$, \\$b\\$, \\$c\\$ such that:

\\$a \times b = c\\$

\\$b \times c = a\\$

\\$c \times a = b\\$

(ie \\$a, b, c\\$ form an *orthonormal basis*)

How do we calculate a unit quarternion \\$q\\$ such that the sandwidch product (ie rotation) of \\$q\\$ on (1,0,0) is \\$a\\$, (0,1,0) is \\$b\\$ and (0,0,1) is \\$c\\$ ?

# Answer
@Andrew Tomazos is correct, but conversion of the three vectors to a matrix first requires the storage of 16x additional floats, and is a bit slow.

A better solution is found by writing out the basis vectors a,b,c and plugging these into the matrix-to-quaternion conversion, where the elements are explicit.

```
m[0][0] = a.x, m[1][0] = b.x, m[2][0] = c.x
m[0][1] = a.y, m[1][1] = b.y, m[2][1] = c.y
m[0][2] = a.z, m[1][2] = b.z, m[2][2] = c.z

```

Now, we rewrite the matrix-to-quaternion function using the subsituted orthonormal vectors a,b,c. The result is the following function:

```
// Quaternion from orthogonal basis
Quaternion& Quaternion::fromBasis(Vector3DF a, Vector3DF b, Vector3DF c)
{
    float T = a.x + b.y + c.z;
    float s;
    if (T > 0) {
        float s = sqrt(T + 1) * 2.f;
        X = (c.y - b.z) / s;
        Y = (a.z - c.x) / s;
        Z = (b.x - a.y) / s;
        W = 0.25f * s;
    } else if ( a.x > b.y && a.x > c.z) {
        s = sqrt(1 + a.x - b.y - c.z) * 2;
        X = 0.25f * s;
        Y = (b.x + a.y) / s;
        Z = (a.z + c.x) / s;
        W = (c.y - b.z) / s;
    } else if (b.y > c.z) {
        s = sqrt(1 + b.y - a.x - c.z) * 2;
        X = (b.x + a.y) / s;
        Y = 0.25f * s;
        Z = (c.y + b.z) / s;
        W = (b.z - c.y) / s;
    } else {
        s = sqrt(1 + c.z - a.x - b.y) * 2;
        X = (a.z + c.x) / s;
        Y = (c.y + b.z) / s;
        Z = 0.25f * s;
        W = (b.x - a.y) / s;
    }
    return *this;
}

```

This function gives a quaternion (X,Y,Z,W) directly from the orthonormal basis vectors a,b,c without intermediate storage of a matrix. You may still need to normalize the quaternion. If you have a direction and up-vector, say for a camera, you can construct the basis as: a=dir, b=up, c=cross(dir,up)
> 3 votes

# Answer
An orthonormal basis forms a rotation matrix trivially by combining the three vectors and transposing (recall for an orthonormal matrix the inverse is just the transpose). The resulting rotation matrix can then be converted into a quarternion in the usual fashion.
> 1 votes

---
Tags: mathematics, geometry, quaternion
---


# Question
Title: Getting the contact point when using OverlapCapsule
I am trying to use `OverlapCapsuleNonAlloc` to determine all enemy weapons that intersect with my character's `CapsuleCollider` at the same time. I want to get the contact point to trigger vfx in the right place. Is there someway I can find the contact point using OverlapCapsuleNonAlloc in Unity ?

# Answer
`overlapResults[i].ClosestPoint(yourGameObject.position)` works pretty well, but consider specifying the Layer you are targeting in your overlap ^^
> 0 votes

---
Tags: unity, collision-detection
---


# Question
Title: How can I stop this timer from another script?
Here is the script:

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

public class Timer : MonoBehaviour
{
    public static Timer instance;

    public TextMeshProUGUI TimerText;
    private float startTime;

    private void Start()
    {
        instance = this;

        startTime = Time.time;
    }

    private void Update()
    {
        float time = Time.time - startTime;

        string minutes = ((int)time / 60).ToString();
        string seconds = (time % 60).ToString("f0");

        TimerText.text = minutes + ":" + seconds;
    }
}

```

I tried quite a few things and none of them worked. I'm kind of new to C# and unity and I would like to know how to stop this timer from another script. And I want to check if the game object the script is on is enabled.

Any help is appreciated :)

# Answer
First, store a reference to the game object that has the timer you want to stop:

```
public Timer timerToStop;

```

You can fill this in by dragging the object with the timer into this field in the inspector. You can also have another script set this variable, or find the timer with `FindObjectOfType<Timer>()`.

Next, you simply disable it:

```
timerToStop.enabled = false;

```

This will prevent its `Update()` method from ticking, so the displayed time value will freeze at the last time it had. This will not out of the box support resuming the timer, but that wasn't included in your question.

Since you seem to be using a singleton pattern here, you could also write

```
Timer.instance.enabled = false;

```

...without storing/looking up your own reference to it. But this limits you to having just one timer, which may or may not be what you want.

You can check whether the timer script is enabled just by reading the value of its `enabled` property.

You can check whether the game object it's on is active by checking `timerToStop.gameObject.activeInHierarchy` \- this will return false if the game object or any of its parents in the hierarchy have been set to inactive. If you care only about this game object itself and not those above it, you can use `.activeSelf`.
> 2 votes

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


# Question
Title: How to rotate a 3D object based on stick Input and the normal of the ground's surface?
I am making a game where I want to view an object from any angle and use an analog stick to rotate it according to this input and the surface the object is currently resting on. Here's a visualization of what I am trying to accomplish to outline my question:

(this is from a camera perspective, user's view. Also that's "transform.forward", woops)

At the moment I go about some of the initial steps like this with a short cylinder (think a hockey puck):

1. Take the average normal below the puck using 8 raycasts around the rim towards the ground
2. Use this average normal to have the puck mimic the surface's average tilt
3. Use the camera's rotation to as the reference for determining where the stick is pointing from the player's POV
4. In terms of the diagram, this is the step where I'd hope to calculate the orange arrow (the output direction of the object's forward direction), but so far I cannot figure that part out.

To specify, I want to apply force based on the transform's forward direction relative to the ground so simply applying force on an XY plane is not what I am trying to accomplish. Below is my best attempt so far. It fails in that it doesn't turn on the ground according to its movement on the plane.

```
// All the objects I am using to capture/store the data
GameObject input;
GameObject camera_Axis;

GameObject tank_Manager;
bool isGrounded;

GameObject base_Model; // The "puck's" model
GameObject base_Collider; // The "puck's" collider
GameObject ground_Checker; // Object which casts the 8 rays directly down from puck rim
float groundMatchSpeed; // Speed the objects mimics the ground surface
float turnSpeed; // Speed at which the object would turn left and right relative to the surface

float lastAngleLSFromOrigin;
Vector3 lastPosition;

PlayerControls moveControl;
Vector2 move;

void Awake()
{
    moveControl = new PlayerControls();
}
void OnEnable()
{
    moveControl.Gameplay.Enable();
}
void OnDisable()
{
    moveControl.Gameplay.Disable();
}

void Update()
{
    Quaternion rotation = base_Collider.transform.rotation;

    move = moveControl.Gameplay.LeftStick.ReadValue<Vector2>();
    float LSx = move[0];
    float LSy = -move[1];
    Vector2 LS = new Vector2(LSx, LSy); // Stick inputs

    float angleLSFromOrigin = Vector2.SignedAngle(new Vector2(0f, -1f), LS);
    if ((LSx == 0) & (LSy == 0))
    {
        angleLSFromOrigin = lastAngleLSFromOrigin; // If there is any input, update the angle
    }

    Quaternion relative = camera_Axis.transform.rotation;

    if (LS.magnitude >= 1)
    {
        lastAngleLSFromOrigin = angleLSFromOrigin; // If stick is beyond threshold, update angle
    }

    if (rotation == camera_Axis.transform.rotation)
    {
        relative = Quaternion.Inverse(rotation) * yRotation(camera_Axis.transform.rotation);
        // I am going to be honest, I don't remember why this works and how, but it is essential. Fixes a problem where the object and camera align perfectly
    }

    // Determine ground tilt from hover test points
    Vector3[] hover_Test_Normals = ground_Checker.GetComponent<check_Grounded>().hover_Test_Normals;
    Vector3 averagedNormal = new Vector3();

    for (int i = 0; i < hover_Test_Normals.Length; i++ )
    {
        averagedNormal[0] += hover_Test_Normals[i][0];
        averagedNormal[1] += hover_Test_Normals[i][1];
        averagedNormal[2] += hover_Test_Normals[i][2];
    }

    averagedNormal[0] = averagedNormal[0] / hover_Test_Normals.Length;
    averagedNormal[1] = averagedNormal[1] / hover_Test_Normals.Length;
    averagedNormal[2] = averagedNormal[2] / hover_Test_Normals.Length;

    Quaternion rotateTo = base_Collider.transform.rotation;
    rotateTo = Quaternion.FromToRotation(base_Collider.transform.up, averagedNormal) * rotateTo;

    // Find vector of displacement from last frame
    Vector3 displacmentSinceLastFrame = new Vector3(Mathf.Abs(base_Collider.transform.position.x - lastPosition.x), 0f, Mathf.Abs(base_Collider.transform.position.z - lastPosition.z));
    Vector3 displacementDirection = displacmentSinceLastFrame.normalized;

    var colliderStep = Time.deltaTime * groundMatchSpeed;
    var modelStep = Time.deltaTime * turnSpeed;

    // If grounded, mimic tilt of surface
    if (tank_Manager.GetComponent<tank_State>().isGrounded == true)
    {
        transform.rotation = Quaternion.Lerp(rotation, rotateTo, colliderStep);
        base_Model.transform.rotation = Quaternion.Slerp(rotation, rotateTo, colliderStep);
    }

    lastPosition = base_Collider.transform.position;
}

private Quaternion yRotation(Quaternion q)
{
    float theta = Mathf.Atan2(q.y, q.w);

    // quaternion representing rotation about the y axis
    return new Quaternion(0, Mathf.Sin(theta), 0, Mathf.Cos(theta));
}`

```

I would also like to voluntarily acknowledge I don't entirely understand Quaternions and may be doing something stupid as a result. If so, please let me know. Any other suggestions?

# Answer
> 1 votes
You can solve this with the method I show here: Camera-relative movement is pushing into/off the ground instead of parallel.

```
Vector3 CameraRelativeFlatten(Vector3 input, Vector3 localUp)
{
    // It's more efficient to cache the reference to the camera to use, if you can.
    Transform cam = Camera.main.transform;

    // This first part creates a rotation looking (z+) along the terrain normal,
    // "up" (y+) facing back toward the camera as closely as possible.
    var zToUp = Quaternion.LookRotation(localUp, -cam.forward);

    // This second part rotates the object's local y+ vector to face along z+,
    // and takes z- to y+.
    var yToZ = Quaternion.Euler(90, 0, 0);

    // Chaining these, we get a rotation that maps local y+ to the terrain normal,
    // and local z+ so it points away from the camera as best as possible.
    var flatten zToUp * yToZ;

    // Now we rotate our input vector into this frame of reference
    return flatten * input;
}

```

This will map the z+ component of the `input` vector so that it points away from the camera, parallel to the terrain. The x+ will map to the camera's right, parallel to the terrain, and y+ will point perpendicular to the terrain.

You can turn this into a rotation with:

```
Quaternion.LookRotation(CameraRelativeFlatten(input, localUp), localUp);

```

---
Tags: unity, camera, rotation, movement, linear-algebra
---


# Question
Title: I want to cut a pizza slice out of a 2D circle using mouse input in Unity. What data structures and geometric formulas would be best for this?
I understand this is probably not an easy task considering I haven't found any code examples online that do something like this but if I wanted to take in mouse input lets say during a drag and use that input as soon as the user lets go of the mouse to calculate into some kind of slicing for a part of a mesh, what would I need to watch out for and what would be the best algorithms and data structures for this?

# Answer
> 4 votes
In theory this isn't that complicated -- given a point *a* somewhere on the surface of the circle, project a ray from the center of the circle through that point of length *r*. The endpoint of that line is where you slice the outer edge of the circle. Repeat for the other edge of the pie slice.

```
Vector2 calcEdgePoint(Vector2 mouseDownPosition,Vector2 circleCenter, float circleRadius)
   {
    Ray2D ray = new Ray2D(circleCenter, mouseDownPosition - circleCenter);

    return ray.GetPoint(circleRadius);
   }

```

How you put this in practice in your Unity game depends on how accurate you need to be and how exactly you want to handle user input.

## Mesh MouseOver

A simple approach and what I would probably try first is to "pre-slice" the pizza (circle) mesh and simply track which portions the user drags over to determine which portions to subtract.

Here's a quick and dirty example.

1. The meshes -- I used 3D to make sure convex colliders work, but you could probably get this to work with simple triangles. My pizza has 32 slices. Use as many as you need to get the desired resolution.

2. Scene set up -- "pie" parent with child meshes and a controller. The camera points straight down on pie.

3. Each slice has a convex collider and a `PieSlice` script:

4. The pie slice script "phones home" to the `PizzaPieSlicer` controller with mouse enter, exit and (optionally) stay info:

```
using UnityEngine;

public class PieSlice : MonoBehaviour
{
    MeshRenderer mr;

    void Start()
    {
        mr = GetComponent<MeshRenderer>();
    }

    private void OnMouseEnter()
    {
        Debug.Log("entered");
        PizzaPieSlicer.instance.SliceEnter(mr);
    }

    private void OnMouseExit()
    {
        PizzaPieSlicer.instance.SliceExit(mr);
    }
}

```

The controller script tracks whether the pizza is "active" with a state machine. When no slices are active, it goes ahead and slices the pie.

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

public class PizzaPieSlicer : MonoBehaviour
{

    [SerializeField] Transform pieParent;
    [SerializeField] Material[] materials;
    public static PizzaPieSlicer instance;

    public enum State
    {
        slicing,
        idle,
        sliced
    }

    public List<Transform> slices = new List<Transform>(); // public for debugging
    public State state; // public for debugging;
    public int hit = 0; // maybe useful to count? public for debugging " "

    void Start()
    {
        instance = this;
        state = State.idle;

    }

    public void SliceEnter(MeshRenderer mr)
    {
        mr.sharedMaterial = materials[1];
        state = State.slicing;
        if (!slices.Contains(mr.transform))
        {
            slices.Add(mr.transform);
        }
        hit++;
    }

    public void SliceExit(MeshRenderer mr)
    {
        mr.sharedMaterial = materials[2];
        state = State.idle;
    }

    public void SliceStay()
    {
        state = State.slicing;
    }

    void SliceIt()
    {
        var sliceParent = new GameObject().GetComponent<Transform>();

        foreach(Transform t in slices)
        {
            t.SetParent(sliceParent);
        }

        sliceParent.position = new Vector3(1, 1, 1); //Do something more intelligent here
    }

    void Update()
    {
        switch (state)
        {
            case State.idle:
                if(hit > 0)
                {
                    Debug.Log("Slice it!");
                    SliceIt();
                    state = State.sliced;
                }
                break;

            case State.slicing:
                // do something
                break;

            case State.sliced:
                // reset maybe?
                break;

            default:
                break;
        }
    }
}

```

Demo:

*Note: I had intended for the PieSlice script to notify PizzaPieSlicer during OnMouseOver events, but it turns out this may be unnecessary; nevertheless I think my script's state machine may rely on an race condition that might not be reliable (exit events always triggering before entering events) -- a better approach might be to keep a stack that pushes on enter and pulls on exit; if a frame goes by and the stack is empty, trigger the slice.*

## Image Radial Fill

Another approach in Unity, if this is to be a UI element, is to use the `Image.FillMethod.Radial360` and specify a `fillAmount` based on the user's mouse inputs. A possible drawback of this approach is that the Image fill Origin is limited out of the box to the four cardinal points; starting the fill elsewhere would require first rotating the image, which might not be desirable if the sprite isn't a plain fill.

---
Tags: 2d, vertex
---


# Question
Title: How to apply a factor over multiple frames?
am trying to do something that should be quite common in games: Applying a factor over a certain amount of time. For example let's say a number should become a quarter of itself every second.

How do we do this with variable frame rate?

I have written the following code:

```
using System;

public class Program
{
    static double NthRoot(double x, double n)
    {
        return Math.Pow(x, 1.0f / n);
    }

    public static void Main()
    {
    double input = 10;
    double factor = 0.25;

    Console.WriteLine("Direct result: " + (input * factor));
    Random rnd = new Random();

    // simulate everything five times
    for (int i = 0; i < 5; i++)
    {
        double val = input;

        double total_time = 0;
        // simulate the frames that accumulate to one second
        while(total_time < 1.0)
        {
            // simulate a delta time for the current frame
            double delta = rnd.Next(50, 100)/1000.0;

            total_time += delta;
            double current_frames = 1.0/delta;

            // apply the current factor
            val *= Program.NthRoot(factor, current_frames);
        }

        Console.WriteLine("Result over one second: " + val);
    }
}

```

It produces a random delta (as if frame rate were fluctuating) and calculates a special factor for every frame based on the framerate derived by this delta time.

However the results are inaccurate and tend to be too small:

```
Direct result: 2.5
Result over one second: 2.37171078785113
Result over one second: 2.36842517649817
Result over one second: 2.4655817612334
Result over one second: 2.34555299125168
Result over one second: 2.38820734095609

```

Here a Fiddle for the code: https://dotnetfiddle.net/1tEXba

How does one do this more accurately?

Huge thanks!

# Answer
```
currentValue *= Math.Pow(ratioRemainingAfter1Second, secondsElapsedThisFrame);

```

If your time delta were exactly 1 second, then this power function would spit our your original ratio unchanged.

If your time delta were exactly 2 seconds, then this power would spit out your ratio squared - reducing the value by the ratio once for the first second, and again for the second second.

If your time delta were exactly 0.5s second, then this power would spit out the square root of your ratio. Multiplying by this square root twice in a row (two 0.5 second frames) gives the same outcome as multiplying by the original ratio once (one full second).

And so on. This adjusts the ratio correctly to whatever amount of time has passed (up to the limits of floating point precision and rounding error - so if you need exact determinism you'll want a different mechanism).

---

The error in your code is that you were simulating different time intervals. Depending on the random rolls, you'd simulate between 1.0 seconds and 1.098 seconds - and that makes a difference between runs! Fix up your final loop so that you always end at exactly 1.0 seconds and you'll get the desired outcome:

```
while(total_time < 1.0)
{
    // simulate a delta time for the current frame
    double delta = rnd.Next(50, 100)/1000.0;

    if (total_time + delta > 1) {
        // For the final loop, ensure we finish exactly at 1.0 seconds.
        delta = 1.0 - total_time;
        total_time = 1;
    } else {
        // For other loops, advance by our random delta.
        total_time += delta;
    }

    double current_frames = 1.0/delta;

    // apply the current factor
    val *= Math.Pow(factor, delta);
}

```
> 2 votes

---
Tags: frame-rate
---


# Question
Title: How to get rid of intersections between terrain and road strip drawn on top?
When I draw a road as is (stencil:off, depth:on,less), the results are like this - ;

Then I tried adding stencil a test for the road:

```
// Write to Stencil, Color & Depth buffers
Gl.Enable(EnableCap.DepthTest);
Gl.Enable(EnableCap.StencilTest);
Gl.ClearStencil(0);
Gl.Clear((uint)(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit));

// Write 1, when image drawing (road)
Gl.StencilFunc(StencilFunction.Always, 1, 0xff);
// write all bits of "reference" param;
Gl.StencilMask(0xff);
// stencil fail; stencil pass, depth fail; stencil pass, depth pass
Gl.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);

road.Draw();  //draw road
// now, road in stencil buffer is 1, others - zeros;

//all not one - fail stencil, and do not drawing
Gl.StencilFunc(StencilFunction.Notequal, 1, 0xff);
// no more write to stencil buff
Gl.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Keep);

// draw terrain
EndlessTerrain.DrawVisibleChunks();

```

and got this:

after 3 days of random tests, I managed to hide the road behind the mountain, but there are still glitches (blue-green fill - "stencil pass, depth fail" in GlStencilOP()")  Here are 2 calls for drawing the terrain and 2 calls for drawing the road, with the one additional step for clearing of the depth. I think this is not correct way.

I found What are the correct steps for the renderer, to do normal roads drawing on terrain mesh?, but no solution, also, other than modifying the mesh.

# Answer
As @DMGregory said, for solution use glPolygonOffset - Renderer code:

```
Gl.Enable(EnableCap.PolygonOffsetFill);
Gl.PolygonOffset(1f, 100f);
EndlessTerrain.DrawVisibleChunks();
road.Draw();

```

frag shader code:

```
#version 330
out vec4 fragColor;

uniform mat4 uView;
uniform mat4 uProjection;
uniform mat4 uModel;
in vec3 v_position;

void main()
{
    vec4 v_clip_coord = uProjection * uView * uModel * vec4(v_position, 1.0);
    float f_ndc_depth = v_clip_coord.z / v_clip_coord.w;
    gl_FragDepth = (1.0 - 0.0) * 0.5 * f_ndc_depth + (1.0 + 0.0) * 0.5;

    fragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

```

vert shader code:

```
#version 330
layout (location = 0) in vec3 vPosition;

uniform mat4 uView;
uniform mat4 uProjection;
out vec3 v_position;
void main()
{
    v_position = vPosition;
    gl_Position = uProjection * uView * vec4(vPosition, 1.0);
}

```

Additional detailed description about glPolygonOffset.
> 1 votes

---
Tags: opengl, depth-buffer, terrain-rendering, stencil, decal-system
---


# Question
Title: How to move X and Y position of sprite in GameMaker Studio 2?
In the tutorial it told me to add the sprite to the object and then add an event to the object called Step. I did this and then added the sprite to the room.

The GML code I used in the Step event is `x = x + 4;` to move to the right but when I run the game it does not move at all.

Why doesn't my sprite move to the right when I have this code in the object's Step event?

# Answer
As mentioned in the comments, you have placed the sprite in the room instead of the object itself. The object is the one that contains the code and functionality, so replace the sprite with the object and then your function will work.

Keep in mind that sprites and objects are placed on a different layer in a room.
Objects are placed on an 'instances' layer. and standalone sprites are placed on an 'Assets' layer.
> 1 votes

# Answer
That is not a player moving script, but this is:

```
if (keyboard_check(vk_left)) x = x - 3;
if (keyboard_check(vk_right)) x = x + 3;
if (keyboard_check(vk_up)) y = y - 3;
if (keyboard_check(vk_down)) y = y + 3;

```

This snippet works for top-down movement. In the first line of code, it basically says 'if you press the left arrow button key on your keyboard, you will move left'.
> 0 votes

---
Tags: game-maker-studio-2
---