# Question
Title: Score counter not increasing after recalling object from a pool with raycast detection hit
# Context

Hello, its me again. I have been playing around with "Object Pool" and it is fascinating the amount of CPU performance can save up. However, I have encountered a new "feature" where it scores once for the object being called and going through the pipe.

In my object pool, I have a pipe GameObject where is being Instantiated and set its method `Active(false)` until it is spawned. Once spawned, my prefabs will be filled accordingly to the Object Pool's size.

# Problem

Once it spawns, it does what it should do, both scoring and the same mechanic as "Flappy Bird". However, once the object gets Active again, it doesn't seem to score anymore because it was passed by a player. What I have done is to have a flag that checks if the player (bird) has passed the pipe or not. However, when I pass through it, it will update it as if it was 6 times (one point per frame). You may ask "have you done another flag for the pipe itself?" then the answer is **yes**. I tried that way also, but it will only keep the score once and not increase further than 5.

I ran out of ideas with the object pool approach. It seems to work fine if it is **WITHOUT** object pooling, but the flaw here is that it costs me CPU performance.

It either increases it by just 1, or it increases it by 6 times (because for each frame the object is in the ray, it counts another point).

# Attempts

I have browsed on the Unity Learning center to find out how to do the object pooling, and it wasn't too bad as I thought. Later, I found this issue and I thought it was a problem with my logic (which it can be). I have spent several hours already (first mistake) to think it is something easy to fix, but apparently it wasn't due the time I have spent to just figure out why it is not working . I have been fiddling around my `RayCastDetection`, `SpawnManager`, `ObjectPooling`, and `PlayerControl` logic that interacts accordingly to the way I want, but *nada*.

# Code

## `ObjectPooling.cs`

```
public static ObjectPooling sharedInstance;
public List<GameObject> pooledObjects;
public GameObject objectToPool;
private PlayerControl playerControllerScript;
public int amountToPool;

void Awake()
{
    sharedInstance = this;
}
void Start()
{
    playerControllerScript = GameObject.Find("Player").GetComponent<PlayerControl>();
    pooledObjects = new List<GameObject>();
    GameObject tmp;

    for (int i = 0; i < amountToPool; i++) //Add objects to the pool and turns them invisible (false)
    {
        tmp = Instantiate(objectToPool);
        tmp.SetActive(false);
        playerControllerScript.passedBeam = false;
        pooledObjects.Add(tmp);
    }
}
public GameObject GetPooledObject()
{
    for (int i = 0; i < amountToPool; i++)
    {
        if (!pooledObjects[i].activeInHierarchy)
            return pooledObjects[i];
    }
    return null;
}

```

## `RayCastDetection.cs`

```
public class RayCastDetection : MonoBehaviour
{
    public UIManager UIManagerScript;
    public PlayerControl playerControlScript;
    private RaycastHit hit;
    public bool passed;

    void Start()
    {
        UIManagerScript = GameObject.Find("UI_Manager").GetComponent<UIManager>(); //Used for scoring
        playerControlScript = GameObject.Find("Player").GetComponent<PlayerControl>(); //used for player passing through the pipe
        passed = false;
    }

    void Update()
    {
        Vector3 beamDown = transform.TransformDirection(Vector3.down);
        Ray ray = new Ray(transform.position, beamDown);

        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.tag == "Player" && passed == false)
            {
                passed = true;
                UIManagerScript.score++; //Scoring happens here
                if (passed == true)
                    playerControlScript.passedBeam = true;
            }
            Debug.DrawRay(transform.position, hit.point - transform.position);
        }
    }
}

```

## `SpawnManager.cs`

```
public class SpawnManager : MonoBehaviour
{
    public GameObject[] obstaclesPrefab;
    private PlayerControl playerControllerScript;
    private float startDelay = 1.69f;
    private float repeatRate = 1.1f;

    void Start()
    {
        playerControllerScript = GameObject.Find("Player").GetComponent<PlayerControl>();
        InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
    }

    void Update()
    {

    }
    void SpawnObstacle()
    {
        // int obstaclesIndex = Random.Range(0, obstaclesPrefab.Length); //This is used only if I don't want to deal with object pooling, but the whole point is to use it. This is just a reference if I want to go back

        if (playerControllerScript.gameOver == false)
        {
            float randomY = Random.Range(-2f, 2f);
            Vector3 randomHeight = new Vector3(35, randomY, -7);
            GameObject pipe = ObjectPooling.sharedInstance.GetPooledObject();
            if (pipe != null)
            {
                pipe.transform.position = randomHeight;
                pipe.SetActive(true);
                //My guess is that I want to instantiate the object pipe's beam to false here
            }
        }
            // Instantiate(obstaclesPrefab[obstaclesIndex], randomHeight, obstaclesPrefab[obstaclesIndex].transform.rotation); //This is used only if I don't want to deal with object pooling, but the whole point is to use it. This is just a reference if I want to go back
    }
}

```

Feel free to leave some suggestions in what I have missed out or any questions in regards to fill in. Thank you for your time!

# Answer
> 0 votes
I wanted to share some good news. My problems has been fixed!

Before I step into the solution, big thanks to **rotgers** and sharing me the approach he used. I actually was stubborn and wanted to feel *unique* in some way when it was coming to a solution. I had to step back a little bit and look at the **big picture**.

# Reflection

If you ever struggle and spent like 8-12hrs like me for some logic nonsense and you feel it in the tip of the tongue, it is time to step a little bit back when you are not going anywhere after 1 hour.

Few tips to do (which I didn't do but I wish I do at the moment) was have **drawings in how you are picturing it out mentally**. Not drawing for the first time was my first mistake. I felt challenged by my own mind and sabotaging my own work to continuing being stubborn.

# Code Solution

Now, the solution is that I added my `UIManager` script with my `SpawnManager` and `RayCastDetection` in order to make it work. Here is how I did it:

## `UIManager.cs`

```
public class UIManager : MonoBehaviour
{
    public Text scoreBoardDisplay;
    public Text scoreBoardDisplayShadowed;
    public AudioSource sound_score;
    public string scoreText;
    public int score;
    public int oldScore;
    public bool success;
    public bool incrementScore;

    void Start()
    {
        success = false; //NEW
        incrementScore = false; //NEW
    }

    void Update()
    {
        if (score != oldScore)
        {
            sound_score.Play();
            scoreText = score.ToString();
            scoreBoardDisplay.text = scoreText;
            scoreBoardDisplayShadowed.text = scoreText;
            oldScore = score;
        }
    }
}

```

## `SpawnManager.cs`

```
public class SpawnManager : MonoBehaviour
{
    public GameObject[] obstaclesPrefab;
    private PlayerControl playerControllerScript;
    public UIManager UIManagerScript; //NEW
    private float startDelay = 1.69f;
    private float repeatRate = 1.1f;
    void Start()
    {
        playerControllerScript = GameObject.Find("Player").GetComponent<PlayerControl>();
        UIManagerScript = GameObject.Find("UI_Manager").GetComponent<UIManager>();
        InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
    }

    void SpawnObstacle()
    {
        if (playerControllerScript.gameOver == false)
        {
            float randomY = Random.Range(-2f, 2f);
            Vector3 randomHeight = new Vector3(35, randomY, -7);
            GameObject pipe = ObjectPooling.sharedInstance.GetPooledObject();
            if (pipe != null)
            {
                pipe.transform.position = randomHeight;
                pipe.SetActive(true);
                UIManagerScript.incrementScore = false; //NEW, where my problem happens to be solved
                UIManagerScript.success = false; //NEW, where my problems happens to be solved
            }
        }
    }
}

```

## `RayCastDetection.cs`

```
public class RayCastDetection : MonoBehaviour
{
    public UIManager UIManagerScript;
    public PlayerControl playerControlScript;
    private RaycastHit hit;
    public bool passed;
    void Start()
    {
        UIManagerScript = GameObject.Find("UI_Manager").GetComponent<UIManager>();
        playerControlScript = GameObject.Find("Tomato").GetComponent<PlayerControl>();
        passed = false;
    }

    void Update()
    {
        Vector3 beamDown = transform.TransformDirection(Vector3.down);
        Ray ray = new Ray(transform.position, beamDown);

        if (!passed)
        {
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "Player" && !UIManagerScript.success) //Setting a condition to check if the beam hasn't been touched YET
                {
                    //Once touched, turn this true and increment
                    UIManagerScript.incrementScore = true;
                    UIManagerScript.score++;
                }
//If I already incremented my score, then there is no need to re-increment it again from the same ray. Thus, a flag for success is handled
                if (UIManagerScript.incrementScore)
                    UIManagerScript.success = true;
                Debug.DrawRay(transform.position, hit.point - transform.position);
            }
        }
    }
}

```

Again, thank you very much for guiding me to the right track :). If I think in something to add, I will update it under my *Reflection* header.

---
Tags: unity, c#, raycasting, gameobject, object-pools
---


# Question
Title: How to allow a CharacterController to pass through walls?
I'm developing a game in which bot-controlled billboards pursue you.

If the bot gets stuck behind a wall for a while, not able to catch the player, I want the bot to pass through the wall.

I'm using a `CharacterController` and I don't know how to disable collision and allow it to pass through other colliders.

# Answer
> 1 votes
Unity has a "Layer Collision Matrix" that lets you define interactions between different layers. I'm guessing that you will want to:

1. Assign the player to a Player layer.
2. Assign the billboards to an Enemy or Billboard layer.
3. Assuming 3D, update the level you have so that walls are a separate layer from the floor.
4. Update the Layer Collision Matrix so that the Player collides with the floors and the walls.
5. Update the Layer Collision Matrix so that the Billboards collide with ONLY the floors.

Per DMGergory's comment, if you want to temporarily do this based on how long the enemy is stuck, here are some ideas:

* Teleport the enemy closer if it gets too far away from the player. Should be pretty effective and a lot of games do this, not always to the player's enjoyment though.
* Setup another layer in the collision matrix which does what I describe above (doesn't collide with walls), and switch the enemy to that layer, at least temporarily, if it gets to far or hasn't moved much recently (and it's supposed to be).
* Disable collision (Colliders) on walls that are far enough away from the player (off screen?).

---
Tags: unity, c#, movement, collision-resolution, character-controller
---


# Question
Title: How can I change the default dawn and dusk times in Unity?
I'm working on a game in which the season is particularly important to the player, along with sunlight. It progresses from early spring to late fall. I have a very basic day/night cycle system working, but dawn and dusk are consistently at the same times; whereas, in the real world, days get longer into the summer and shorter into the winter.

The whole thing basically involves rotating a directional light now; but aside from changing the rate of rotation of the light in a non-linear fashion, I'm not sure how to implement the day-length-per-day-of-year system. Before I do something like that, I can't help but feel like there must be a better way to do it.

In summary, if I haven't been clear, sunrise and sunset are 6AM and 6PM (mapped to a normalized angle) by default. I may need sunrise at 5AM and sunset as late as 9PM at some point in my game. Is there an efficient or built-in way of managing this?

# Answer
So you probably need some sort of "Calendar"... maybe a simple range tracked from 0 - 365. Track the current day in a variable and increment it each new day. We'll also need some sort of light value. Let's say from 50% light to 100% light.

To adjust the lighting, we're going to assume that summer has the most sun, and work backwards from there. So you'll want to map the current day of the year to a percentage of light. To simplify things, let's assume that January 1st (Day 0 or 1) is the winter solstice with the least amount of light. So we would map 0 to 50%. July 1st (day 180) would be about 100%, and then back to December 31st (day 365) at 50%.

From there, you can apply that light percentage in 2 ways. The speed at which the light rotates, and the height of the light in the sky. 50% light means that the light should rotate faster. 100% light would mean normal speed. 50% light would also mean the light is lower in the sky, just like in the winter the sun is lower in the sky. 100% light would mean that the light would be directly overhead, or almost directly overhead.

One suggestion: Depending on your setup, you may not want to just rotate the light, but *move* the light across the map. This should cause the shadows to move and provide a really cool affect where locations look entirely different in the morning vs the night, even though the have the same *amount* of light.
> 1 votes

---
Tags: unity, lighting, skybox, world-design, time
---


# Question
Title: Viewport offset from top also creates a gap at the bottom
I am trying to do something really basic with `sf::View`.

On a 1280x720 pixel window. I need to place a viewport which is 560x560 with a 160px gap from the top.

What I get is this:

It creates the correct gap length on the top, but it also applies a gap at the bottom.

Code I wrote for the viewport:

```
int viewport_bl_OffsetX = 0;
int viewport_bl_OffsetY = 160;
int viewport_bl_W = 560;
int viewport_bl_H = 560;

sf::View viewBL(sf::FloatRect(
    static_cast<float>(viewport_bl_OffsetX),
    static_cast<float>(viewport_bl_OffsetY),
    static_cast<float>(viewport_bl_W),
    static_cast<float>(viewport_bl_H)
));

float viewport_bl_OffsetXRatio = static_cast<float>(viewport_bl_OffsetX) / window_W;
float viewport_bl_OffsetYRatio = static_cast<float>(viewport_bl_OffsetY) / window_H;

float viewport_bl_WRatio = static_cast<float>(viewport_bl_W) / window_W;
float viewport_bl_HRatio = static_cast<float>(viewport_bl_H) / window_H;

viewBL.setViewport(sf::FloatRect(
    viewport_bl_OffsetXRatio, // 0.00000000
    viewport_bl_OffsetYRatio, // 0.222222224
    viewport_bl_WRatio, // 0.437500000
    viewport_bl_HRatio // 0.777777791
));

```

The ratios seem to be correct, but I am not sure why it leaves a gap at the bottom.

# Answer
You don't provide much details about how you set up your scene but it seems to me, from what I remember about SFML (and the documentation), that there is a bit of confusion about how to set up your code.

The `View` is a *view on your scene*, it defines what portion of your scene you want to show to your users.

The `Viewport` is about *where you'll show this on your window*.

So the engine will try to "fit" the content of the View into the Viewport.

I assume the image you show is actually 560x560, and that you have set it at 0x0 in your scene; analyzing what we see on it, it seems that the "top" part of the image is cropped.

This would match the fact that you set the View's y at 160: you show 560 px of your scene, but starting at 160 instead of 0. The black part you see at the bottom is simply because there is nothing to show from your scene.

So the correct way to set your view is actually:

```
sf::View viewBL(sf::FloatRect(
    0.0f,
    0.0f,
    static_cast<float>(viewport_bl_W),
    static_cast<float>(viewport_bl_H)
));

```

(That is, until you want to show some other parts of your scene.)
> 0 votes

---
Tags: c++, sfml, viewport
---


# Question
Title: How to use a 3D cube using 2D URP and an orthographic camera?
I am creating 1 scene in my game that would use a 3D asset - a cube, that I would like to rotate to show its different faces. My game is set up for URP 2D, and the game uses an orthographic camera.

First, is this possible to do - or would I have to use a perspective camera?

Here is what I have tried:

* Using a perspective camera. But everytime I add a cube to the scene, it's showing as one big blob when rotated around, and is grey, probably because I don't know where/if I can add 2D directional light - I don't think that'll work with a 3D cube? When I add 3D directional light, it doesn't seem to work.
* Changed the material of the cube.

Here is what I have currently tried:

This is my cube, using an orthographic camera, but without any directional light. So this makes sense to me.

This is now a perspective camera set-up with a nice directional light hitting it directly.

However, it looks like this.

I would like for it to look like a standard cube with shadows, etc. It looks like a grey blob at the moment. How do I fix this, and also is it possible to show that it is a cube using an orthographic camera?

EDIT:

Using the URP "lit" material and directional light, this is still how it looks:

And on the camera:

***2D URP Pipeline Steps***

I was asked to recreate the steps in a new scene, so here we go:

This is my scene camera after I created a brand new 2D URP project. It is orthographic and these are the settings:

Note the camera settings/size/etc. It's a skybox, but it still shows up as a blue background on the camera.

As you can see here, directional light has been added, facing the cube. The global light 2D is also in this scene.

Nothing seems to change the flatness and blue background? Toggling 2D on and off does not work either.

This may be pertinent. Here's what my URP textures look like. One is red, another pink. I feel like this might be a problem with the materials or how they're being handled?

This is what my cube material looks like.

# Answer
It looks like the "Renderer 2D" URP pipeline definition does not process 3D lighting at all.

If you just want lighting for the sake of distinguishing cube faces, you can fake it with a shader. Here I've created a new unlit shader graph, and configured it like so:

This is just the math of Lambertian diffuse "n dot l" lighting plus an ambient term, written out as shader nodes, and using a vector parameter as your light direction (so you don't actually need a "light" object in your scene).

Slap this shader on your cube and you'll get shading dependent on the faces' direction and rotation of the cube:
> 1 votes

---
Tags: unity
---


# Question
Title: How fps limiting works in pygame (specific example)
I recently wrote a program where I needed to limit the fps. After some searching I found a way via pygame built-in methods `pygame.time.Clock()` and `clock.tick(fps)` but an even better, more accurate way through the `time module`. But now comes the tricky part and that is `delta time` and its use in this example. As far as I know it is used to measure the time between frames to be able to calculate the movement of an object in real time. So my question is, how does `dt` help me limit fps and what is the meaning of the `sleep_time` variable in this example?

I will be grateful for any explanation and attempt to help with this topic

A quick note: *I'm also quite new to python and I'm still trying to understand it, but not programming in general and I already grasp the basics. What I don't understand is the algorithm behind the scenes. So that's basically all I need help with.* Thank you.

```
# Modules ---------------------------------------- #

import pygame as pg, time

# Initialization --------------------------------- #

pg.init()
pg.display.set_mode((720, 400))

# Variables -------------------------------------- #

prev_time = time.time()
FPS = 60
running = True

# Main-loop -------------------------------------- #
while running:
    current_time = time.time()
    dt = current_time - prev_time
    prev_time = current_time
    sleep_time = 1./FPS - dt
    if sleep_time > 0:
        time.sleep(sleep_time)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False

```

# Answer
> what is the meaning of the sleep\_time variable in this example?

The time required to process a single frame will be calculated for each frame. If it takes less than 1/60th of a second (i.e. sleep\_time will be bigger than 0), put the process on hold for the remained of the 1/60th of a second, so that this frame actually takes 1/60th of a second.

`time.sleep(sleep_time)` suspends the thread for *at least* the duration of sleep\_time (it may be longer).

> how does dt help me limit fps

So in this example, the dt will be used to make sure you have a fixed/constant time step of `FPS`.

Sort of.

This way of limiting the framerate is not very good. I've modified the example in the question a bit with "printouts":

```
import time

prev_time = time.time()
FPS = 60
STEP_TIME = 1./FPS
running = True

count = 0
accum = 0

while running:
    current_time = time.time()
    dt = current_time - prev_time
    accum += dt
    count += 1
    if accum >= 1.0:
        accum -= 1.0
        print(count)
        count = 0

    prev_time = current_time
    sleep_time = STEP_TIME - dt
    if sleep_time > 0:
        time.sleep(sleep_time)

```

With the results:

```
% py main.py
64
64
68
62
62
62

```

We don't get 60hz. For two reasons:

First, as mentioned, `time.sleep(sleep_time)` will guarantee that the thread sleeps for *at least* this amount of time. That is how the OS works. So you can't control precisely how long your program will be sleeping.

Second, let's take a closer look at `dt`.

```
dt = prev_time - current_time

```

so the `dt` is the time spent during *the previous* frame. That's fine and all, and it would likely work if we didn't want to throttle the framerate. The problem comes when we want to sleep. When we call `time.sleep(sleep_time)`, we're actually calling `time.sleep(1./FPS - (prev_time - current_time))`. We're actually fixing *last frames* time. This has a nasty effect of having some frames where we'll sleep, and other frames where we'll not sleep, resulting inconsistent frame times, at least from the user perspective; adding `print(dt, sleep_time)` at the end of the previous code snippet, we get something like:

```
% py main.py
0.0 0.016666666666666666
0.03285384178161621 -0.016187175114949545
0.0 0.016666666666666666
0.033695220947265625 -0.01702855428059896
0.0 0.016666666666666666
0.03452634811401367 -0.017859681447347005
0.0 0.016666666666666666
0.03141927719116211 -0.014752610524495443
0.0002942085266113281 0.01637245814005534
0.032390594482421875 -0.01572392781575521
0.0 0.016666666666666666
0.031510353088378906 -0.01484368642171224
0.0 0.016666666666666666
0.019999265670776367 -0.0033325990041097008
0.0005021095275878906 0.016164557139078776
0.03202223777770996 -0.015355571111043295
0.0006344318389892578 0.01603223482767741
0.03662467002868652 -0.019958003362019857
0.0 0.016666666666666666

```

To control the frame rate, I generally prefer the "busy loop" approach, which offers a more fine grained control w.r.t. using any sleep methods.

```
import time

prev_time = time.perf_counter()
current_time = prev_time
FPS = 60
STEP_TIME = 1./FPS
running = True

count = 0
accum = 0

while running:
    prev_time = current_time
    current_time = time.perf_counter()
    dt = current_time - prev_time

    accum += dt
    count += 1
    if accum >= 1.0:
        accum -= 1.0
        print(count)
        count = 0
    # print(dt)

    # busy loop, where we just wait this frame's time to pass
    while time.perf_counter() < (current_time + STEP_TIME):
        pass

```

Please note that instead of `time.time()`, I use `time.perf_counter()` which is much more precise for what we need to do.

With this method, I get this for the actual frame rate:

```
% py main.py
61
60
60
60
60
60
60
60

```

and this for individual frame time:

```
% py main.py
2.100015990436077e-06
0.016670000040903687
0.016669799922965467
0.016668600030243397
0.016668600030243397
0.016668800031766295
0.016668399912305176
0.01667120005004108
0.016669100034050643
0.016668599913828075
0.016668800031766295
0.016668800031766295
0.016668600030243397
0.016668399912305176
0.016669300035573542
0.0166680000256747
0.016668400028720498
0.016668399912305176
0.0166680000256747

```

Although `dt` is still about *last frame's* time, we're still controlling how *this frame's* time is spent.
> 1 votes

---
Tags: python, pygame, frame-rate, deltatime
---


# Question
Title: How would you implement card effects in a card game?
I'm making a card game right now and I am hesitating in how to design my cards.

Let me explain

I have a card that draws two cards from the deck when played. The way I'd code it is I'll create a class called Card where I'll put all the info a card could have (cost, description, name, etc). Then I'll create another class that'll inherit from Card and add a method to it which draws two cards, so when played, I'll call the method.

If the game gets bigger, would this be easily manageable and efficient?

Or how should I approach this instead?

# Answer
# Considerations

I have a couple of considerations for this architecture

## Cards with Multiple Effects

Right now, you have a card that when played, draws two cards. In the future, you might want a card that draws 3 cards and then discards 1, or a card that discards 1 and then draws 3.

A good architecture will allow you to re-use code between cards with similar effects.

## Cards which trigger other than when played

In a more complicated game, you might have a card that says, "When you draw this card, take two damage."

A good architecture will support weird cards like this.

# Solution: Events

If you are working in C# (like with Unity), there is an elegant language feature that can help here called Events.

Each event can take an arbitrary number of subscribers, and fires all of them in order when those events are triggered.

Here is some example code.

public delegate void CardEffect(CardPlayer player, CardGameObject? target);

public class Card
{
    public event CardEffect Played;

    public event CardEffect Drawn;

    public event CardEffect Discarded;

    // TODO: Write some code here to invoke the events when they come up.
}

public static class ExampleCards
{
    public static Card DrawTwo()
    {
        var card = new Card();
        card.Played += ExampleCardEffects.Draw(2);
        return card;
    }

    public static Card DrawThreeDiscardOne()
    {
        var card = new Card();
        card.Played += ExampleCardEffects.Draw(3);
        card.Played += ExampleCardEffects.Discard(1);
        return card;
    }

    public static Card TakeDamageWhenDrawn()
    {
        var card = new Card();
        card.Drawn += ExampleCardEffects.TakeDamage(2);
        return card;
    }
}

public static class ExampleCardEffects
{
    public static CardEffect Draw(int amount)
    {
        return (player, target) => player.Draw(amount);
    }

    public static CardEffect Discard(int amount)
    {
        return (player, target) => player.Discard(amount);
    }

    public static CardEffect DealDamage(int amount)
    {
        return (player, target) => player.DealDamage(target, amount);
    }

    public static CardEffect TakeDamage(int amount)
    {
        return (player, target) => player.DealDamage(player, amount);
    }
}

```

> 0 votes

---
Tags: architecture, software-engineering, card-game
---


# Question
Title: 2D turret aiming at the player, but only within a certain arc and with a defined angular velocity
I have a turret game object and a player game object, say it's a spaceship. Right now, every frame the turret updates its rotation, so it's always pointing at the player, giving it potentially infinite angular velocity.

What I want is to restrict the turret's aiming angle. As an example, say the turret may only track the player within an angle of 0 to 180 degrees (where orientation 0 would be "to the right", or Vector(1, 0)).

I can do this in code, but my issue is that if the player then enters the "tracking arc" of the turret, the turret immediately adjusts its rotation, seemingly "jumping" to tracking the player, whereas I want it to slowly rotate towards the player, based on some `agility` / `angular_velocity` variable.

How can implement an "angular velocity" so my turret rotates only at a certain speed?

My current code (scope turret):

```
function update(delta)
turret.rotation = getAngleFromTo(self.position, player.position)

```

# Answer
> 1 votes
First we'll make a couple utility functions:

```
// Map an angle into a standard range [-180, 180) degrees.
// (This matches Atan2 return range, avoids special cases for angles > 360 etc.,
//  and makes it easy to rotate "the shortest way" between two angles.)
float NormalizeAngle(float degrees) {
    degrees += 180f;
    float fullTurns = Mathf.Floor(degrees/360f);
    return degrees - fullTurns * 360f - 180f;
}

// Clamp an angle between a clockwise limit and counterclockwise limit (all in degrees),
// snapping out of bounds angles to whichever bound is closest around the circle.
float ClampAngle(float degrees, float cwLimit, float ccwLimit) {
    // Get all inputs into standard range, to minimize wrap-around cases to deal with.
    degrees = NormalizeAngle(degrees);
    cwLimit = NormalizeAngle(cwLimit);
    ccwLimit = NormalizeAngle(ccwLimit);

    // If in bounds, return the angle. Two cases for whether the allowed
    // range does not / does cross the -180/180 wrap-around point.
    if (ccwLimit >= cwLimit) {
        if (degrees <= ccwLimit && degrees >= cwLimit)
            return degrees;
    } else {
        if (degrees >= cwLimit || degrees <= ccwLimit)
            return degrees;
    }

    // If we get here, the angle is outside our range.
    // Find its difference from each limit:
    float cwDifference = Mathf.Abs(NormalizeAngle(degrees - cwLimit));
    float ccwDifference = Mathf.Abs(NormalizeAngle(degrees - ccwLimit));

    // Clamp to the closest of the two limits:
    if (cwDifference <= ccwDifference)
        return cwLimit;
    else
        return ccwLimit;
}

```

Now we can compute your new rotation angle like so:

```
float GetNewRotation(float degreesPerSecond, float deltaTimeSeconds) {

    // Form a vector pointing from the turret to the player.
    Vector2 toTarget = player.position - turret.position;

    // Extract the bearing angle from this vector, in range [-180, 180).
    float targetAngle = Math.Atan2(toTarget.y, toTarget.x) * Mathf.Rad2Deg;

    // Clamp to within our turret's min/max range.
    targetAngle = ClampAngle(targetAngle, turret.cwLimit, turret.ccwLimit);

    // Find shortest signed angle between current and target rotation.
    float difference = NormalizeAngle(targetAngle - turret.rotation);

    // Work out maximum travel this frame, and clamp difference to those bounds.
    float maxAngleStep = degreesPerSecond * deltaTimeSeconds;

    // Can be replaced with a Clamp(value, min, max) function if you have one.
    float step = Mathf.Min(Mathf.Max(difference, -maxAngleStep), maxAngleStep);

    // Increment our rotation angle by this limited step, and return a normalized version.
    return NormalizeAngle(turret.rotation + step);
}

```

---
Tags: 2d, rotation, linear-algebra, aiming
---


title: Unity Nested FOR loops Bug

text:
# Question
Title: Unity Nested FOR loops Bug
I'm writing a script to randomly generate a maze, and I can't even get it off the ground, rip. I've written fractal generators so I'm no stranger to nested FOR loops. `FOR x{ FOR y }`
I'm using my same old tricks to generate the maze. To initialize it, I set the boundary of the Maze (NESW sides) to be walls like so:

```
// Create
List<Room> row = new List<Room>();
for(int i=0; i<width; i++)  // Columns (X-axis)
{   row.Clear();
    for(int j=0; j<depth; j++){ // Rows (Z-axis)
        row.Add(new Room(i, yOffset, j));

        if(i==width-1){ Debug.Log("SetE: i "+i+", j "+j);
        row[j].setE(-1); }
        if(i==0){ Debug.Log("SetW: i "+i+", j "+j);
        row[j].setW(-1); }
    }
    row[width-1].setN(-1);
    row[0].setS(-1);
    rooms.Add(row);
}
// Instantiate
for(int i=0; i<width; i++) for(int j=0; j<depth; j++)
{   // Room
    Instantiate(roomGO, new Vector3(i + transform.position.x,
                           yOffset, j + transform.position.z), transform.rotation);
    // North Side
    Instantiate(getWall(rooms[i][j],0), new Vector3(i + transform.position.x,
                                           yOffset, j + transform.position.z + .75f), transform.rotation);
    // East Side
    Instantiate(getWall(rooms[i][j],1), new Vector3(i + transform.position.x + .75f,
                                           yOffset, j + transform.position.z), transform.rotation);
    // South Side
    Instantiate(getWall(rooms[i][j],2), new Vector3(i + transform.position.x,
                                           yOffset, j + transform.position.z - .75f), transform.rotation);
    // West Side
    Instantiate(getWall(rooms[i][j],3), new Vector3(i + transform.position.x - .75f,
                                           yOffset, j + transform.position.z), transform.rotation);
}

```

My problem is here (\*I think), Lines 7 to 10:

```
if(i==width-1){ Debug.Log("SetE: i "+i+", j "+j);
    row[j].setE(-1); }
if(i==0){ Debug.Log("SetW: i "+i+", j "+j);
    row[j].setW(-1); }

```

The positions are correct. I have no problems with the North and South sides.
The Western walls are not Instantiating. But the Eastern walls are Instantiating on every single row?
I'm trying to set all the West and East walls of the rooms with Coords `(x=0/x=Width, z)`. The `Debug.Log` lines are printing the expected coordinates.
**Question**
Why aren't the Eastern and Western walls Instantiating properly? What is a better way to set the walls of my Maze?

# Answer
Simple fix, the bug is not in lines 7 to 10 like I thought. Rather, because I'm adding the same instance of the List `row`, Clearing it, and adding it repeatedly, the rows get a little buggy. My fault for not seeing this.
Instead of `rooms.Add(row)`, I should have been using `rooms.Add(new List<Room>(row))`. This way, when I dump `row`, I still have the data stored in `rooms`.
*Special thanks to @DMGregory and @Pikalek*
> 1 votes

---
Tags: unity, maze
---


# Question
Title: Why is my alpha transparency not working correctly in Unity?
In Unity I have never seen a bug quite as weird as this one.

As usual, I import my texture with a transparent background and then check the alpha is transparency box and apply it, and everything seemed okay. It had worked like it usually does and made the background of my texture transparent. When I apply it to an object or even just paint it onto the terrain it shows the original texture, but in the areas where there should be nothing it replaces it with some nightmarish plaid hell.

I have tried other transparent textures but that doesn't seem to work either same result but for each different picture there is a different pattern and color of plaid. I really would appreciate any help I can get on this because I'm just stumped.

# Answer
> 0 votes
So I at least figured out a fix for some reason, my toon shader is just acting up and the regular unity shaders are doing just fine, so my first guess is that the toon shader is just not up to date. If I find out anything else I will post it here.

# Answer
> 3 votes
Try using a different shader on your material. `Unlit/Transparent` should do the trick, though without any lighting.

# Answer
> 0 votes
I faced a problem with alpha transparency. I wanted to make object transparent but changing the alpha was not working. Then i set rendering mode to transparent and it worked.

---
Tags: unity, textures, transparency
---


# Question
Title: How are playtesters recruited for closed playtests?
I've heard that large game studios often run playtests where they pull in people with no association to the project, have them play the game (usually under NDA), either with designers watching or the session recorded, and sometimes have them fill out a survey afterward to quantify the data.

Is this actually a thing? If so, how are those people recruited? Is it something that can be replicated on the scale of an indie dev or small team?

---

I see that a question like this one has been asked before, however, the dupe-chains all seem to wind up at a deleted question. I do not think this would be a dupe regardless, as the questions that get duped to that one tend to be about finding users for a large scale "open beta," and be about building an initial user-base (or, more frequently, trying to recruit users from this stack) rather than finding one-time test players for an NDA playtest.

# Answer
> 2 votes
> Is this actually a thing?

Yes.

> If so, how are those people recruited?

When I was at Ubisoft, we'd use a sign-up portal playtest.ubisoft.com/, where players could fill out a short survey about themselves and the games they play.

When planning a playtest, we'd consult that database to find players similar to the target audience of the game being tested (say, having played competing games in a similar niche, or previous games in the same franchise) and invite them to come to our playtest lab, typically for full-day play sessions over the course of a week.

(Since the COVID-19 pandemic, these playtests are now often conducted remotely, with players playing on their own PCs at home via game streaming software like Parsec, so the game code/assets never leave the studio to limit leaks)

As you say, these players would sign an NDA. Most often they're compensated for their time using free copies of games or gift cards, rather than cash payment as an employee or contractor. (There may be legal reasons for this, but not being a lawyer I can't share any particular expertise here)

> Is it something that can be replicated on the scale of an indie dev or small team?

I think other answers can speak to this in more detail, since my direct experience for the past decade has been limited to AAA. You're unlikely to be able to build up the kind of general-purpose playtester database that a big-name studio would have amassed over the years, but you do have options. From what I hear from Indies:

* A Discord server is a great way to cultivate a community around your game and gather early feedback. You'd promote the server on your game website and social media posts to attract folks interested in what you're making.

You can assign roles to users who have signed NDAs and give them access to "insider" channels for playtests and feedback. I've even heard of teams setting up Discord bots to automatically import posts from a Bug Report channel into their task-tracking software.

At the smaller end of the indie scale, you might not need to be too draconian about NDAs like the mega-corps trying to limit all leaks/cracks — just make sure there's a clear written agreement that the playtesters are not to redistribute in-development builds you provide, and that sharing/discussion of unreleased content shall be limited to the provided feedback channels. Talk to a lawyer for specifics related to your needs in your legal jurisdiction.
* You can advertise your game's playtest in dedicated promotion channels of other gaming Discords and social media communities, or dedicated playtester-recruiting spaces like r/playmygame.

Just be sure to check the community's moderation guidelines first, so you're not treated as a spammer for self-promotion beyond the community norms.

---
Tags: playtesting
---


# Question
Title: Pass input event from stage to added actor
I am diving into libgdx and used their sample game as a starting point.

I also added a touchpad to move the bucket. That was kind of easy and worked flawless. My additional idea was to make the touchpad disappear when not touching/clicking the screen and be shown again once you touch it. Basically to give the player the freedom to decide where he wants to have the touchpad located on the screen.

Watching this recording it works pretty good but obviously I don't want to make it follow the mouse constantly. So I tried to make the touchpad (which is an actor on my stage) invisible. As soon as I do that, I am losing the touch event being forwarded to the touchpad. See this recording.

My initial idea was to not have the pad constantly follow the mouse pointer (as I want to support touch screens at some point too). So the ideal approach I tried but failed to implement was to add the touchpad on any "down" event and and "move" event afterwards is dealt by the touchpad but that does not work. The stage keeps the primary target of the input event and the touchpad is not informed about anything. I tried it with an InputMultiplexer but failed with it as well...

Any ideas?

My main class:

```
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import com.badlogic.gdx.utils.ScreenUtils

class MyGame : ApplicationAdapter() {
    private lateinit var pad: Touchpad
    private lateinit var stage: Stage
    private lateinit var camera: OrthographicCamera

    override fun create() {
        // create the camera and the SpriteBatch
        camera = OrthographicCamera().apply {
            setToOrtho(false, 800f, 480f)
        }

        stage = Stage()
        stage.addListener(object : InputListener() {
            override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
                println("tdown")
                pad.isVisible = true
                return super.touchDown(event, x, y, pointer, button)
            }

            override fun mouseMoved(event: InputEvent?, x: Float, y: Float): Boolean {
                println("mmoved")
                if (!pad.isVisible) {
                    pad.x = x - pad.width / 2f
                    pad.y = y - pad.height / 2f
                }
                return super.mouseMoved(event, x, y)
            }

            override fun touchUp(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int) {
                println("tup")
                pad.isVisible = false
                super.touchUp(event, x, y, pointer, button)
            }
        })
        Gdx.input.inputProcessor = stage;

        val padBackground = TextureRegionDrawable(Texture(Gdx.files.internal("pad_circle.png")))
        val padThumb = TextureRegionDrawable(Texture(Gdx.files.internal("pad_thumb.png")))
        pad = Touchpad(10f, Touchpad.TouchpadStyle(padBackground, padThumb))
        pad.addListener(object : InputListener() {
            override fun enter(event: InputEvent?, x: Float, y: Float, pointer: Int, fromActor: Actor?) {
                println("pad enter")
                pad.isVisible = true
                super.enter(event, x, y, pointer, fromActor)
            }

            override fun exit(event: InputEvent?, x: Float, y: Float, pointer: Int, toActor: Actor?) {
                pad.isVisible = false
                println("pad exit")
                super.exit(event, x, y, pointer, toActor)
            }
        })
        pad.isVisible = false
        stage.addActor(pad)
    }

    override fun render() {
        ScreenUtils.clear(0f, 0f, 0.2f, 1f)
        camera.update()

        stage.act(Gdx.graphics.deltaTime)
        stage.draw()
    }

    override fun dispose() {
    }
}

```

# Answer
> 0 votes
I found the solution to my problem: InputMultiplexer (but used correctly :D )

My create() method in my main class now looks like this:

```
override fun create() {
    // create the camera and the SpriteBatch
    camera = OrthographicCamera().apply {
        setToOrtho(false, 800f, 480f)
    }

    stage = Stage()

    val padBackground = TextureRegionDrawable(Texture(Gdx.files.internal("pad_circle.png")))
    val padThumb = TextureRegionDrawable(Texture(Gdx.files.internal("pad_thumb.png")))
    pad = EnhancedTouchPad(10f, Touchpad.TouchpadStyle(padBackground, padThumb))
    stage.addActor(pad)

    val inputMultiplexer = InputMultiplexer()
    inputMultiplexer.addProcessor(0, pad.inputProcessor)
    inputMultiplexer.addProcessor(1, stage)
    Gdx.input.inputProcessor = inputMultiplexer
}

```

I also created my own Touchpad child class (mainly to organize my code better).

Anyway, with the multiplexer in place, it will basically call the InputProcessor correctly but (and I do not know the reason for that) it will not call any InputListener that is internally added inside the Touchpad. So what I had to do was to "forward" the `touchDragged` event manually from within the InputProcessor, see the `fireDrag(...)` method

```
class EnhancedTouchPad : Touchpad {
    constructor(deadzoneRadius: Float, skin: Skin) : super(deadzoneRadius, skin)
    constructor(deadzoneRadius: Float, skin: Skin, styleName: String) : super(deadzoneRadius, skin, styleName)
    constructor(deadzoneRadius: Float, style: TouchpadStyle) : super(deadzoneRadius, style)

    init {
        isVisible = false
    }

    val inputProcessor = object : InputProcessor {
        override fun keyDown(keycode: Int) = false

        override fun keyUp(keycode: Int) = false

        override fun keyTyped(character: Char) = false

        override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
            if (debug) println("touchDown")
            isVisible = true
            val touchPos = Vector3(screenX.toFloat(), screenY.toFloat(), 0f)
            stage.camera.unproject(touchPos)
            setPosition(touchPos.x - width / 2, touchPos.y - height / 2)
            fireDrag(touchPos.x, touchPos.y)
            return true
        }

        override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
            if (debug) println("touchUp")
            isVisible = false
            return true
        }

        override fun touchDragged(screenX: Int, screenY: Int, pointer: Int): Boolean {
            if (debug) println("touchDragged")
            val touchPos = Vector3(screenX.toFloat(), screenY.toFloat(), 0f)
            stage.camera.unproject(touchPos)
            fireDrag(touchPos.x, touchPos.y)
            return true
        }

        override fun mouseMoved(screenX: Int, screenY: Int) = false

        override fun scrolled(amountX: Float, amountY: Float) = false
    }

    fun fireDrag(eventX: Float, eventY: Float) {
        val inputEvent = InputEvent()
        inputEvent.type = InputEvent.Type.touchDragged
        inputEvent.stageX = eventX
        inputEvent.stageY = eventY
        this.fire(inputEvent)
    }
}

```

---
Tags: libgdx, touch
---


# Question
Title: Can't play my .apk on Pico VR due to Copyright Verification error
I’m learning to use Unity to create VR applications for my company to use internally. I created an app that worked great on the Quest 2, and decided to try to do this for Pico as well. I followed a tutorial for Pico, and was able to get a working .apk file and transfer it to my Pico Neo 3 Pro using ManageXR (MDM).

I was able to view my app in VR for about 10 seconds, just long enough to see it was working – but then Pico automatically closed it and displayed this message: This app didn’t pass “Copyright Verification”. Go to “App Store” to check if you’ve purchased this app and restart it. Go to “app Store”? \[Exit\] \[Enable\] I pressed Enable, and expectedly the app store said “No information available” I’ve already created a Pico developer account, and got an app ID, which I included in the .apk. I don’t want this app to be publicly accessible, I just want to explore VR for internal use.

I want to iterate & develop. Any ideas how to get past this issue?

# Answer
> 3 votes
Go to PXR\_SDK (on top ribbon of Unity, next to Windows), click Platform Settings, make sure User Entitlement Check\[?\] box is unchecked.

This fixed it for me - thank you Luis Z!

---
Tags: unity, android, virtual-reality
---


# Question
Title: How to make animation in unity Dots hybrid?
I'm working on isometric game in 2D but didn't find any good tutorial in how to handle animation...any help?

# Answer
> 1 votes
> **Update:** There is now an animation package for DOTS which might work better than what is described in this answer, but is still considered highly experimental.

As far as I am aware, the machinima animation system with its convenient visual state machines and animation timelines isn't ported to DOTS yet. So you will have to program your own. My approach would be as follows:

1. Create a new shared component `Animation` which refrences the meshes used for all the different animation frames of an animated asset.
2. Create instances of that shared component - one for each asset you want to animate.
3. Assign those shared `Animation` component instances to any entities you want to animate.
4. Create a new system `AnimationSystem` which queries all entities with `Animation`, `Unity.Rendering.RenderMesh` and any components which are relevant for determining what frame to display (Maybe `Unity.Transforms.Rotation` to determine the direction it faces? Maybe `Unity.Physics.MotionVelocity` to determine if it's running or standing? Maybe a component of your own which handles the current state of your entity?).
5. Implement the system to use the data from the components to determine which frame to display, retrieve the mesh for that frame from the `Animation` component and apply it to the `RenderMesh.mesh` of the entity.

# Answer
> 0 votes
The DOTS Animation package is no longer usable and the next release isn't planed for quite some time. We have to go back to the Hybrid approach.

Here is a tutorial series that covers 1.0 and it's latest episode covers hybrid animation.

---
Tags: unity, 2d, animation, entity-component-system, unity-dots
---


# Question
Title: Getting the face of a cube when using arrows to rotate it
I've got a 3D cube in a scene, and rotatable using arrow keys. This is what it looks like, imagine that the boxes are left, right, up, and down.

Unlike other questions, I am not casting a ray cast at the cube directly, though I am trying to do this to figure out what face is facing the camera.

I want to be able to figure out what face is facing the camera, and when the arrows are what trigger the movement 90' in a given direction.

Once I listen for the arrows moving left or right, I try to cast a Raycast directly at the cube - but it doesn't seem to hit anything or make a difference if I use a 2D or 3D raycast. My scene is in 2D, but my cube is 3D. What am I doing wrong?

Here is my code:

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

public enum MCFace
{
    None,
    Up,
    Down,
    East,
    West,
    North,
    South
}

public class CubeHandling : MonoBehaviour
{
    private void OnEnable()
    {
        TouchScreenManager.SignalButton += CheckCubeFace;
    }

    private void OnDisable()
    {
        TouchScreenManager.SignalButton -= CheckCubeFace;
    }

    void CheckCubeFace(GameObject arrow)
    {
        if (arrow.name == "Left" || arrow.name == "Right")
        {
            // now cast another raycast at the cube
            var position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, 0);
            Ray ray = Camera.main.ScreenPointToRay(gameObject.transform.position);

            Physics.Linecast(Camera.main.transform.position, position, out RaycastHit hit);
            Debug.Log("the ray is: " + ray + " and the hit is  " + hit);

            var face = GetHitFace(hit);
            Debug.Log(face);
        }
    }

    public MCFace GetHitFace(RaycastHit hit)
    {
        Vector3 incomingVec = hit.normal - Vector3.up;

        if (incomingVec == new Vector3(0, -1, -1))
            return MCFace.South;

        if (incomingVec == new Vector3(0, -1, 1))
            return MCFace.North;

        if (incomingVec == new Vector3(0, 0, 0))
            return MCFace.Up;

        if (incomingVec == new Vector3(1, 1, 1))
            return MCFace.Down;

        if (incomingVec == new Vector3(-1, -1, 0))
            return MCFace.West;

        if (incomingVec == new Vector3(1, -1, 0))
            return MCFace.East;

        return MCFace.None;
    }
}

```

Edit: I have now transformed the normal into the object's local space, which seems to be working. However, note that my arrows are meant to do the following - left and right will move the block both sides on the y axis. Up and down will move it on the x axis.

However, there now appears to be a problem synching up all of the movements so the faces stay consistent no matter what order the arrows are pressed in.

If the front-facing side is "West", and I press the left arrow, I will see the following movement:

West \> North \> East \> South

However, if I now press the right arrow, it does this:

South \> West \> South \> East \> North, etc.

I am not sure why it would repeat itself, and indicate faces out of order.

This may be to do with how I am rotating my cube:

```
IEnumerator RotateCube(GameObject UI)
    {
        float timeElapsed = 0;
        Quaternion startRotation = cube.transform.rotation;
        Quaternion targetRotation = cube.transform.rotation;

        if (gameObject.name == "Up" || gameObject.name == "Down")
        {
            targetRotation *= Quaternion.Euler(angleRotation, 0, 0); // this rotation depends on the face. sometimes it'll be rotating on the y-axis, other times on the z.
        } else
        {
            targetRotation *= Quaternion.Euler(0, angleRotation, 0);
        }

        while (timeElapsed < lerpDuration)
        {
            cube.transform.rotation = Quaternion.Slerp(startRotation, targetRotation, timeElapsed / lerpDuration);
            timeElapsed += Time.deltaTime;
            yield return null;
        }
        cube.transform.rotation = targetRotation;
    }

```

# Answer
> 1 votes
```
MCFace GetSideFacing(Transform cube, Vector3 direction) {
    var localDirection = cube.InverseTransformDirection(direction);

    var positive = Vector3.Scale(localDirection, localDirection);

    if (positive.x > positive.y) {
        if (positive.x > positive.z) {
            return localDirection.x > 0 ?
                   MCFace.East : MCFace.West;
        } else {
            return localDirection.z > 0 ?
                   MCFace.North : MCFace.South;
        }
    } else {
        if (positive.y > positive.z) {
            return localDirection.y > 0 ?
                   MCFace.Up : MCFace.Down;
        } else {
            return localDirection.z > 0 ?
                   MCFace.North : MCFace.South;
        }
    }

}

```

Now you can skip the raycast and just call:

```
GetSideFacing(cube.transform,
     Camera.main.transform.position - cube.position);

```

Of course, since you're controlling this cube in 90 degree increments, you could also just keep track of which face is pointing which way as part of your rotation logic.

---
Tags: unity
---


# Question
Title: How do you limit the Pitch of the UE4 and UE5 camera which is on a Springarm in C++
I want to limit the pitch of the Player camera, which is connected to the spring arm attached to the player capsule.  I **want to do this in C++ rather than Blueprints.**

Does anyone know how to implement this in C++ for the Unreal Engines?

# Answer
I rephrased my question in several ways and came up with a solution which I would lie to share.

In BeginPlay of the PlayerController add the code below.

```
APlayerController* ShooterPlayerController = Cast<APlayerController>( Controller );
if ( ShooterPlayerController )
{
    if ( ShooterPlayerController->PlayerCameraManager )
    {
        ShooterPlayerController->PlayerCameraManager->ViewPitchMin = -45.0;
        ShooterPlayerController->PlayerCameraManager->ViewPitchMax = 45.0;
    }
}

```
> 0 votes

---
Tags: camera, unreal, unreal-5
---


title: Add a placeholder text to the TextField

text:
# Question
Title: Add a placeholder text to the TextField
This is my TextField:

```
EditorGUILayout.TextField("Placeholder Text", textfield, GUILayout.Height(35));

```

How can I add a placeholder text in my textfield that will be removed when I want to type in the field?

# Answer
> 1 votes
@Thomas Mathieson approach is close to the answer, but I'd like to add more. With this example the text field value will return to the default Placeholder text if it is empty:

```
private string defaultPlaceHolder = "Insert Text: ";
public string textFieldValue;

textFieldValue = EditorGUILayout.TextField(textFieldValue == string.Empty ? defaultPlaceHolder : textFieldValue, GUILayout.Height(35));

```

To avoid having the Placeholder value on Play mode, you could either add more logic, or just set the value to **string.Empty** if the value is equal to the Placeholder's.

Additionally, **EditorGUILayout.TextField** has an overload that takes a **GUIStyle** as a parameter, with that you can change the placeholder color to a more gray one, to give that illusion that it's a placeholder. I just have used **GUIStyle** for textures, so I don't know exactly how to change the text color, but, you could check by tweaking values on the inspector, just serialize a GUIStyle, and assign that to the **TextField**, something like this:

```
public GUIStyle textStyle;
public string textFieldValue;
private string defaultPlaceHolder = "Insert Text: ";

textFieldValue = EditorGUILayout.TextField(
                "Text Field Label: ",
                textFieldValue == string.Empty ? defaultPlaceHolder : textFieldValue,
                textStyle);

```

Check TextField's Overloads for more reference. Hope it helps.

# Answer
> 1 votes
I was looking for the same thing as OP and didn't find an answer here, so here's my solution:

Imports:

```
using System;
using UnityEditor;
using UnityEngine;

```

Simplest implementation:

```
string TextField(string text, string placeholder) {
    var newText = EditorGUILayout.TextField(text);
    if (String.IsNullOrEmpty(text)) {
        var guiColor = GUI.color;
        GUI.color = Color.grey;
        EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), placeholder);
        GUI.color = guiColor;
    }
    return newText;
}

```

Implementation supporting both TextField and TextArea using generic method, as well as placing Label at the same spot where Text is rendered:

```
string TextField(string text, string placeholder) {
    return TextInput(text, placeholder);
}

string TextArea(string text, string placeholder) {
    return TextInput(text, placeholder, area: true);
}

private string TextInput(string text, string placeholder, bool area = false) {
    var newText = area ? EditorGUILayout.TextArea(text) : EditorGUILayout.TextField(text);
    if (String.IsNullOrEmpty(text.Trim())) {
        const int textMargin = 2;
        var guiColor = GUI.color;
        GUI.color = Color.grey;
        var textRect = GUILayoutUtility.GetLastRect();
        var position = new Rect(textRect.x + textMargin, textRect.y, textRect.width, textRect.height);
        EditorGUI.LabelField(position, placeholder);
        GUI.color = guiColor;
    }
    return newText;
}

```

Usage:

```
string text = String.Empty;
string area = String.Empty;

void OnGUI() {
    text = TextField(text, "Field placeholder");
    area = TextArea(area, "Area placeholder");
}

```

Here's how it looks in Unity:

# Answer
> 0 votes
I've not been able to test this but you could try:

```
//In the script initialisation
string textfield = "Placeholder text";
//In the OnGui function
textfield = EditorGUILayout.TextField(textfield,GUILayout.Height(35));

```

# Answer
> 0 votes
Try using this code:

```
public string inputContent = "";
public string placeholder = "Text here...";

private void OnGUI() {
  // Draw TextArea
  inputContent = EditorGUILayout.TextArea(inputContent, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
  // Draw Placeholder
  if (string.IsNullOrEmpty(inputContent)) {
    Rect pos = new Rect(GUILayoutUtility.GetLastRect());
    GUIStyle style = new GUIStyle
    {
      alignment = TextAnchor.UpperLeft,
      padding = new RectOffset(3, 0, 2, 0),
      fontStyle = FontStyle.Italic,
      normal =
      {
        textColor = Color.grey
      }
    };
    EditorGUI.LabelField(pos, placeholder, style);
  }
}

```

That's what it will look like:

---
Tags: unity
---


title: Get the closest point on an SDF

text:
# Question
Title: Get the closest point on an SDF
Is there a cheap and effective way to get the closest point on an SDF? (signed distance field). CodeParade made a video on a game he developed that uses SDF collisions with a sphere, how did he do it? I understand how he was able to detect if a collision occurred, but not how he got the point of collision.

# Answer
I believe this is the video in question: Marble Marcher - A Fractal Physics Game.

We can find the source code in the description: MarbleMarcher source code.

Looking around in main, I see here there is an `UpdateMarble` method of the Scene class here. Which in turn calls `MarbleCollision`.

There we see it uses two relevant methods:

* `DE`: distance estimator.
* `NP`: Nearest point.

But it does ray marching, right? I expected there would be some code that uses `DE` for ray marching, but there isn't. So looked for where does ray marching happen, and - I should have expected this - it happens in the GPU. Futhermore, the `DE` code has a counterpart in a shader here. But `NP` does not!

Thus, the game is not getting the nearest point from a signed distance field. It is using an alternative field that gives the nearest point (a 3D Vector) instead of the distance (a float value).

*The details of this alternative field are specific of the fractal, in a similar fashion that you have dedicated functions for the signed distance field of different shapes.*
> 1 votes

---
Tags: collision-detection, collision-resolution, signed-distance-field, raymarching
---


# Question
Title: Viewport controls in UE5 - can you lock the Z axis?
I recently got into UE5 after using Unity some years ago - I am a bit surprised about the shooter-like controls in the level editor, as most of the time I will want to pan across the level (X/Y axes) while looking down at the level at an angle. Using the default controls, moving with W will move me straight through the level.

While holding down the LMB, dragging up/down actually does exactly what I would want from the W and S keys - is there any way to configure them to do just that?

# Answer
For panning, the docs say:

> Alt + MMB + Drag
>
> Tracks the camera left, right, up, and down in the direction of mouse movement.

I'm not an UE5 dev so I can't test this solution myself.
For future reference, Unreal Engine 5 uses Maya style controls - if you have trouble finding navigation / UI info for EU5 directly, try searching for the same thing with Maya instead.
> 0 votes

---
Tags: unreal-5, configuration
---


title: What is a 'Mask' in Game development?

text:
# Question
Title: What is a 'Mask' in Game development?
* What does it mean a 'mask' in 2D (and possibly 3D) Game development?
* What would an experience Game Dev understands if I say ´make this Rect a mask´?

I know it could be a very broad term and it may depend on the context, if is so then just a bullet list of possible meaning would do.

---

My understanding is that is something that 'masks' with the purpose to cover some other entity on the game world, however what are the most use cases and why would you use it?

I research a bit online, but because of the naming 'mask' the search result gets easily polluted with unreleated topic (especial after covid).

# Answer
Conceptually, masking involves selectively ignoring something, usually to isolate something else.

The two main uses I've familiar with are:

1. Masking data such as bit fields or flags for bitwise operations.
2. Masking images, often for compositing or other effects.

**Data Masking**

For an example of the first, let's say you have a bit field such as the 6502 status register:

| Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **N**egative flag | o**V**erflow flag | - | **B**reak flag | **D**ecimal flag | **I**nterrupt-disable flag | **Z**ero flag | **C**arry flag |

`AND`ing the register with `01000000` would mask out everything except the overflow flag. So something like `if(R & 01000000)` would allow you to check for the overflow condition. Specifically, the logical operation preserves (masks) only the 6th bit for evaluation.

**Image Masking**

This question examines ways to use an alpha mask to ignore unwanted portions of a texture in order to get a more complex result:

| Mask | Addition of a red hexagon sprite | Result of masking the sprite |
| --- | --- | --- |
|  |  |  |

In the above example, the mask preserves the portion of the sprite in the round center area. You might use this form of masking to implement a circular field of view in a top down game as it allows the player to see things in the field of view, but not outside it.

It's probably worth mentioning, sometimes it can be a bit ambiguous regarding whether mask is being used to refer to what is kept versus what is discarded.
> 34 votes

# Answer
Maybe I'm too old, but back in the day a mask meant an area of blank pixels around the outer shape of a sprite. This was to isolate the sprite from the background and prevent the background colours mixing with or showing through the sprite colours. I'm sure it's still used in 2D games to give sprites separation from the background. In fact, you can see a mask at work when you look at your mouse cursor - the white area around the black arrow icon is a mask.

The mask data was often stored alongside the sprite data, and applied first to the background to mask out a "hole" for the sprite, before the sprite was drawn on top.
> 4 votes

# Answer
This is how Wikipedia describes it.

> This technique is used for painting pointing device cursors, in typical 2-D videogames for characters, bullets and so on (the sprites), for GUI icons, and for video titling and other image mixing applications.

Although, personally, I mostly only use masks for UI. Very often you'll have one UI element sliding under another and a mask is an easy way to prevent something from being visible when it shouldn't.
> 2 votes

# Answer
There are some decent answers so far, but I think this part deserves a bit more attention.

> What would an experience Game Dev understands if I say ´make this Rect a mask´?

To a game dev, there would be no doubt that if you are using a Rect (short for rectangle in a lot of game engines), that you would clearly be asking about an image mask. You would generally not be creating a data mask from a polygon.

However, if the developer is unfamiliar with the project, there may be some ambiguity about if you want a vector or raster mask. 2d graphics can generally be saved in 2 ways, a vector image which is a composition defined by lines drawn from points procedurally filled with colors, or a raster image which is an image made from a grid of pixels. In most cases it does not matter that much which kind of map you use, but it can. If you are trying to mask an image that has to be highly scalable, you will generally want to use a vector mask to keep from loosing detail to poor resolutions. If you need to make an especially complex mask, like for doing photographic selective tinting, then a raster mask is often the better choice.
> 2 votes

---
Tags: 2d, 3d, terminology, masking, tile-bitmasking
---


title: Rotate and Zoom a group of tiles

text:
# Question
Title: Rotate and Zoom a group of tiles
I'm working on a tile-based game and I'm trying to rotate my tiles as a group around the center of the screen and want to have the ability to zoom in and out. Here my code:

```
        Matrix transform = Matrix.CreateTranslation(new Vector3(-origin.X, -origin.Y, 0f)) *
                           Matrix.CreateRotationZ(rotation) *
                           Matrix.CreateScale(new Vector3(zoomFactor, zoomFactor, 0)) *
                           Matrix.CreateTranslation(new Vector3(Basic.width, Basic.height, 0));

        Vector2 pos = new Vector2(r.X, r.Y);
        pos = Vector2.Transform(pos, transform);
        r.X = (int)pos.X;
        r.Y = (int)pos.Y;
        angle += rotation;

        Draw(r, origin, angle, zoomFactor, Color.White);

```

Somehow, this rotates my tiles around the lower right corner of the screen. The zooming point is also there.

When setting the second CreateTranslation to

```
        Matrix.CreateTranslation(new Vector3(origin.X, origin.Y, 0))

```

only 1/4 of the screen is visible.

Can someone help me with this? I just want to let the tiles rotate as a group around the center of the screen. Zomming should also be centered. How to achieve this without using a 2D camera?

Thank you very much!

# Answer
> 2 votes
Pass your `transform` matrix to the `_spriteBatch.Begin()` method.

The following code provides the default parameters.

```
_spriteBatch.Begin(SpriteSortMode.Deferred,null,null,null,null,null,transform);

```

Note that this only applies to drawing, and any collision code will need to be adjusted accordingly.

---
Tags: xna, sprites, monogame, scale, rotate
---


title: Decouple shared data from consumers

text:
# Question
Title: Decouple shared data from consumers
I am a former Unity user, and after a big pause in game dev decided to try out Monogame (I'm a software engineer IRL so I'd figure this is the best way to go).

In Unity I was using scriptable objects to decouple my data from their mutators / consumers, as explained here.

For example, I would have a scriptable object that represented my player's health, and my player entity would just have it as a public field and in the editor I could drag the scriptable object in.

My UI was also interested in the health, so I could just expose a public field on my health bar and it would consume it.

Hence my data was decoupled from the once using it and no dependencies where between different systems.

So I'd like to reproduce this in Monogame.

I was thinking of using something like a service provider / locator pattern where I could register the health for my player for example and each system needing it would retrieve it trough that.

This seems less flexible though then the way Unity shows it, as I could have multiple 'healths' registered, and to get the right one would mean I'd have to find a way to retrieve the right one (which is totally possible but more complex then just dragging in the right scriptable object in Unity).

Someone found a nice way of doing this before I dive in?

# Answer
In MonoGame you are welcome to implement any structure you want.

Remember the KISS principle. Don't over think it or over engineer.

A single static class can hold any/all game wide data.

A `public static int Score = 0, Health = 100;` in Game1.cs is sufficient for most purposes.

Multiple health's is achieved via instance health variables in each class.
> 0 votes

---
Tags: unity, monogame, scriptable-object
---


# Question
Title: Best way to draw a tile (a floor) all over the screen?
I wanted a tip, a guidance perhaps to know the best way to draw a tile all over the screen. This tile is a 16x16 tile that should be the floor in my top-down map. I set my resolution to 1280x720 and i know i should make a foreach and a for loop ( i looked around in the foruns to find this) but couldn’t make it work on my own. I just finished a monogame course and i’m trying to make a game on my own to really acknowledge the things i’ve learned, but i wanted a help with it if anyone could. I wanted to do the same thing to draw things repetitively on the screen (like trees, rocks, and this kind of stuff). My tile is called “floor”, it’s imported alright and it is loaded too with `backGroundFloor = Content.Load<Texture2D>("background/floor");`

Anyone know a way to solve this? Also, would this be the best way to do it, or should i just draw a full map and place it on screen? I think this way would be more complicated with itens on the screen to handle collisions and etc

# Answer
The tile is 16x16, so calculate the number of tiles required for the width:

`1280 / 16 = 80` `720 / 16 = 45`

So 80 wide by 45 tall:

This means that you need to draw 80 * 45 = 3600 instances to the screen in the `Draw()` method:

```
for (int i = 0; i < 3600; i++)
   _spriteBatch.Draw(backGroundFloor, new Vector2(i % 80 * 16, i / 80 * 16), Color.White);

```

Make sure that this line is higher(first) than the other Draw statements or loops so that it remains in the background.
> 0 votes

---
Tags: c#, xna, monogame
---


# Question
Title: Meshes seem to get distorted when I use rotate or zoom transforms (XNA/Monogame)
Whenever I seem to create a rotation matrix or try to zoom, the meshes that I draw to the screen get stretched and distorted.

I've tried to make a simple rotation matrix like this:

```
Matrix transform = Matrix.CreateRotationZ(MathHelper.ToRadians(ang))

```

And then I do this when I make the vertices:

```
verts[i].Position = Vector3.Transform(verts[i].Position, transform);

```

And it *does* rotate it, but it also gets stretched at the same time.

Similarly, I made a simple Camera class:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;

namespace _04_texturedquad
{
    public class Camera
    {
        public Vector2 position {get; private set;}

        public Matrix ortho;

        float zoom;

        public float rotation;

        Viewport viewport;

        public Camera(Viewport v)
        {
            this.viewport = v;

            ortho = Matrix.CreateOrthographicOffCenter(
            0,
            viewport.Width,
            0,
            viewport.Height,
            0, 1);
        }

        public void Move(Vector2 vec)
        {
            this.position += vec;
            Update();
        }

        public void Zoom(float amount)
        {
            zoom += amount;
            Update();
        }

        public void SetPosition(Vector2 vec)
        {
            this.position = vec;
        }

        public void Update()
        {
            ortho = Matrix.CreateOrthographicOffCenter(
            0               + position.X - zoom,
            viewport.Width  + position.X + zoom,
            0               + position.Y - zoom,
            viewport.Height + position.Y + zoom,
            0, 1);
        }
    }
}

```

And moving around works, but when I zoom, it *does* zoom, but it also gets stretched vertically when I do so.

Here's what I'm doing when I'm sending the buffers to the GPU:

```
public void Draw()
    {

        RasterizerState rs = new RasterizerState();
        game.GraphicsDevice.RasterizerState = rs;

        effect.Projection = c.ortho;

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            game.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, _vertices, 0, _vertices.Length, _indices, 0, _indices.Length / 3, VertexPositionColor.VertexDeclaration);
        }
    }

```

I've also tried setting effect.View = Matrix.Identity, but that hasn't worked either.

Why does everything get distorted when I zoom/rotate? I don't think this is a problem with how I'm making the meshes, because they look fine otherwise.

# Answer
Your camera is an Orthographic projection. Zoom should have no effect; When non-axis aligned, the view produces distortion on all non-90 degree angles by definition.

Use the following code in place of:

```
//ortho = Matrix.CreateOrthographicOffCenter(
//...
//with:

CreatePerspectiveOffCenter(new Rectangle(0,0,viewport.Width,viewport.Height),0,500);

```

The signature is: `CreatePerspectiveOffCenter(Rectangle viewingVolume, float nearPlaneDistance, float farPlaneDistance)`
> 0 votes

---
Tags: xna, monogame, matrix
---


title: Drawing Textured Quads

text:
# Question
Title: Drawing Textured Quads
I've been starting to write some XNA / Monogame code lately, and wanted to draw a quad with a Texture2D attached to it.

After searching the internet for a while, I've come up with this render code:

```
public void Draw(GraphicsDevice gd)
{
    BasicEffect effect = new(gd);
    effect.Texture = this.texture;
    effect.TextureEnabled = true;

    VertexPositionTexture[] vertices = new VertexPositionTexture[4];
    vertices[0].Position = this.pointA;
    vertices[1].Position = this.pointB;
    vertices[2].Position = this.pointC;
    vertices[3].Position = this.pointD;

    foreach (EffectPass pass in effect.CurrentTechnique.Passes) {
        pass.Apply();
        gd.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices,
        0, 3, new[] { 0, 1, 2, 1, 2, 3 }, 0, 2);
    }
}

```

in a `Quad` class:

```
internal sealed class Quad
{
    Vector3 pointA;
    Vector3 pointB;
    Vector3 pointC;
    Vector3 pointD;
    Texture2D texture;
}

```

with this initialization code:

```
Quad quad = new Quad(new Vector3[]
{ new Vector3(-0.5f, -0.5f, 1f), new Vector3(-0.5f, +0.5f, 1f),
  new Vector3(+0.5f, -0.5f, 1f), new Vector3(+0.5f, +0.5f, 1f) } //points
debugTexture);

```

Currently, nothing appears on the screen. I've tried drawing 1 triangle only, switching out the `debugTexture`, using `DrawUserPrimitives` instead, and none of them seem to work.

After doing some testing, I found that it *did* actually work. I was just clearing the screen with white, which, coincidentally, the quad I was drawing was *also* white.

This means that the only problem now was that the quad didn't have the texture attached.

# Answer
The `VertexPositionTexture` requires a `.TextureCoordinate` aswell.
(where 0f being the start, 1f being the end.)

The solution is just:

```
// VertexPositionTexture
//     Vector2 position (Viewport coordinate [-1.0->1.0]),
//     Vector2 texturePosition (Texture coordinate [0.0->1.0]
VertexPositionTexture[] vertices = new VertexPositionTexture[4]
{
    new VertexPositionTexture(pointA, new Vector2(0f, 1f)),
    new VertexPositionTexture(pointB, new Vector2(0f, 0f)),
    new VertexPositionTexture(pointC, new Vector2(1f, 1f)),
    new VertexPositionTexture(pointD, new Vector2(1f, 0f)),
};

```

and replace the `DrawUserIndexedPrimitives` with

```
GraphicsDevice.DrawUserIndexedPrimitives(
    PrimitiveType.TriangleList, // Specify tri-based quad assembly
    vertices,                   // Your input vertices
    0,                          // Offset in vertex array (0 for no offset)
    4,                          // Length of the input vertices array
    new[] { 0, 1, 2, 1, 2, 3 }, // Indicies (a tri with index (0, 1, 2), and (1, 2, 3))
    0,                          // Offset in index array (0 for none)
    2                           // Number of tris to draw (2 for a square)
);

```

Note that the input vertex array is order-sensitive and you might get wrongly assembled quads if the order isn't correct.
> 0 votes

---
Tags: c#, xna, monogame
---


# Question
Title: The Script says class not derived from MonoBehaviour in Unity
No matter what script I try to add, it always says the script does not contain a class from UnityEngine.MonoBehaviour. An example script I'm trying to use is this:

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

public class Wander : MonoBehaviour
{

    public float wanderRadius;
    public float wanderTimer;

    private Transform target;
    private NavMeshAgent agent;
    private float timer;

    // Use this for initialization
    void OnEnable()
    {
        agent = GetComponent<NavMeshAgent>();
        timer = wanderTimer;
    }

    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;

        if (timer >= wanderTimer)
        {
            Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
            agent.SetDestination(newPos);
            timer = 0;
        }
    }

    public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask)
    {
        Vector3 randDirection = Random.insideUnitSphere * dist;

        randDirection += origin;

        NavMeshHit navHit;

        NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);

        return navHit.position;
    }
}

```

# Answer
> 1 votes
This happens when you change the name of the class or file, but not the other. Make sure that your class and file name match. Also make sure the file is in the Assets folder, or a subdirectory of it.

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


# Question
Title: Animation plays when walking left but not right
I have created two animations: "Walk" and "Idle" and I made the transitions from "Idle" to "Walk" and from "Walk" to "Idle" as well.

When I go the the left side, the "Walk" animation is being played, but when I go to the right, the animation doesn't play.

Here is my Movement Function:

```
void PlayerMovement()
{
    tempPos = transform.position;
    float h = Input.GetAxisRaw("Horizontal");

    if (h > 0)
    {
        //tempPos.x += speed * Time.deltaTime;
        animator.SetBool("WalkParam", true);
        //sr.flipX = false;

    }
    if (h < 0)
    {
        //tempPos.x -= speed * Time.deltaTime;
        animator.SetBool("WalkParam", true);
        //sr.flipX = true;
    }
    else
    {
        animator.SetBool("WalkParam", false);
    }
    transform.position = tempPos;
}

```

# Answer
The problem might be more obvious if we adjust the whitespace in your code like so:

```
if (h > 0) {
    animator.SetBool("WalkParam", true);
}

if (h < 0) {
    animator.SetBool("WalkParam", true);
} else {
    animator.SetBool("WalkParam", false);
}

```

See how the case that checks for movement to the right is completely separated from the case that checks to the left?

So let's step through this code for a frame when `h > 0`:

1. We hit the first `if` and pass the test, so we enter the block.
2. Inside this `if` block, `"WalkParam"` gets set to `true`.
3. We resume execution at the end of the first `if`'s block, since it has no attached `else if` or `else` blocks to skip over.
4. We hit the second `if` and fail the test, so we skip to the `else` block.
5. Inside this `else` block, `"WalkParam"` gets set to `false`.

So we finish this function with `WalkParam` set to false.

You can fix this by changing your second `if` to an `else if`, so it's only executed if the first `if` test fails, and skipped otherwise. That joins the full `if`-`else if`-`else` into one chain, where exactly one of their contained blocks will be executed. Without this joining keyword, each `if` will be checked independent of the previous test's outcome.

But you can actually do all this much more simply:

```
// Use approximate comparisons for floats,
// in case of small rounding errors
if (Mathf.Approximately(h, 0)) {
    animator.SetBool("WalkParam", false);
} else {
    // Use one branch for both walk directions.
    // Less repetition = fewer places for bugs.
    float step = Mathf.Sign(h) * speed * Time.deltaTime;
    transform.Translate(step, 0, 0, Space.World);
    animator.SetBool("WalkParam", false);
    sr.flipX = h < 0;
}

```
> 0 votes

---
Tags: unity, c#, 2d, animation
---


# Question
Title: When I rotate a game object, it keeps moving the same direction
When I try to rotate my game object, it keeps moving in same direction. I think there is pretty basic solution but couldn't figure it out.

Here is my code:

```
private void Move()
{
    rb.velocity = new Vector3( rb.velocity.x, rb.velocity.y, speed * forwardSpeedMultiplier * Time.deltaTime );

    float xVelocity = horizontalInput * speedMultiplier * horizontalSpeed * Time.deltaTime;
    float yVelocity = -verticalInput * speedMultiplier * verticalSpeed * Time.deltaTime;

    rb.velocity = Vector3.Lerp(rb.velocity,
        new Vector3(xVelocity, yVelocity, rb.velocity.z),
        Time.deltaTime * smoothness);
}

```

Note that I am using a rigidbody to move it.

I try to add `+ transform.forward` to the first line. It kind of works but it messes up the speed. I know this is probably basic question but still would appreciate the help.

# Answer
> 1 votes
When you multiply a speed by a time interval, you get a distance, not a speed. So you should delete the `* Time.deltaTime` from every line where it's being multiplied by a speed parameter. (And then reduce your speed parameters by a factor of 30 or 60 so they're actually measuring speed correctly)

Now, it looks to me like you want to construct a new speed relative to the object's orientation, something like this:

```
// Compute velocity in local coordinates:
Vector3 targetVelocityLocal = new Vector3(
                                   horizontalInput * speedMultiplier,
                                  -verticalInput * speedMultiplier,
                                  speed * forwardSpeedMultiplier
                              );

// Rotate velocity into world coordinates:
Vector3 targetVelocityWorld = rb.rotation * targetVelocityLocal;

// Accelerate toward this velocity:
Vector3 deltaV = targetVelocityWorld - rb.velocity;

rb.AddForce(deltaV * smoothness * Time.deltaTime, ForceMode.VelocityChange);

```

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


# Question
Title: Object stuck to screen no matter what eye position is used
I've run into an issue when trying to write a simple rendering program in D3D11. I'm 90% sure it's to do with some faulty matrix multiplication or generation, but I've tried debugging the values of the matrices and they seem fine to me.

The problem is that no matter where I move the eye position, the rendered cube always appears the same.

The resulting screen image is like this:

Each vertex of the cube has a different colour, and the pixel shader should be blending between them, so the gradient effect you can see is between four vertices of the cube.

Here's some of my code

```
eyePos = XMVectorSet(0.0f, 1.0f, -5.0f, 0.0f);
lookAtPos = XMVectorSet(0.0f,1.0f,0.0f,0.0f);
up = XMVectorSet(0.0f,1.0f,0.0f,0.0f);

world = XMMatrixIdentity();
view = XMMatrixLookAtLH(eyePos, lookAtPos, up);
projection = XMMatrixPerspectiveFovLH(XM_PIDIV2, 1000.0f / 680.0f, 0.01f, 100.0f);

_pIContext->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);
_pIContext->IASetIndexBuffer(_indexBuffer, DXGI_FORMAT_R16_UINT, 0);
_pIContext->VSSetConstantBuffers(0, 1, &_cbWorldBuffer);
_pIContext->VSSetConstantBuffers(1, 1, &_cbViewBuffer);
_pIContext->VSSetConstantBuffers(2, 1, &_cbProjBuffer);

```

And then for shader code, we've got...

```
cbuffer worldBuffer : register(b0) {
    matrix World;
    float t;
}

cbuffer viewBuffer : register(b1) {
    matrix View;
}

cbuffer projectionBuffer : register(b2) {
    matrix Projection;
}

PS_INPUT vs(float4 pos : POSITION, float4 col : COLOUR) {
    PS_INPUT output = (PS_INPUT)0;
    output.Pos = mul(pos, World);
    output.Pos = mul(pos, View);
    output.Pos = mul(pos, Projection);

    output.Colour = col;
    return output;
}

float4 ps(PS_INPUT input) : SV_TARGET{
    return input.Colour;
}

```

My gut tells me it's the projection matrix, although I've based this on another project I did, and comparing the code, I can't find out what I've done differently.

# Answer
> 0 votes
Your code overwrites `output.Pos` three times, so only the last write sticks. That last write was:

```
output.Pos = mul(pos, Projection);

```

Note that this is multiplying your *input* vertex position (in object space) by the projection matrix. So your resulting position depends only on the mesh and the projection, ignoring the object's world transformation and the camera's view.

It looks like you meant to write something more like this:

```
output.Pos = mul(pos, World);
output.Pos = mul(output.Pos, View);
output.Pos = mul(output.Pos, Projection);

```

Note that the input to the last two steps is the output from the previous step, so their work filters through to the final result.

But a more conventional solution would be to multiply these three matrices together on the CPU, and upload a single combined matrix to the GPU as one uniform variable or constant buffer entry: your `WorldViewProjection` matrix. Then in the shader you only need to do one matrix multiplication instead of chaining three dependent ones.

---
Tags: shaders, graphics, directx11, matrix, projection
---


# Question
Title: DivideByZeroException is only thrown in Mono builds, not in IL2CPP. Why?
I'm working on exception handling and I usually test it with causing a `DivideByZeroException`.

But this time **it's not thrown**. (While throwing a `System.Exception` works just like usual).

So I've created an **empty project** with only this script:

```
void Update()
{
    if (Input.GetKeyDown(KeyCode.L))
    {
        Debug.Log("L");
        var x = 0;
        var y = 1 / x;
    }
    if (Input.GetKeyDown(KeyCode.P))
    {
        Debug.Log("P");
        throw new System.Exception("test");
    }
}

```

And with the empty project the `DivideByZeroException` **is thrown**, so I had a look on the project configurations.

Turns out the new project's **Scripting Backend is Mono**.

Once I changed it from Mono to **IL2CPP**, the `DivideByZeroException` **is not thrown** in this project as well.

I experimented with changing the **API Compability Level**, but they **behave the same**.

So last time I debugged exception handling, I was on Mono and then I changed it ... I guess to make it faster or something.

My question is: **why is this the case?**

# Answer
As @user253751 pointed it out: **both variables get optimized out** because they are **not used**.

Yes, most likely that's the case. I added a line:

`gameObject.name = y.ToString()`

Now it **crashes** when I press L.

So yes, probably it was removed due to not being used.

It's still interesting **why does it crash instead of just throwing an exception.**
> 0 votes

---
Tags: unity, exceptions, mono, il2cpp
---


title: How are the unwrapped textures created?

text:
# Question
Title: How are the unwrapped textures created?
For many years really, I have been slowly learning game dev and asset creation (3d modelling etc). After much time, I am becoming reasonably skilled at modelling and writing code for games. However, making nice 3d art is still eluding me.

I can make the model. I can even unwrap it and create a UV Map image. But when I see other old commercial games they use a texture similar to this:

And I am wondering how is this created? To me, it even looks as if they have managed to unwrap an already textured model and turn it into this.

The only way I can think of is to draw it manually myself. But many examples I have seen in real games (and indie game projects), the textures look too good to have been made by hand. They literally look like they somehow unwrapped an existing model. But obviously at some point in time somebody had to make it from scratch, and I am wondering how this is done.

Any direct help on this matter would be massively appreciated. Thank you for reading.

# Answer
There are some dedicated software tools that allow you to paint a texture directly on a model. An example of this would be Substance Painter as you mentioned in the comments. Personally, I don't have a lot of experience with these tools as the didn't really mature until after I had pivoted away from dabbling at this sort of work, but I assume they've become popular because they can deliver results.

Alternatively, some 3d rendering packages provide some texture painting support. For instance, here's the documentation for texture painting in Blender.

For myself, I've used the following approach. First I like to use UV unwrapping to export an outline of the model's polys as mapped to a texture.

Next, I do some course painting in the 3d app. This might be as rough as flat color assignment to areas of the model. For example, make the general face area a skin tone & assign a hair color to polys in the hair area, etc. It looks like the options available now are much better than when I used to do this, so you might be able to go further with this step & put in more detail than I've described.

Next I'd use UV unwrapping to export the rough draft texture again.

A this point, I switch to an image editing program (Photoshop or the like). I import both of the exported images as layers into a new image. I then start making refinements to the rough texture. When needed, I use the outline layer to see where the polys are & how they're oriented. That layer is used as a reference to make sure I'm drawing with the grain of the model so to speak.

As I'm refining the model, if the hardware can keep up, I reload the work in progress texture back onto the model to look at it. If running both is too taxing, you might look for a stand alone model viewer for this part instead of using full 3d rendering app.

As I recall, the hardest parts were were textures needed to wrap across edges that were not adjacent in the UV unwrap. Drawing off the edge of one, followed by cutting, pasting & rotating was the best I came up with for a starting point, but usually I'd need to go back over it by hand. If there's any painting/texturing you can do directly in the 3d app for this, it can help a lot. For example a blob of color where you plan to draw a tattoo. Also I found it significantly easier to start with an existing initial texture & edit it rather than starting from scratch.

I myself found that there's a considerable but not impossible learning curve for this. I went with a route the allowed me to use my experience with tools I was already fluent with. I suspect that if it was something I had to do a lot of, it would be worth investing the time in learning to use a more direct set of tools.
> 3 votes

---
Tags: textures, uv-mapping, art, 3d-modeling, modelling-techniques
---


title: Zenject: Inject into monobehavior

text:
# Question
Title: Zenject: Inject into monobehavior
I want to start using zenject in my project but I encountered an issue. From their tutorial in github page I was able to inject non monobehavior objects into each other like this.

```
public class MyInstaller : MonoInstaller {
     public override void InstallBindings() {
         Container.Bind<string>().FromInstance("Hello World!");
         Container.Bind<Greeter>().AsSingle().NonLazy();
         Container.Bind<BasicArmorDamageCalculator>().AsSingle().NonLazy();
     }
}

public class Greeter {

    public Greeter(String message) {
        Debug.Log("this was injected: " + message);
    }
}

```

But the problem is that I cannot inject objects to Monobehavior classes. Using this Installer I tried to inject Greeter to monobehavior class like this

```
[Zenject.Inject]
public void Construct(Greeter greeter) {
    Debug.log(greeter);
}

```

And the greeter variable is null. As I understand I have to register my monobehavior class in the Installer class but It requires instantiating it while mono class is already on some game object.

What is the solution to this one?

Thanks in advance!

# Answer
In order to have dependencies injected into MonoBehaviours that were instantiated through `Instantiate()`, you need to change that to:

```
 diContainer.InstantiatePrefab()

```

where `diContainer` is injected through `[Inject]`. You don't need to create an instance of *Container*, you can simply inject it as it is already available from the box.
> 1 votes

---
Tags: unity, dependency-injection
---


# Question
Title: Perlin noise terrain generation around given road mesh
I am generating terrain around a route. The route already exists. I am using the Perlin Noise function implemented in Unity to generate terrain tiles that merge seamlessly. I generate the terrain tiles in the origin layer. From each terrain grid point I shoot a raycast to scan the street. I set the height values so that they are below the road (see picture 1 box without number). The terrain therefore adapts to the road

The problem, however, are roads with an elevation profile. For these, I save the highest road point within a terrain tile and add it to the height value of the respective tile. This allows me to arrange the tiles along the elevation profile of the road (image 2). Unfortunately, this height offset again breaks the seamlessly transitioning Perlin Noise. Is there a way to make the tiles merge seamlessly again after adding the offset?

So clearly the tiles surrounding the road sections with elevation profile are not supposed to be in the origin plane, but like the road elevation. I hope I have explained it reasonably well.

# Answer
> 1 votes
I found the solution myself! Thanks to everyone anyway! It wasn't that difficult.

For all those who are interested, here is the solution: You need functions that describe the height profile of the road. I implemented an example using two chained functions (shown with the linerenderer in white) and generated 3 seamless terrainchunks.

The heightmap generated with Perlin Noise from each chunk must be additively linked with the function of the road height profile. result = PerlinNoiseHeightMap\[x,z\] += RoadHeightFunction(x); This generates the PerlinNoise along the height profile as shown in the picture.

I hope it helps those who are interested.

---
Tags: procedural-generation, terrain, perlin-noise, heightmap
---