# Question
Title: Comparing angles and working out the difference
I want to compare angles and get an idea of the distance between them. For this application, I'm working in degrees, but it would also work for radians and grads. The problem with angles is that they depend on modular arithmetic, i.e. 0-360 degrees.

Say one angle is at 15 degrees and one is at 45. The difference is 30 degrees, and the 45 degree angle is greater than the 15 degree one.

But, this breaks down when you have, say, 345 degrees and 30 degrees. Although they compare properly, the difference between them is 315 degrees instead of the correct 45 degrees.

How can I solve this? I could write algorithmic code:

```
if(angle1 > angle2) delta_theta = 360 - angle2 - angle1;
else delta_theta = angle2 - angle1;

```

But I'd prefer a solution that avoids compares/branches, and relies entirely on arithmetic.

# Answer
> 46 votes
Here's my simplified, branchless, compare-free, no min/max version:

```
angle = 180 - abs(abs(a1 - a2) - 180);

```

Removed the modulo, as the inputs are sufficiently constrained (thanks to Martin for pointing that out).

Two abs, three subtracts.

# Answer
> 10 votes
> Although they compare properly, the difference between them is 315 degrees instead of the correct 45 degrees.

What makes you think 315 is incorrect? In one direction, it is 315 degrees, in the other direction, it's 45. You want to choose whichever is the smallest of the 2 possible angles and this seems to intrinsically require a conditional. You can't solve it with wrap-around arithmetic (ie. via modulus operator) because as you gradually increase one angle the angle between them grows until it hits 180 and then starts declining.

I think you either have to check both angles and decide which direction you want to measure, or calculate both directions and decide which result you want.

# Answer
> 6 votes
There's always the trick of doing both branches and letting the comparison result pick one:

```
delta_theta = (angle1 > angle2) * (360 - angle2 - angle1)
              + (angle2 > angle1) * (angle2 - angle1);

```

I don't know of a way to do it without *comparisons*, but usually the *branch* is what makes code slow and long, not the compare. At least in my opinion, this is more readable than Martin's answer (any good C programmer will recognize it as a branchless equivalent and see what it's doing), but also less efficient.

But like I said in my comment, branchless algorithms are good on processors with deep pipelines and bad prediction - a microcontroller usually has a tiny pipeline, and a desktop PC usually has good prediction, so unless you are targeting a gaming console, the branching version is likely best route if it reduces instruction count.

As always, profiling - which might be as simple as op-counting for your system - will give you the real answer.

# Answer
> 2 votes
Assuming *true* evaluates to -1 and *false* evaluates to 0, and '~', '&' and '|' are bitwise *not*, *and* and *or* operators respectively, and we're working with two's-complement arithmetic:

```
temp1 := angle1 > angle2
/* most processors can do this without a jump; for example, under the x86 family,
   it's the result of CMP; SETLE; SUB .., 1 instructions */
temp2 := angle1 - angle2
temp1 := (temp1 & temp2) | (~temp1 & -temp2)
/* in x86 again: only SUB, AND, OR, NOT and NEG are used, no jumps
   at this point, we have the positive difference between the angles in temp1;
   we can now do the same trick again */
temp2 := temp1 > 180
temp2 := (temp2 & temp1) | (~temp2 & (360 - temp1))
/* the result is in temp2 now */

```

# Answer
> 1 votes
What about this?

```
min( (a1-a2+360)%360, (a2-a1+360)%360 )

```

The addition of 360 is there in order to avoid negative differences, because a modulo of a negative number returns a negative result. Then you get the smaller of the two possible results.

There is still an implicit decision, but I don't know how to avoid it. Basically you compare the two angles by computing the difference clockwise or counterclockwise, and it seems that you explicitly want the smaller of these two differences. I don't know how to get that result without comparing them. That is, without using "abs", "min", "max" or some similar operator.

# Answer
> 1 votes
While your question made no reference of them, I'm going to be working on the assumption that your angle calculation question stems from wanting to know the minimum angle between two *vectors*.

That calculation is easy. Assuming A and B are your vectors:

`angle_between = acos( Dot( A.normalized, B.normalized ) )`

If you didn't have vectors and wanted to use this approach you could construct unit length vectors given your angles by doing `new Vector2( cos( angle ), sin ( angle ) )`.

# Answer
> 1 votes
Basically the same as JasonD's answer, except using bitwise operations instead of absolute value function.

**This is assuming you have 16-bit short integers!**

```
short angleBetween(short a,short b) {
    short x = a - b;
    short y = x >> 15;
    y = ((x + y) ^ y) - 180;
    return 180 - ((x + y) ^ y);
}

```

# Answer
> 1 votes
```
theta = ((destAngle - startAngle) + 180) % 360 - 180;

```

Will return a signed angle in the range of \[-180,180\] so that you can get rotational direction along with the smallest distance.

# Answer
> 1 votes
If we assume that you want the function work for any input angles (which could be outside the range of 0 to 360)...

```
a1 = a - floor(a/360)*360
b1 = b - floor(b/360)*360
diff = a1 - b1
diff_ab = (360 + diff) % 360
diff_ba = (360 - diff) % 360
smallest_diff = min(diff_ab, diff_ba)

```

If you're looking for extra performance, perhaps map the 0 to 2pi range to 0 to 2^n-1 so that you can use bitwise-AND masking operations instead of divide (/) and mod (%) operations.

# Answer
> 0 votes
I think

```
delta = (a2 + Math.ceil( -a2 / 360 ) * 360) - (a1 + Math.ceil( -a1 / 360 ) * 360);

```

# Answer
> 0 votes
Since you only care about eliminating branches and "complex" operations beyond arithmetic, I would recommend this:

`min(abs(angle1 - angle2), abs(angle2 - angle1))`

You still need an `abs` in there despite all angles being positive. Otherwise, the most negative result will always be chosen (and there will always be exactly one negative answer for positive, unique a and b when comparing a-b and b-a).

Note: This will not preserve direction between angle1 and angle2. Sometimes you need that for AI purposes.

This is similar to CeeJay's answer, but eliminates all modulos. I don't know what the cycle cost is of `abs`, but I'm gonna guess it's 1 or 2. Hard to say what the cost is of `min` as well. Maybe 3? So along with a 1 cycle per subtraction, this line should have a cost somewhere around 4 to 9.

# Answer
> 0 votes
Get the **smaller relative** angle in **signed**(+/-) form, from the perspective of **have** towards **want**:

* *at most* 180 degrees | PI radians
* -signed if anticlockwise
* +signed if clockwise

### Degrees

```
PITAU = 360 + 180 # for readablility
signed_diff = ( want - have + PITAU ) % 360 - 180

```

### Radians

```
PI = 3.14; TAU = 2*PI; PITAU = PI + TAU;
signed_diff = ( want - have + PITAU ) % TAU - PI

```

### Rationale

I came across this thread after I had figured this out, looking for a solution that avoids modulo; *so far I have found none*. This solution is for preserving the perspective sign, as @jacob-phillips asked this comment . There are cheaper solutions if you just need the shortest unsigned angle.

# Answer
> 0 votes
It's an old question but I ran into same case - had to get signed angular difference and preferably without branches and heavy math. This is what I ended up with:

```
int d = (a - b) + 180 + N * 360; // N = 1, 2 or more.
int r = (d / 360) * 360;
return (d - r) - 180;

```

The limitation is that 'b' should not have more than 'N' rotations compared to 'a'. If you can't ensure it and can allow extra operations then use this as first line:

```
int d = ((a % 360) - (b % 360)) + 540;

```

I got the idea from the 13th comment of this post: http://blog.lexique-du-net.com/index.php?post/Calculate-the-real-difference-between-two-angles-keeping-the-sign

# Answer
> -1 votes
i guess i could say

```
angle1=angle1%360;
angle2=angle2%360;
var distance = Math.abs(angle1-angle2);
//edited
if(distance>180)
  distance=360-distance;

```

ofcourse, considering the angle is measured in degrees.

---
Tags: mathematics, angles
---


# Question
Title: Scene Doesn't Change After Animation Complete
I'm encountering an issue in Godot 4 with my 2D character where the "Hurt" animation plays correctly when the character's health reaches 0, but the scene does not change as expected. Here's my code:

```
extends CharacterBody2D

const SPEED = 300.0
const JUMP_VELOCITY = -400.0

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var health = 10
var is_dead = false

@onready var anim = get_node("AnimationPlayer")
@onready var sprite = get_node("AnimatedSprite2D")

func _physics_process(delta):
    # Add the gravity.
    if !is_dead:
        if not is_on_floor():
            velocity.y += gravity * delta

        # Handle Jump.
        if Input.is_action_just_pressed("ui_accept") and is_on_floor():
            velocity.y = JUMP_VELOCITY
            anim.play("Jump")

        # Get the input direction and handle the movement/deceleration.
        # As good practice, you should replace UI actions with custom gameplay actions.
        var direction = Input.get_axis("ui_left", "ui_right")
        if direction == -1:
            sprite.flip_h = true
        elif direction == 1:
            sprite.flip_h = false

        if direction:
            velocity.x = direction * SPEED
            if velocity.y == 0:
                anim.play("Run")
        else:
            velocity.x = move_toward(velocity.x, 0, SPEED)
            if velocity.y == 0:
                anim.play("Idle")

        if velocity.y > 0:
            anim.play("Fall")
        move_and_slide()

    if health <= 0 and !is_dead:
        sprite.play("Hurt")
        is_dead = true
        print("Enter")
        await sprite.animation_finished
        print("Finish")
        queue_free()
        get_tree().change_scene_to_file("res://main.tscn")

```

# Answer
> 2 votes
If this part of the code is not running:

```
print("Finish")
queue_free()
get_tree().change_scene_to_file("res://main.tscn")

```

We conclude that the preceding line never returns:

```
await sprite.animation_finished

```

Which means that the `AnimatedSprite2D` never reports the animation as finished.

If the animation started (which you say it did), that means it never finished. Which would be the case if the animation is looping.

Thus: modify the animation to not loop, so it can finish, and the exaction flow can continue.

---
Tags: godot, gdscript, godot-4
---


# Question
Title: For Google Play, what kinds documentation can I provide to prove I have permission to use a third party's music in my game?
I'm working on an indie rhythm game for Android that uses pre-existing music. We got the OK from the original artist to use said music on the condition that we release the game for free. However, Google Play documentation -- specifically here: Play Console Help - Intellectual Property -- recommends that we submit "written documentation" proving we have permission to use the artist's intellectual property in order to help prevent copyright strikes.

However, I don't know what form this documentation should take. For example, will Google accept an email exchange between us and the artist wherein they state that we have permission to use their music, or do we need something more "official" like a signed permission letter?

I reached out to Google Play support via this link (Play Console Help - Contact Us) to ask about the types of documents they'd accept, but the representative only said, "Unfortunately, I'm not able to confirm if the receipts of the conversation via email are enough. If you think your app is compliant, you may try to send your app for review."

The advice I'm seeing on other forums so far is to speak with a lawyer just to be safe. I think this is good advice and I'm taking steps to do so. However, I wanted to ask around in case anyone had been in a similar situation before and knew what sort of documentation Google Play might accept.

Thank you in advance!

# Answer
> 7 votes
Ideally you should have some manner of legally binding contract between you and your artist & I would expect that would satisfy their documentation requirements. As a somewhat related topic, you might also want to see another answer I posted that touches on secondary infringement.

If you don't have a contract, I would strongly recommend that you get one. A good contract works to the benefit of both sides, putting everyone on the same page, spelling out the mutual obligations of both parties. While emails could be submitted as evidence in the event that one party brings a dispute against the other, I would expect that such evidence wouldn't carry as much weight as a signed contract.

I'm not a lawyer, this is not legal advice and situations vary by jurisdiction. You've already been advised to consult an actual lawyer & I would agree that's a far safer basis for making business decisions than relying on the wisdom of internet strangers - after all we aren't contractually obligated to give you good advise ;)

---
Tags: android, legal, copyright, google-play, publishing
---


# Question
Title: Why can't I press buttons after re-enabling the UIDocument?
I have this UI with buttons that should be clickable whenever the UIDocument is enabled, but for some reason whenever I disable and then re-enable the UIDocument (in the second code block), the buttons are no longer clickable even though the UI shows up. This is the UI code:

```
public class UI : MonoBehaviour
{
    public BattleSystem battleSystem;
    void Start(){
        VisualElement root = GetComponent<UIDocument>().rootVisualElement;

        Button grenadeButton = root.Q<Button>("Grenade");
        Button pistolButton = root.Q<Button>("Pistol");

        grenadeButton.clicked += () => StartCoroutine(battleSystem.useWeapon(Weapon.GRENADE));
        pistolButton.clicked += () => StartCoroutine(battleSystem.useWeapon(Weapon.PISTOL));
    }
}

```

And this is the code in the BattleSystem class:

```
public IEnumerator useWeapon(Weapon weapon){
        Debug.Log("Button was pressed");
        StopCoroutine(turn); // stops the takeTurn Coroutine
        switch (weapon){
            case Weapon.GRENADE:
                yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Space));
                Debug.Log("Powering Grenade");
                yield return new WaitUntil(() => !Input.GetKey(KeyCode.Space));
                Debug.Log("Grenade thrown");
                break;
            case Weapon.PISTOL:
                yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Space));
                Debug.Log("Pistol fired");
                break;
        }
        yield return new WaitUntil(() => Input.GetKeyDown(weaponsKey));
        yield return new WaitUntil(() => !Input.GetKey(weaponsKey));
        StartCoroutine(takeTurn(currentPlayer));
    }
IEnumerator takeTurn(GameObject player){
        currentPlayer = player;
        LoadCameraToPlayer(currentPlayer);
        currentPlayer.GetComponent<PlayerMovement>().enabled = true;
        BattleState currentState = state;
        while (state == currentState){
            yield return new WaitUntil(keyPress);
            switch (pressedKey){
                case var v when v == passKey:
                    StartCoroutine(TurnEnd()); // changes state to break out of loop
                    break;
                case var v when v == weaponsKey:
                    yield return new WaitUntil(() => !Input.GetKey(weaponsKey));
                    updateWeaponUIState(!weaponWheel.GetComponent<UIDocument>().enabled); // turn on/off weapon UI upon pressing and releasing the weapons key
                    currentPlayer.GetComponent<PlayerMovement>().enabled = !weaponWheel.GetComponent<UIDocument>().enabled; // player movement
                    break;
            }
        }
    }
    void updateWeaponUIState(bool active){
        weaponWheel.GetComponent<UIDocument>().enabled = active;
        UnityEngine.Cursor.visible = active;
        if (active){
            UnityEngine.Cursor.lockState = CursorLockMode.Confined;
        } else{
            UnityEngine.Cursor.lockState = CursorLockMode.Locked;
        }
        tpc.enabled = !active; //ThirdPersonCamera
        cfl.enabled = !active; //CinemaFreeLook
    }

```

The buttons in the UI class work when I first enable the UIDocument (it starts disabled) but not after disabling and re-enabling it. Things I've tried:

* Removing and adding the listeners back onto the buttons with OnEnable/OnDisable - I don't think you can remove listeners in UIElements so that doesn't work, but I think Start() should be best
* Disabling the UIDocument GameObject instead of the Component - made no difference
* Stopping (and not stopping) the takeTurn Coroutine before starting the useWeapon Coroutine. I thought maybe running two related coroutines simultaneously was the problem, it wasn't

Does anyone have any clue what the issue could be?

# Answer
> 0 votes
This person figured it out, had to change the display mode instead of enable/disable, https://forum.unity.com/threads/why-cant-i-press-this-button-after-re-enabling-the-ui.1505888/

---
Tags: unity, c#, input, unity-ui
---


title: Untraceable exception in XAudio dll

text:
# Question
Title: Untraceable exception in XAudio dll
I'm developing a game using OpenGL and XAudio 2.9. For some reason I am getting an exception in release builds inside the XAudio dll. Here is the exception :

Exception thrown at 0x00007FFBB5416EF1 (XAudio2\_9.dll) in Eclipse.exe: 0xC0000005: Access violation reading location 0x000002AE0FF1B8A8.

I've tried everything from zeroing memory before assigning something to it to initializing all properties to an initial value (since in the debug version I never have crashes). I'm also using mutexes for multithreading safety...

Anyone that has faced something similar and how did you solve it?

Code:

```
SoundSystem::SoundSystem()
{
    UINT32 flags = 0;
#if defined _DEBUG || defined NDEBUG
    flags |= XAUDIO2_DEBUG_ENGINE;
#endif
    DXCall(CoInitialize(nullptr));
    DXCall(XAudio2Create(&pEngine, flags));
#if defined _DEBUG || defined NDEBUG
    pEngine->SetDebugConfiguration(
        new XAUDIO2_DEBUG_CONFIGURATION
        {
            XAUDIO2_LOG_ERRORS | XAUDIO2_LOG_WARNINGS | XAUDIO2_LOG_INFO,
            XAUDIO2_LOG_ERRORS | XAUDIO2_LOG_WARNINGS,
            true, true, true, true
        }
    );
#endif
    assert(pEngine);
    DXCall(pEngine->CreateMasteringVoice(&pMaster, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE));
    assert(pMaster);
    DWORD dwChannelMask;
    DXCall(pMaster->GetChannelMask(&dwChannelMask));
    DXCall(X3DAudioInitialize(dwChannelMask, X3DAUDIO_SPEED_OF_SOUND, X3DInstance));
    assert(X3DInstance);
    std::this_thread::sleep_for(std::chrono::duration<float, std::milli>(1000.f));
    ZeroMemory(&mListener, sizeof(X3DAUDIO_LISTENER));
    mListener.pCone = (X3DAUDIO_CONE*)&Listener_DirectionalCone;
}

```

Here is the play sound buffer method

```
void SoundSystem::PlaySoundBuffer(std::shared_ptr<Sound>& s, uint32_t loop)
{
const std::lock_guard lock(mMutex);

if (activeChannelSoundPtrs.size() > 180) return;

s->PlaySoundEffect(loop);

auto it = std::find_if(idleChannelSoundPtrs.begin(), idleChannelSoundPtrs.end(),
    [&s](const std::unique_ptr<ChannelSound>& pChan) -> bool
    {
        auto& f1 = pChan->GetFormat();
        auto& f2 = s->GetFormat();

        return
            (f1.nChannels == f2.nChannels
                && f1.wBitsPerSample == f2.wBitsPerSample
                && f1.nAvgBytesPerSec == f2.nAvgBytesPerSec
                && f1.nSamplesPerSec == f2.nSamplesPerSec
                && f1.wFormatTag == f2.wFormatTag
                && f1.cbSize == f2.cbSize
                && f1.nBlockAlign == f2.nBlockAlign);
    }
);

if (it == idleChannelSoundPtrs.end()) {
    activeChannelSoundPtrs.push_back(std::make_unique<ChannelSound>(*this, s->GetFormat()));
    activeChannelSoundPtrs.back()->PlaySoundEffect(s, loop);
}
else
{
    activeChannelSoundPtrs.push_back(std::move(*it));
    idleChannelSoundPtrs.erase(it);
    activeChannelSoundPtrs.back()->PlaySoundEffect(s, loop);
}
}

```

Here is the sound buffer on buffer end method:

```
__declspec(nothrow) void __stdcall SoundSystem::ChannelSound::VoiceCallback::OnBufferEnd(void* pBufferContext)
{
const std::lock_guard lock(SoundSystem::Get().mMutex);

ChannelSound& chan = *(ChannelSound*)pBufferContext;
if (chan.pSound) {
    chan.Stop();
    chan.pSound->RemoveChannel(chan);
    chan.pSound.reset();
    DXCall(chan.pSource->SetVolume(1.f));
    DXCall(chan.pSource->SetFrequencyRatio(1.f));
    chan.xaBuffer.LoopCount = 0;
    SoundSystem::Get().DeactivateChannelSound(chan);
}
}

```

And here is the update method that is called once per frame from the main thread

```
void SoundSystem::Update()
{
const std::lock_guard lock(mMutex);

XAUDIO2_VOICE_DETAILS details{};
ZeroMemory(&details, sizeof(XAUDIO2_VOICE_DETAILS));
pMaster->GetVoiceDetails(&details);

for (auto& channel : activeChannelSoundPtrs) {
    assert(channel);
    assert(channel->pSound);

    X3DAUDIO_DSP_SETTINGS DSPSettings{};
    ZeroMemory(&DSPSettings, sizeof(X3DAUDIO_DSP_SETTINGS));
    std::unique_ptr<FLOAT32[]> matrix = std::make_unique<FLOAT32[]>(channel->pSound->mFormat.nChannels * details.InputChannels);
    ZeroMemory(matrix.get(), channel->pSound->mFormat.nChannels * details.InputChannels * sizeof(FLOAT32));
    DSPSettings.SrcChannelCount = channel->pSound->mFormat.nChannels;
    DSPSettings.DstChannelCount = details.InputChannels;
    DSPSettings.pMatrixCoefficients = matrix.get();
    DSPSettings.pDelayTimes = nullptr;

    X3DAudioCalculate(
        X3DInstance, &mListener, &channel->pSound->Emitter,
        X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_DOPPLER | X3DAUDIO_CALCULATE_LPF_DIRECT,
        &DSPSettings);

    // Apply X3DAudio generated DSP settings to XAudio2
    DXCall(channel->pSource->SetFrequencyRatio(DSPSettings.DopplerFactor * channel->pSound->mPitch));
    DXCall(channel->pSource->SetOutputMatrix(pMaster, DSPSettings.SrcChannelCount, DSPSettings.DstChannelCount, DSPSettings.pMatrixCoefficients));
    XAUDIO2_FILTER_PARAMETERS FilterParametersDirect = {
        LowPassFilter, // Filter type (e.g., low-pass)
        2.0f * sinf(X3DAUDIO_PI / 6.0f * DSPSettings.LPFDirectCoefficient), // Cutoff frequency
        1.0f // Resonance or other filter parameters
    };
    DXCall(channel->pSource->SetOutputFilterParameters(pMaster, &FilterParametersDirect));
}

if (mMixToBattle && mBattleMusic && mBGM) {
    if (mBGMVolume > 0.f) {
        if (!mBattleMusic->IsPlaying() || mBattleMusic->GetQueuedBuffers() == 0) {
            PlayMusicStream(mBattleMusic, true);
        }
        mBGMVolume -= TimeManager::GetInstance()->DeltaTimeF();
        mBattleVolume += TimeManager::GetInstance()->DeltaTimeF();

        mBGMVolume = glm::clamp(mBGMVolume, 0.f, 1.f);
        mBattleVolume = glm::clamp(mBattleVolume, 0.f, 1.f);

        if (mBGMVolume <= 0.f) {
            mMixToBattle = false;
            mBGM->Stop();
        }
        else {
            mBGM->SetVolume(mBGMVolume);
            mBattleMusic->SetVolume(mBattleVolume);
        }
    }
}
if (mMixToBGM && mBattleMusic && mBGM) {
    if (mBattleVolume > 0.f) {
        if (!mBGM->IsPlaying() || mBGM->GetQueuedBuffers() == 0) {
            PlayMusicStream(mBGM, true);
        }
        mBattleVolume -= TimeManager::GetInstance()->DeltaTimeF();
        mBGMVolume += TimeManager::GetInstance()->DeltaTimeF();

        mBGMVolume = glm::clamp(mBGMVolume, 0.f, 1.f);
        mBattleVolume = glm::clamp(mBattleVolume, 0.f, 1.f);

        if (mBattleVolume <= 0.f) {
            mMixToBGM = false;
            mBattleMusic->Stop();
        }
        else {
            mBattleMusic->SetVolume(mBattleVolume);
            mBGM->SetVolume(mBGMVolume);
        }
    }
}
}

```

If I remove the update code the game does not crash. I omitted the code for the streaming music part. Let me know if you need to see that too as it is a lot of code for it.

Also after getting the pdbs from the windows servers I was able to get a call stack if it is useful to someone:

# Answer
> 0 votes
The top of the call stack is `ResampleLinearFroMin16MonoSse2()`, and it's crashed reading a non-null memory address. That address is only 8-byte aligned, so it's probably not the start of a memory allocation.

I'd guess that that function would be reading one of your buffers full of 16-bit mono samples and is re-sampling them.

I'm guessing that you might have deleted the data that it's in the middle of playing. As a simple test you could try just commenting out all of the code that deletes them. You could also try logging all XAudio related memory allocations and frees.

---
Tags: c++, xaudio2
---


# Question
Title: How do I create a backward selection code?
Here is the code for my forward selection:

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

public class CustomizeModels : MonoBehaviour
{   public GameObject[] outfits;
    private int currentOutfit;

    void Start()
    {
        currentOutfit = 0;
    }

    void Update()
    {
        for (int i = 0; i < outfits.Length; i++)
        {
            if (i == currentOutfit)
            {
                outfits[i].SetActive(true);
            }
            else
            {
                outfits[i].SetActive(false);
            }
        }
    }

    public void SwitchOutfits()
    {
        if (currentOutfit == outfits.Length - 1)
        {
            currentOutfit = 1;
        }
        else
        {
            currentOutfit++;
        }
    }

}

```

How do I create a backward selection?

# Answer
> 1 votes
Your `SwitchOutfits()` method skips the first and last element of the array. The following code does not.

Here is the commented refactored code:

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

public class CustomizeModels : MonoBehaviour
{
    public GameObject[] outfits;
    private int currentOutfit;
    private int previousOutfit;

    void Start()
    {
        currentOutfit = 0;
        previousOutfit = 0;
        outfits[currentOutfit].SetActive(true); // set initial active
        // active should be false on all `outfit`s during creation
    }

    void Update()
    {
        if(currentOutfit == previousOutfit)
            return; // shortcut exit if there is no change

        outfits[previousOutfit].SetActive(false);
        outfits[currentOutfit].SetActive(true);
        previousOutfit = currentOutfit;
    }

    public void SwitchOutfits(int direction = 1) // use -1 for reverse
    {
        currentOutfit += direction;
        if (currentOutfit < 0 || currentOutfit >= outfits.Length)
            currentOutfit = (currentOutfit + outfits.Length) % outfits.Length;
        // The addition handles the negative case: outfits.Length + (-1) = outfits.Length - 1
        // The mod then shifts the value between 0 and outfits.Length - 1
    }
}

```

If you prefer the use of `if`s instead of the mod `%`:

```

    public void SwitchOutfits(int direction = 1) // use -1 for reverse
    {
        currentOutfit += direction;

        if (currentOutfit == outfits.Length)
        {
            currentOutfit = 0;
        }
        else
        {
            if (currentOutfit == -1)
            {
                currentOutfit = outfits.Length - 1;
            }
        }
    }

```

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


# Question
Title: Client and server with fixed tick in pygame
I'm trying to write a 2D RTS game with maximum of 10 players. When server finish intializing each player receives start coordinates and game start time so each client will start processing ticks around the same time. When player moves he sends client tick with his position and direction to server. When server receives player movement it checks client's tick in packet. I don't know what to do in this types of scenarios:

1. If client is ahead. Should I update current server state to the client tick? Should I allow client to be ahead?
2. if client tick is the same as server I just check his data. If its correct I send it to the other players so they can simulate. What to do if it is different? Should I check if in range of previous states(tick - x, tick) data matches? Should I reconcile or just send to player "NO your are here and moving in this direction"
3. What reconciliation actually means? Do I understand it correctly that I roll back to the state where player's data matches and then apply new input and recalculate to the current server tick?

My server and client loop looks almost the same:

```
    def run(self):

        while True:
            self.tickClock.tick(16)
            while not self.inqueue.empty():
                uuid, msg_type, msg_data = self.inqueue.get()
                self.handle_msg(uuid, msg_type, msg_data)
            self.apply_players_state(self.tick)
            self.player_group.update(self.tick)
            self.players_state_next(self.tick+2)
            self.tick += 1

```

I use `pygame.clock.Clock()` for fixed tick. `self.inqueue` is multiprocessing.Queue with received packets I want to process. In `handle_msg` I check type of packet and run corresponding function. For now it's just movement where I check the ticks and if coordinates match if so I update player's state for tick. `apply_players_state()` is used to make sure that player gets his rect and direction updated from map of states for current server tick. `player_group.update()` is just a `pygame.sprite.Group` where I move player based on his actuall coordinates and direction. `player_state_next()` is used to create a new item for each player for the tick given so I don't get `keyError`.

# Answer
This is not a simple question to answer. Many papers have been written on the subjects at hand, and this answer can only address certain aspects. Please forgive my incompleteness.

Network delays round-trip-time(RTT) and propagation can be inconsistent.

## Is cheating a concern?

If so, the server is the absolute authority and its position is the absolute truth and sent back to the client.

If not, validate the difference is possible, and then average the client and server positions, updating both with timing offsets.

## RTS is unique in its timing requirements

Commands are issued rather slowly(in computer timing terms) and the results are not needed in absolute real-time.

Slow the server down to tick to say, 3-7 times per second, apply all of the enqueued commands in order, then run the actual tick repeatedly until it catches up to real-time, sending the data to the clients. This will give the client a position target adjustment close to the expected value.

This would require two server queue variables. One collecting, while the other replays.

The advantage is that all clients would experience the similar input delays (\***1**), 333.3 - 142.85 ms, while maintaining the real-time consistency across the clients.

The client side should queue and send requests at 2 - 3 times the processing rate. This will give time to fill the request buffer, and also further offset the phase and delay values.

## Use TCP for input.

The target payload size is up to ~1000 bytes per packet.

For most game networking, I suggest using UDP, not in this case.

In this application, use TCP, also called reliable, as the transport method, if possible.

Given the slower update times, the reordering and retry delays associated with TCP, far outweigh the possibility of loss or mis-ordering of commands.

UDP responses are fine, just as long as they are given regularly.

---

***1**: There is a phase offset error inherent in this fixed timing model that still disadvantages slower connections, but it minimizes the impact by guaranteeing the slower client a response chance within the same or next server tick.
> 0 votes

---
Tags: pygame, client-server, rts
---


title: Move player at godot4

text:
# Question
Title: Move player at godot4
I designed a character that has 4 walking modes for godot4. I saved the picture in PNG format.

I enter it into the animation section. When I set the keyframes and play, in addition to playing the animation, the position of the character in the X direction is also changed. I checked that the position of the character does not change in the settings, but the character moves in the X direction when playing. How can I keep the position of the character fixed so that it does not move in an animation?

# Answer
> 1 votes
Do you have sprites that are of different sizes for the animation? That might be the cause of the problem. If so, making them the same size would solve the problem.

Alternatively, you could change the `offset` of your sprite to compensate for the apparent movement.

---
Tags: animation, godot, godot-4
---


title: Detecting collisions with trajectories

text:
# Question
Title: Detecting collisions with trajectories
What if an object were to have collision detection implemented as so: A ray in the direction the object is moving in, and a ray in the direction of gravity.

# Answer
> 1 votes
Usually objects are not simply points, and by that I mean that usually objects have size. If you only rays to check for collisions, the size of the object is not being taken into account.

Which means that - regardless of how big the object is - it might fall through a crack in floor or similar... How are you representing the floor anyway? You are going to need to define collision shapes one way or another.

*I cannot read your mind, but I'll venture to guess you are trying to find some way avoid tunneling… In which case, I'd suggest to look into how continuous collision detection works.*

# Answer
> 1 votes
There is a trick to use zero sized rays to check collision between two non zero sized objects: You just sum their radiuses. This way when a ray is cast, it will hit larger obstacle, even if it would've missed it at the edge for normal sized obstacle. Only works for a simple shape, sphere. But can be used as a crude first step, and fine details of the collision can be checked later. Or if your physics is simple enough to use spheres as a object's physical model.

---
Tags: collision-detection, physics, raycasting, trajectory
---


# Question
Title: How to check if a point is on the navmesh?
How do I know if a node is in within a navigation rectangle? I am working on an enemy spawner that puts enemies off screen but I need to pick positions where the enemies will actually work (read: on a navigation area).

*(Originally asked on Discord.)*

# Answer
> 2 votes
I'd find the closest point (`NavigationServer3D.map_get_closest_point()`) and check the distance between them. If it's on the map, the distance would be approximately zero.

Also, that likely gives you a valid spawn position. You could also push in away from original point to spawn away from area edge!

Something like this:

```
func get_point_on_map(target_point: Vector3, min_dist_from_edge: float) -> Vector3:
    var map := get_world_3d().navigation_map
    var closest_point := NavigationServer3D.map_get_closest_point(map, target_point)
    var delta := closest_point - target_point
    var is_on_map = delta.is_zero_approx()  # Answer to original question!
    if not is_on_map and min_dist_from_edge > 0:
        # Wasn't on the map, so push in from edge. If you have thin sections on
        # your navmesh, this could push it back off the navmesh!
        delta = delta.normalized()
        closest_point += delta * min_dist_from_edge
    return closest_point

```

Something similar should also work for 2D.

You could probably also get the nav mesh polygons and do an inside polygon test, but that's probably slower and more hassle.

---
Tags: godot, navmesh, godot-4
---


# Question
Title: Raycast suspension simulation rebounds car on landing
I'm expecting the car to land and engage the suspension to dampen the landing. The code I'm using currently has this effect:

```
# vehicle.gd
extends RigidBody3D

# Suspension variables
@export var suspension_rest_length: float = 0.5
@export var suspension_max_length: float = 1.0
@export var suspension_stiffness: float = 500.0
@export var dampening_sensitivity: float = 450.0
@export var dampening_max: float = 30.0

# Suspension Raycasts
@onready var fr: RayCast3D = $FR
@onready var fl: RayCast3D = $FL
@onready var rr: RayCast3D = $RR
@onready var rl: RayCast3D = $RL

# Wheel nodes
@onready var fr_wheel: Marker3D = $FR/Wheel
@onready var fl_wheel: Marker3D = $FL/Wheel
@onready var rr_wheel: Marker3D = $RR/Wheel
@onready var rl_wheel: Marker3D = $RL/Wheel

func _physics_process(delta):
    if fr.is_colliding():
        # Get distance to ground
        var dist = fr.get_collision_point().distance_to(fr.global_transform.origin)

        # Get dampening, clamp between 0 and max dampening
        var dampening = clamp(fr_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)

        # At location of raycast, apply suspension forces
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), fr.global_transform.basis.y)

        # Set location of wheel to raycast collision point
        fr_wheel.global_transform.origin = fr.get_collision_point()

    if fl.is_colliding():
        var dist = fl.get_collision_point().distance_to(fl.global_transform.origin)
        var dampening = clamp(fl_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), fl.global_transform.basis.y)
        fl_wheel.global_transform.origin = fl.get_collision_point()

    if rr.is_colliding():
        var dist = rr.get_collision_point().distance_to(rr.global_transform.origin)
        var dampening = clamp(rr_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), rr.global_transform.basis.y)
        rr_wheel.global_transform.origin = rr.get_collision_point()

    if rl.is_colliding():
        var dist = rl.get_collision_point().distance_to(rl.global_transform.origin)
        var dampening = clamp(rl_wheel.get_velocity().length() * dampening_sensitivity, 0, dampening_max)
        self.apply_force(Vector3.UP * (suspension_stiffness * (dist - suspension_rest_length) + dampening), rl.global_transform.basis.y)
        rl_wheel.global_transform.origin = rl.get_collision_point()

```

# Answer
Three issues:

1. `suspension_stiffness` is 500 which seems like a very large massive force to apply. (Maybe the car is so heavy that this level is necessary?)
2. Assuming your RayCast3D are casting below the wheel's neutral contact point, checking `fl.is_colliding()` means when the wheels are on the ground, they are applying the upward force. So the car will never want to rest on the ground.
3. An upward "dampening" force is applied whenever the wheels are moving (in any direction).

Adjust your RayCast3D so they end their cast just above the lowest acceptable position for the wheel.

Step through your code and see what kinds of force values you're getting. Use a local variable so you can easily see the force strength:

```
var force_magnitude = suspension_stiffness * (dist - suspension_rest_length) + dampening
self.apply_force(Vector3.UP * force_magnitude, fl.global_transform.basis.y)

```

Try removing the damping component of the force so it can sometimes be zero. You may need to omit the call to `apply_force` if the total force is zero.

Try using a CSGSphere3D and changing its colour to indicate different states in your code to make it easier to see what's going on (or use the godot\_debug\_draw\_3d plugin). You can also draw debug text and record your screen so you can scrub back and forth to see what's happening.
> 0 votes

---
Tags: physics, 3d, godot, raycasting, godot-4
---


# Question
Title: How to Y-Sort a multi-tile entity as a single tile?
I am trying to use Y-Sorting on a tilemap tree to Y-Sort the whole tree, but it is Y-Sorting each tile of the tree instead of the tree as a whole:

I have tried adjusting the Y-Sort Origin but that didn't work. I am trying to make the tree render completely over the Character when he's behind and below when he's in front.

# Answer
You should be able to adjust the Y-Sort Origin of the top tiles to be at the same y position as the bottom tiles. That way all four tiles will get y sorted the same and behave the same relative to the player.

So if your tiles are 64px tall, then set Y-Sort Origin for the top to be -32 and the bottom two to be 0.

(You mentioned adjusting the Y-Sort Origin, but it's not clear *what* didn't work. Hopefully this is helpful.)
> 0 votes

---
Tags: godot, gdscript, godot-4
---


# Question
Title: Optimal position detection for character
In a classic fighting game like Mortal Kombat, character A is on the left facing right and character B is on the right facing left.

At some point the characters can swap positions and hence where they're facing to.

How could I detect this new positions on the characters?

I don't want to be constantly checking `if(A.x > B.x + B.width)` and I'm guessing is not what video games are doing. So what is the optimal way to detect a swap?

# Answer
> 2 votes
Keep it simple.

You are asking for premature optimization, which is a good way to overengineer your game.

In general overengineering happens when trying to satisfy some fictitious requirements (in this case that would be that you don't want to check every frame because reasons, but that is not a function of your game, and as long as it can run correctly it isn't a restriction either).

---

To answer the question as written: You don't have to check every frame. If you have the conditional, you only need to change when the involved variables change.

In your case you only need to check `if(A.x > B.x + B.width)` when the first character move, or when the second character moves (or when the second character changes width).

And we could come up with a mechanism to react to changes to those values (anything from a dirty flag to an observer pattern).

---

**If these changes are frequent** (i.e. the characters are moving most frames, which would be the case on a fighting game), then said mechanism is added overhead compared to checking every frame.

*It is even worse if the change can happen many times per frame.*

---

**If these changes are infrequent** (which is unexpected for a fighting game), then you can have said mechanism to react to one of the variables changing by performing the comparison...

And then the question is: Can perform the required update (flip the characters) right away?

* If you can't, you would have to set a flag to be check every frame... So you would still have an `if` every frame anyway. Making this effort not worth doing.
* If you can, go ahead, and measure and compare the performance against checking every frame. Even if it more performant, you have the drawback that you are making the code harder to reason about, which might mean harder to maintain.

---

*We have restricted the cases where the optimization might be useful to when the change to the variables is infrequent, and the update can be performed right away.*

Yet, I do not know if the optimization even worth doing. So, how do we find out? We fuck around experiment.

First, We know that checking every frame works. Thus make that your initial implementation. *You can call it a "reference implementation", and use it as base line for the correct behavior and performance.*

Next, if testing that initial implementation you find that is has bad performance, you can run it in a profiler. The profiler will tell you where your code is expending more time.

I cannot tell for sure if the check will show up as a performance problem in your profiler. You have to do the experiment.

Yet, usually bad performance comes from some asynchronous operation your code is waiting on (probably some IO), or some CPU intensive computation (probably something you are doing many times each frame).

Thus: I do not expect `if(A.x > B.x + B.width)` to be a performance problem. *If it turns out to be, then you will have quite a question to ask, and more information on what is going on.*

*To be completely honest, I struggle to imagine why this might be a performance problem (I'd be open to find out), or how it could be optimized (I'd hope that if have a real case, we would also have the information to figure it out).*

---

Be aware that we are talking about two characters in a fighting game. This is not a problem of a naïve approach scaling poorly, because this does not have to scale.

If it needs to scale, we need to define how the behavior must scale beyond two character. But to avoid getting into that, and making this answer longer, I'll limit myself to mention a couple tools we would use to optimize this for thousands of characters: space partitioning and flow fields. *I'll also mention that we would want to move some of the code to the GPU.*

Thankfully, this is not the problem at hand.

---

Thus: Keep it simple. And don't get ahead of yourself.

---
Tags: fighting-game, position
---


# Question
Title: How do I prevent camera jitter when rotating the player?
This is a problem that seems to have no reasonable answer anywhere around, yet is a commonly needed aspect of developing game mechanics.

---

**Context**

I'm developing a traditional 3rd person character controller esque thing, you know, camera controlled by mouse/joystick all that jazz.

The issue comes when I'm developing a climbing system:

* I have to develop a climbing system, and when I 'attach' the player to a climbing ledge, they could be at any angle relative to this ledge, up to perpendicular.
* When the player jumps up, and the ledge detection runs, the player attaches to the ledge, and needs to rotate to be facing the ledge dead on.
* I need a method for the camera movement to be completely independent of this capsule collider rotation change, as currently I have this problem:...

---

**Problem**

When I rotate my player's capsule collider, the attached camera boom rotates with it.

---

**Specific Problem**

When I set my actor's rotation directly, the camera orients itself immediately with the player's direction, then immediately returns itself to the previous view, creating a massive camera jitter, especially at lower framerates.

---

**The question**

How do I prevent this behaviour

OR

How do I reapproach problems of rotating the player character?

# Answer
> 1 votes
I've had the same problem, and as @natalo77 said in the comments, switching to absolute rotation did the trick.

You need to select the parent of your camera (the camera boom), then in the transform, for the rotation, select "absolute rotation" for the rotation instead of "relative".

I kept the position vector at "location" so that the camera moves with the player.

then I guess you can use the "look at" function bewteew the camera and capsule to keep the player at the center of the screen.

---
Tags: mathematics, camera, rotation, movement, unreal-4
---


# Question
Title: Check if OpenVR / SteamVR / OculusVR headset is mounted on your head
The Oculus and the Vive have this light proximity sensor that detects whether you have your VR headset placed on your head currently or not.

Is there any way to tap into that for our own game checks? E.g. We could pause or restart the game depending on whether the headset's being worn or not.

I'm using Unity/C#, but any (driver / API level) help is much appreciated.

# Answer
The SteamVR input has recently changed completely, it now uses Actions and here is a step by step tutorial from valve on how to set it up.

Here's one of the (best) ways to poll it in code:

```
    void Update(){

    //NOTE: I could have used one-off events. But I used these constant Update() polls instead because if the VR Dashboard is on while the headset is taken off or put on,
    //then the OnDown and OnUp events get eaten by the dashboard and will never reach this code in unity. (github issue here: https://github.com/ValveSoftware/openvr/issues/628)

    // m_inputSourceDevice needs to be Any - there's no entry for "Headset", but the headset's sensors are reported under the Any "hand".
    SteamVR_Input_Sources m_inputSourceDevice = SteamVR_Input_Sources.Any;

    if(!m_isHeadsetOn && SteamVR_Input._default.inActions.Proximity_Sensor.GetState(m_inputSourceDevice)){
            Debug.Log("Headset On.");
            HeadsetOn();
    }
    else if(m_isHeadsetOn && !SteamVR_Input._default.inActions.Proximity_Sensor.GetState(m_inputSourceDevice)){
        Debug.Log("Headset Off (cancellable)");
        StartCoroutine(HeadsetOff());
    }

}

```

Note that as of right now, there is a bug that prevents you from using SteamVR to assign the Proximity Sensor to an action if you have a HTC Vive or Vive Pro, even though ironically it works as intended if you're using it with an Oculus headset. There is an easy fix on this steamvr github issues page.

Also note that even though the builtin unity OpenVR usually implements what SteamVR comes up with, for now it does not let you access the proximity sensor. The only thing you can do with OpenVR is to check the `EDeviceActivityLevel` as MichaelHouse explained in his answer. However that is useless because the only level that involves the prox sensor is the `k_EDeviceActivityLevel_UserInteraction` but it's a union of both the prox and the gyro, so according to OpenVR the headset is always interacting with the user forever as long as a gentle breeze or vibration tilts the headset a little bit once every 10 seconds.

## \[EDIT\]

Some things got fixed in the meantime. For instance now there is an entry for the Hmd, instead of Any; and OpenVR does have an XRDevice.userPresence value (though it might not explicitly be the proximity sensor).
> 1 votes

# Answer
Yes, OpenVR has events for this:

> **VREvent\_TrackedDeviceUserInteractionStarted** fires when the devices transitions from Standby -\> UserInteraction or Idle -\> UserInteraction. **VREvent\_TrackedDeviceUserInteractionEnded** fires when the devices transitions from UserInteraction\_Timeout -\> Idle

Additionally, you can poll the status of the headset with `GetTrackedDeviceActivityLevel` from Valve.VR.IVRSystem. Which will return one of the following values:

```
public enum EDeviceActivityLevel
{
    k_EDeviceActivityLevel_Unknown = -1,
    k_EDeviceActivityLevel_Idle = 0,
    k_EDeviceActivityLevel_UserInteraction = 1,
    k_EDeviceActivityLevel_UserInteraction_Timeout = 2,
    k_EDeviceActivityLevel_Standby = 3,
}

```

There's also some level of this introduced into the Unity scripts (Scripts/Core/VRView.cs:GetIsUserPresent()
> 7 votes

# Answer
Chiming in for checking a mounted / proximity sensor event for the Oculus OVR unity plugin. This is in `OVRManager`:

```
/// <summary>
/// Occurs when an HMD is put on the user's head.
/// </summary>
public static event Action HMDMounted;

/// <summary>
/// Occurs when an HMD is taken off the user's head.
/// </summary>
public static event Action HMDUnmounted;

```

Which is present in the source but for some reason does not come up by searching the oculus docs.

\[EDIT\]

Also, if you don't want Oculus to pause the game to a black screen when you take the headset off:

* If you're using version 1.3 (2016) or below, of the Oculus SDK, then set `runInBackground = true` in `OVRManager`, which is independent from unity's own `runInBackground` setting.
* In newer versions use Unity's `Application.runInBackground = true` and `Camera.stereoTargetEye = StereoTargetEyeMask.None`

## \[EDIT2\]

The OVRManager events didn't work for me at all. What does work is using the `OVRPlugin` class and doing `if (!OVRPlugin.userPresent && m_wasUserPresent)` yourself.
> 2 votes

# Answer
In Unity, using the OpenVR unity plugin, the following works:

```
print(SteamVR_Controller.Input(0).GetPress(EVRButtonId.k_EButton_ProximitySensor));

```

BTW, in a response to the accepted answer i proposed: `OpenVR.System.GetTrackedDeviceActivityLevel(0)`, but that's more for detecting recent motion within 10 seconds.
> 2 votes

# Answer
You can now also use `UnityEngine.XR` and `XRDevice.userPresence` without the need for additional API's : https://docs.unity3d.com/ScriptReference/XR.XRDevice-userPresence.html

For example :

```
if(trackingPresence == true)
    {
        if(XRDevice.userPresence == UserPresenceState.Present && playerPresent == false)
        {
            playerPresent = true;
            Debug.Log("[PLAYER PRESENCE DETECTOR] player is now present");
        }

        if(XRDevice.userPresence == UserPresenceState.NotPresent && playerPresent == true)
        {
            playerPresent = false;
            Debug.Log("[PLAYER PRESENCE DETECTOR] player is now absent");
        }
    }

```

**Edit :** for latest versions of Unity, you can use `XRDisplaySubsystem.running` : https://docs.unity3d.com/2020.3/Documentation/ScriptReference/XR.XRDisplaySubsystem.html
> 2 votes

# Answer
In Android, there is the Proximity Sensor. This is used to disable the screen when you're calling someone. I'm not sure if you have access to the proximity sensor in Unity, but you can call the native method through Unity.
> 1 votes

# Answer
If anyone wants to force the Oculus VR application to not pause the game while the headset is turned off, you need to do some dll stuff.\[source\]

Here's how, and I have also included code for the SteamVR / OpenVR settings:

```
    using System.Runtime.InteropServices;
    [DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool ovrp_SetAppIgnoreVrFocus(bool value);
    [DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
    public static extern uint ovrp_GetStatus2(uint query);

    void Start () {
        Application.runInBackground = true;
        SteamVR_Render.instance.pauseGameWhenDashboardIsVisible = false;
        ovrp_SetAppIgnoreVrFocus(true);
        //ovrp_GetStatus2(uint query);
        //m_vrCam.stereoTargetEye = StereoTargetEyeMask.None;
    }

```
> 1 votes

# Answer
For OVR `ovr_GetSessionStatus()` tells you this, `OVRSessionStatus` has a field `HmdMounted`.
> 1 votes

# Answer
Add this code to new gameobject in the scene and it will check and print the user is occupying the headset or not. Based on that you can do your changes.

```
 public class HeadsetDetection : MonoBehaviour
        {
        public SteamVR_Action_Boolean headsetOnHead = SteamVR_Input.GetBooleanAction("HeadsetOnHead");
                public bool IsHeadsetOnHead;
                public Action OnHeadsetOnHead, OnHeadsetOffHead;
            void Update()
                {
             if (headsetOnHead != null)
                    {
                        if (headsetOnHead.GetStateDown(SteamVR_Input_Sources.Head))
                        {
                            Debug.Log("Headset placed on head");

                            IsHeadsetOnHead = true;

                            if (OnHeadsetOnHead != null)
                            {
                                OnHeadsetOnHead();

                            }
                        }
                        else if (headsetOnHead.GetStateUp(SteamVR_Input_Sources.Head))
                        {
                            Debug.Log("Headset removed");

                            IsHeadsetOnHead = false;
                            if (OnHeadsetOffHead != null)
                            {
                                OnHeadsetOffHead();
                            }
                        }
                    }
            }
    }

```
> 0 votes

# Answer
i ran into the same issue of pausing the game when user takes the headset off, and resumes when puts back on. after trying alot of options, i found the best thing to do is to put your code where oculus is detecting that action. for my case i added it in OVR Manager script's update function.
> 0 votes

---
Tags: unity, virtual-reality, oculus, htc-vive
---


title: Render in a imGui Window

text:
# Question
Title: Render in a imGui Window
How do i render my game scene into an imgui window?

I want to get from this:

to this :

# Answer
> 18 votes
First of all we need to create what is called Frame Buffer Object, or FBO for short. I'll leave you a great tutorial on (pretty much everything regarding OpenGL)FBOs right here: https://learnopengl.com/#!Advanced-OpenGL/Framebuffers

Now that we created an FBO, we should have a texture. This texture contains the image of what is rendered on the FBO. At this point all we need to do is to "put" this image inside of a dear ImGui Window. Let's see how to do this:

```
//this is our main game loop
while (!window.Closed())
{
    //we need to clear the window,
    //This is how the clear method is structured:
    //void Window::Clear(float x, float y, float z, bool enableGLDepth,bool clearImGUIframe)const
    //{
    //  //clear the color of the window with an alpha value of 1.0f
    //  glClearColor(x, y, z, 1.0f);
    //  if (clearImGUIframe)
    //  {
    //      ImGui_ImplGlfwGL3_NewFrame();
    //  }
    //  if (enableGLDepth)
    //  {
    //      //enable the GL_DEPTH_TEST to be able to see 3D object correctly
    //      glEnable(GL_DEPTH_TEST);
    //      //clear both the color buffer bit and the depth buffer bit
    //      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //  }
    //  else
    //  {
    //      //clear just the color buffer bit
    //      glClear(GL_COLOR_BUFFER_BIT);
    //  }
    //}

    window.Clear(0.5f, 0.5f, 0.5f,true,true);

    //switch to our custom FBO
    //window.bindFBO is the same as writing glBindFramebuffer(GL_FRAMEBUFFER,FBO);
    window.bindFBO();

    //we need to call clear twice
    window.Clear(1.0f, 1.0f, 1.0f, true, false);
    //Draw our simple triangle
    shader.Use();
    glBindVertexArray(Tvao);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    //switch to the default FBO
    //again, unbindFBO() is the same as glBindFramebuffer(GL_FRAMEBUFFER,0)
    window.unbindFBO();

    //create our ImGui window
    ImGui::Begin("Scene Window");
    //get the mouse position
    ImVec2 pos = ImGui::GetCursorScreenPos();

    //pass the texture of the FBO
    //window.getRenderTexture() is the texture of the FBO
    //the next parameter is the upper left corner for the uvs to be applied at
    //the third parameter is the lower right corner
    //the last two parameters are the UVs
    //they have to be flipped (normally they would be (0,0);(1,1)
    ImGui::GetWindowDrawList()->AddImage(
        (void *)window.getRenderTexture(),
ImVec2(ImGui::GetCursorScreenPos()),
        ImVec2(ImGui::GetCursorScreenPos().x + window.getWidth()/2,
ImGui::GetCursorScreenPos().y + window.getHeight()/2), ImVec2(0, 1), ImVec2(1, 0));

    //we are done working with this window
    ImGui::End();
    //swap the buffers and check for events
    window.Update();
}

```

after all this you should get this result:

Hope this helped someone! I'll also leave the entire code i am using down here:

Main.cpp

```
#include "Engine.h"

using namespace Engine;
using namespace graphics;

int main()
{
    Window window("Advent3D", 800,600, false);
    Shader shader("Res/Shaders/Unlit.shader");

    //TRIANGLE CREATION//
    float Tvertices[] = {-0.5f, -0.5f, 0.0f,0.5f, -0.5f, 0.0f,0.0f,  0.5f, 0.0f};

    unsigned int Tvbo, Tvao;
    glGenVertexArrays(1, &Tvao);
    glGenBuffers(1, &Tvbo);
    glBindVertexArray(Tvao);
    glBindBuffer(GL_ARRAY_BUFFER, Tvbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Tvertices), Tvertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);

    while (!window.Closed())
    {
        //we need to clear the window,
        window.Clear(0.5f, 0.5f, 0.5f,true,true);

        //switch to the custom fbo
        window.bindFBO();

        window.Clear(1.0f, 1.0f, 1.0f, true, false);

        shader.Use();
        glBindVertexArray(Tvao);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        //switch to the default fbo
        window.unbindFBO();

        ImGui::Begin("Scene Window");

        ImVec2 pos = ImGui::GetCursorScreenPos();

        ImGui::GetWindowDrawList()->AddImage(
            (void *)window.getRenderTexture(), ImVec2(ImGui::GetCursorScreenPos()),
            ImVec2(ImGui::GetCursorScreenPos().x + window.getWidth()/2, ImGui::GetCursorScreenPos().y + window.getHeight()/2), ImVec2(0, 1), ImVec2(1, 0));

        ImGui::End();

        window.Update();
    }
}

```

# Answer
> 0 votes
The best approach I found so far that integrates well with windows even if they hover above others (in contrast to the original answer) and is also performant when rendering multiple views (in contrast to the accepted answer of using images), is as follows:

```
int fbX, fbY;
glfwGetFramebufferSize(ImGui::GetCurrentWindowRead(), &fbX, &fbY);

auto viewWin = ImGui::GetCurrentWindowRead();
Eigen::Vector4f viewRect(viewWin->InnerRect.Min.x, viewWin->InnerRect.Min.y, viewWin->InnerRect.GetWidth(), viewWin->InnerRect.GetHeight());
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddCallback([&](const ImDrawList* dl, const ImDrawCmd* dc)
{
    Eigen::Vector4f clip(
        dc->ClipRect.x, dc->ClipRect.y,
        (dc->ClipRect.z-dc->ClipRect.x), (dc->ClipRect.w-dc->ClipRect.y));
    viewRect *= pixelRatio;
    clip *= pixelRatio;
    glViewport(viewRect.x(), fbY-viewRect.y()-viewRect.w(), viewRect.z(), viewRect.w());
    glScissor(clip.x(), fbY-clip.y()-clip.w(), clip.z(), clip.w());
    glClearColor(0.2f, 0.0, 0.2f, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Enable Depth for 3D scene
    glDepthMask(GL_TRUE);
    glClearDepth(0);
    glDepthFunc(GL_GEQUAL);
    glEnable(GL_DEPTH_TEST);

    // TODO: Render 3D scene
}, nullptr);
draw_list->AddCallback(ImDrawCallback_ResetRenderState, nullptr);

```

The example uses glfw and some eigen but the idea should be clear. Use a callback to render a scene (3D or not) at the right time so the UI elements that should be behind are behind, and the ones ontop are properly ontop. UI is always rendered ontop, so no need to worry about depth buffer, you can use it for your scene or not. The advantage is also that it'll only render the part of the scene that is visible, and you can differentiate between your viewRect and your clipRect.

**Original Answer:**

A much simpler (and, if you have multiple windows with GL viewports, more performant) solution, is to keep all background of windows with GL ports transparent (and dockspace background, if you use it), and then manually clear the backgrounds (using `glViewport` and `glScissor` followed by `glClearColor` and `glClear`) using the rectangle of each window (`GetWindowPos/GetWindowSize`).

Then you can first render your GL part using the same method in the rectangles you want them to be in, and then the UI on top. Looks seamless, and should be much more performant than multiple render passes.

---
Tags: opengl, c++, gui, ui-design, imgui
---


# Question
Title: Problem when changing matrix view in screen space reflexion
I’m using (DX11) LookAtLH or LookTo functions to get my view matrix. When setting Camera Direction so that the y component is zero I have the correct reflexion (picture left). When changing the Dir.y to negative or positive values I have picture on middle or right. In my calculation this corresponds to a rotation on the x axis (e.g. parallel to screen). I’m not using arcball but keyboard input to modify the rotationx/y params.

```
Roty -= 0.005f*iRotate;//iRotate =0 or 1 if keyboard left/right arrow pressed
//iMove 0/1 is up/down arrow pressed
Rotx += 0.005f*iLift;//iLift 0/1 if pageup/pagedown pressed
m_WorldCamera.m_Dir = XMVector3Transform(XMVectorSet(1, 0, 0, 0), XMMatrixRotationY(Roty)*XMMatrixRotationX(Rotx));
m_WorldCamera.m_Eye += m_WorldCamera.m_Dir*(float)iMove
XMVECTOR DEye = m_WorldCamera.m_Eye+XMVectorSet(0, -25, 0, 0);
gView = XMMatrixLookToLH(DEye, m_WorldCamera.m_Dir, XMVectorSet(0, 1, 0, 0));

```

My SSR normal map is calculated in the shader as NSSR = Mesh.Normal\*(float3x3)(ObjectWorldMat\*CameraView).

Is there something important I missed to be able to get the correct reflexion whatever the camera rotationX angle?

On the left you can see the generated textures used in my SSR shader.

1. Bumpped normals in view space (txNormal2);
2. unmodified mesh normals in view space used for reflexion calculation (txNormal1);
3. Layers of the scene (txdiffuse1). In the topright part 1/2 screen resolution for main scene and other parts 1/4 resolution for layers containing occluded objects.
4. Depth buffer for main scene full res, not used in the SSR shader;
5. Depth buffer (txDepth1) for layers texture (txdiffuse1).

Using layers at 1/2 and 1/4 resolution gives the shader below for 3 layers including the main scene. The resulting color is blended to the main target. Note that doing everything in full screen resolution gives me the same problem.

```
static const float2 TpDecal[4] = {{0,0}, {0.25,0}, {0,0.25} , {0.25,0.25}  };
#define STEP 2.5*0.02
#define ITER 30
#define STEP2 0.5f
#define BUMP 0.075f

float4 PS_PostDeferredReflex3(PS_INPUTQUAD Input) : SV_TARGET
{
    //the screen quad mesh used for rendering has regular 0..1 texture coordinates.
    //As we use 1/2 resolution from the topright quad of txDiffuse1
    //we modify Input.Tex.xy as UV to sample topright quad.
    float2 UV = mad(Input.Tex, 0.5, float2(0.5,0));
    //sample 1/2 resolution Depth
    float D = txDepth1.SampleLevel(sPoint, UV, 0).r;
    if ( D > 0.99999 ) return float4(0,0,0,0);
    //sample full screen resolution mesh normals
    float2 NN = txNormal1.SampleLevel(sPoint, Input.Tex, 0);
    if ( NN.r == 0 ) return float4(0,0,0,0);
    //the line below uses precalculated value from the inverse projection matrix (only _11, __22,_34 and _43 values are necessary) to obtain Pos in view space with a mad op.
    float3 PosV = float3(mad(Input.Tex.xy, float2(  0.707243978977203, -0.397824734449387),float2( -0.353621989488602,  0.198912367224693)), 1)/(-0.998999953269959*D+1);
//  line above equivalent to
//  float4 PosV = mul(float4(mad(Input.Tex.xy, float2( 2, -2),float2( -1,  1)), D, 1), InvProj);
//  PosV/=PosV.w;
    NN = mad(NN,2,-1);
    //normals are stored in view space as RG format.
    //We retrieve B value below with Pithagorean theorem.
    float3 VSDir = normalize(reflect(normalize(PosV),float3(NN.rg, 1-sqrt(dot(NN.rg, NN.rg)))));
#ifdef BUMP // add some deviation in the ray based on the bumpy normals in txNormal2
    //not the origin of my problem
    NN = txNormal2.SampleLevel(sPoint, Input.Tex, 0);
    NN = mad(NN,2,-1);
    VSDir += VSDir*float3(NN.rg, 1-sqrt(dot(NN.rg, NN.rg)))*BUMP;
#endif

    float3 SSray = float3(UV, D);//set the start 1/2 resolution
    //line below calculate the end of ray in full screen
    float4 SSEnd = mul ( float4(PosV + VSDir*500, 1), Proj);
    SSEnd/= SSEnd.w;
    //adjust the result to half screen, topright panel (z component
    //not affected) and do the difference to SSray to give the
    //maximum  length of the ray in screen space.
    SSEnd.xyz=mad(SSEnd.xyz, float3(0.5,0.5,1), float3(0.5,0,0))-SSray;
    float3 SSDir = SSEnd.xyz*STEP;//set the step for 1/2 res
    float2 SSDir2 = SSDir.xy*STEP2;//set the step UV for 1/4 res
    float2 TpRay =  Input.Tex*0.25;//set the start UV for 1/4 res
    float2 DZH;
    float3 EndRay;
    float3 MinRay;
    float3 MaxRay;
    float2 EndRay2;

    float3 T;
    float3 ZBufferVal;
    int i=0;
    while (i<ITER)
    {
        i++;
        EndRay = SSray;
        EndRay2 = TpRay;
        SSray+=SSDir;//increments 1/2 res
        TpRay+=SSDir2;//increments 1/4 res
        ZBufferVal.r = txDepth1.SampleLevel(sPoint, SSray.xy, 0);//sample 1/2 res
        ZBufferVal.g = txDepth1.SampleLevel(sPoint, TpRay.xy, 0)+0.00002f;//sample 1/4 layer 1, if Z.g=Z.r the offset ensure selection of the main higher res layer
        ZBufferVal.b = txDepth1.SampleLevel(sPoint, TpRay.xy+TpDecal[1], 0)+0.00002f;//sample 1/4 layer 2
        T = SSray.zzz-ZBufferVal;//select the final layer based on comparison of T.rgb and DZH.x
        DZH = float2(0.005, 0);//set a starting maximum value for DZH.x. The DZH.y component will contain the layer index (1-3)
            //this conditionnal assignment performs better than if statments
        DZH = (( T.r>=0 )&& (T.r<DZH.x))?float2(T.r,1):DZH;
        DZH = (( T.g>=0 )&& (T.g<DZH.x))?float2(T.g,2):DZH;
        DZH = (( T.b>=0 )&& (T.b<DZH.x))?float2(T.b,3):DZH;
        if ( DZH.y>0) //if layer encoutered by the ray
        if ( DZH.x < 0.0005) //if delta depth < 0.0005
        {
            MinRay = EndRay;//refinement loop
            MaxRay = SSray;
            //if not main layer 1 (1/2 res) modify the MinMaxRay
            //UV coordinates according to the 1/4 res viewports
            //decals stored in TPDecal
            if(DZH.y>1)
            {
                float2 dtp = TpDecal[DZH.y-2];
                MinRay.xy = EndRay2+dtp;
                MaxRay.xy = TpRay+dtp;
            }
            for(int j = 0; j < 8; j++)//do refinement loop
            {
                EndRay = (MinRay+MaxRay)*0.5f;
                T.r = txDepth1.SampleLevel(sPoint, EndRay.xy, 0);
                if ( EndRay.z > T.r) MaxRay = EndRay; else MinRay = EndRay;
            }
            if (abs(EndRay.z-T.r)<0.000025) //output color if delta depth low enought with blend according to ray length done
            {
                return float4(txDiffuse2.SampleLevel(sPoint, EndRay.xy, 0).rgb,1-clamp((EndRay.z-D)/SSEnd.z, 0, 1));
            }
        }
    }
    return float4(0,0,0,0);
}

```

# Answer
> 0 votes
Finally the problem was in the normal used for SSR. Retrieving the z component from the stored xy format by the Pythagorean theorem works well if the sign of z can be fixed. Apparently when the camera rotate around the x axis (e.g. axis parallel to screen width in my case) the retrieved z value is not consistent and so it is better to store the normal in full xyz R10B10G10 format. Doing so solved my problem with good precision. Alternative packed format for SSR normal could be another answer. For instance Spheremap Transform with R16G16\_UNORM format works well too with no impact compared to R10G10B10A2 considering the additional coding/decoding instructions. R16G16\_FLOAT gave me small flickering in the mirrored pixels. R8G8 is not precise enought for this purpose with bad reflexion aspect.

```
coding spheremap normal
float2 NOut = mad(N.xy, 1.0/sqrt(N.z*8+8), 0.5);
decoding
float2 NIn = mad(txNormal.sample().rg, 4, -2);
float f = dot(NIn ,NIn );
float3 NOut = float3(NIn*sqrt(1-f*0.25), 1-f*0.5);

```

---
Tags: rotation, screen, view, reflection-rendering
---


# Question
Title: "Rotation Quaternions must be unit length" using rigidbody.MoveRotation in unity
I'm making a game that involves throwing things with catapults. The cup of a catapult needs to use `Rigidbody.MoveRotation` to let a ball respond to being thrown in the physics engine. I use the following code for my update function(just as a test):

```
void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            if (transform.rotation.z > -95.4)
            {
                Quaternion targetRotation= new Quaternion(0f,0f,(float)(transform.rotation.z-5*Time.deltaTime),0f);
                targetRotation=rigidbody.rotation;//rigidbody is a Rigidbody object
                targetRotation.z -= 5;
                rigidbody.MoveRotation(targetRotation);
            }
        }
    }

```

This has been giving me the error `Rotation quaternions must be unit length`. I can't find a reference to that in the unity API, and the one solution I found online was to use the Quaternion's `normalize` attribute. However, when I did this, the throwing arm rotated 180° almost instantly, and then the same error got thrown a bunch of times. How do I prevent this error from happening, and how do I slow down the rotation?(changing the values doesn't seem to help). And yes, interpolation is on in the rigidbody component. Let me know if you need more info, thanks!

# Answer
> 0 votes
It's not meaningful to manipulate individual components of a quaternion the way you're doing. They're not Euler angles. They're points on a 4-dimensional unit sphere where three of the dimensions are imaginary numbers. So, better to stick to the methods of the `Quaternion` class for manipulating them.

It looks like what you want is something more like this:

```
// Physics interactions should be done in FixedUpdate for framerate independence.
void FixedUpdate()
{
    if (Input.GetKey(KeyCode.Space) && transform.localRotation.z > -95.4)
    {
        // Apply the speed of rotation directly, along the desired rotation axis.
        rigidbody.angularVelocity = transform.forward * -rotationSpeed;
    }
}

```

# Answer
> 0 votes
There is a warning in the Unity documentation about Quaternion class:

> Don't modify this directly unless you know quaternions inside out.

I don't fully understand the math behind quaternions either. But that's no problem when using Unity, because it provides so many useful convenience methods for working with quaternions that you will never encounter a situation where you really need to. You can be a perfectly competent Unity developer when you just accept that the inner workings of quaternions are black magic. Just see them as magic black boxes which encode a rotation around an arbitrary axis in 3d space by a certain angle and move on with your life.

* When your catapult arm is a rigidbody, and the projectile it is supposed to launch is also a rigidbody, then you could leave the whole catapult mechanics to the Unity physics engine. Just cause the catapult arm to rotate by applying a torque with Rigidbody.AddTorque.
* When you prefer to handle the projectile launching physics yourself and make the catapult arm movement entirely cosmetic, then you can rotate it with Quaternion.RotateTowards. This method only needs three pieces of information:
    + The current roation, which you can get through `transform.rotation`
    + The desired final rotation, which you do not need to state in the `x, y, z, w` form but can generate through Quaternion.Euler or set in the inspector.
    + Number of degree you want to turn on this frame. Which you usually calculate by taking a constant angular velocity in degree per second and multiplying it by `Time.deltaTime`.
* Or don't hardcode the movement of the arm at all, and do it with the animation system. The animation system is not just for character models. It can animate any public inspector property, including the rotation of a transform.

# Answer
> -1 votes
Don't use Rigidbody methods in `Update` method as much as you can do. I have met similar issues several times. The best you can do is to use Rigidbody related methods in `FixedUpdate` method. Especially if they depend on `deltaTime - fixedDeltaTime`, I highly recommend you to use Rigidbody in `FixedUpdate`. Even if you try to use `Time.deltaTime` in `FixedUpdate` method Unity will know and convert it to `Time.fixedDeltaTime`.

---
Tags: unity, quaternion, rigidbody
---


title: Clicking UI button calls event twice

text:
# Question
Title: Clicking UI button calls event twice
I've designed a game where, when a button is clicked, the moving point stops. If the button is clicked again, the moving point starts moving again.

I only click on the button once, but the `ToggleGame()` is always called twice. Does anyone know the reason?

```
private void Start()
{

    if (toggleButton != null)
    {
        toggleButton.onClick.AddListener(ToggleGame);
    }

    StartGame();
}

public void StartGame()
{
    isMoving = true;
    // init some settings here
}

void Update()
{
    if (isMoving)
    {
       // run the game
    }
}

public void ToggleGame()
{
    if (!isMoving)
    {
        StartGame();
        UpdateButtonText("Stop");
    }
    else
    {
        isMoving = false;
        CheckWinCondition();
        UpdateButtonText("Start");
    }
}

```

# Answer
> 2 votes
This thread may help you. Here's a summary:

You may have your left-click set to 'submit' in input settings and it is both calling a submit and select event on your single-click of the toggle-button. The user in the linked thread reported solving the issue by removing 'mouse 0' from the 'submit' bind in input settings

---
Tags: unity, c#, events, unity-ui, callbacks
---


# Question
Title: Why is my toon shader not getting pixelated?
I made a very simple unlit toon shader that works great, however I have to also pixelate my objects, I tried adding this part marked in blue that modifies the UVs but that did not have the desired effect, how can I change this up so my toon shader also gets pixelated?

# Answer
> 0 votes
It looks like your pixelation is working properly, so maybe it's the toon shading which is making it look too smooth. Try moving the pixelation to the end of the process after everything else is combined?

---
Tags: unity, shaders
---


title: Procedural Path Generation

text:
# Question
Title: Procedural Path Generation
I've been trying to make an algorithm to procedurally generate a path from a tile map attached below.

I'm just looking for a method to go about doing this.

EDIT: I want to make a path for a tile map like generate a path then output to a tile map. Pardon the drawing but this is kinda what I want it to look like: \[ I don’t want it to be something like this: \[

# Answer
> 0 votes
I would look at the maze generation algorithms for inspiration (single path is not generally warranted, so randomly open some paths, the amount depends on the openness needed) and then apply the tileset to the generated graph's turn possibilities, straight, open, and split paths.

---
Tags: procedural-generation, tilemap, path
---


# Question
Title: How do I get the depth texture in an expression in Godot 4's visual shader?
I'm working on a tutorial for creating wake waves with Godot, versions 3.5 and, importantly, the upcoming 4.0. It uses shaders (including visual) and works fine so far, but in attempting to get the fragment shader working, it is suggested that I add an expression using the line:

```
float d = texture(DEPTH_TEXTURE, SCREEN_UV).r;

```

Unfortunately, this tutorial was made during the beta phase, and DEPTH\_TEXTURE has been removed in favor of something called `hint_depth_texture`... which I am having a terrible time finding any actual documentation on. It does not seem to refer to a texture directly, and I cannot seem to declare a uniform from within an expression node.

Can someone help me mimic this functionality with the new Godot visual shaders?

Thank you.

# Answer
> 2 votes
This change really just means that there's no longer a special constant representing the screen or depth textures. Instead, you're supposed to define a uniform `sampler2D` that will receive the screen or depth texture instead.

You can even restore the previous behavior, just by picking `DEPTH_TEXTURE` as its name.

```
uniform sampler2D SCREEN_TEXTURE: hint_screen_texture;
uniform sampler2D DEPTH_TEXTURE: hint_depth_texture;

```

While this sounds like a unnecessary change, it gives you way greater control, e.g. by defining whether you want the texture to repeat, how to filter it, etc. (all using additional hints):

```
uniform sampler2D screen_nearest: hint_screen_texture, filter_nearest;
uniform sampler2D screen_no_repeat: hint_screen_texture, repeat_disable;

```

---
Tags: shaders, glsl, depth, godot-4
---


# Question
Title: How do game engines avoid recalculating normals upon mesh rotation?
Assume that a face of a mesh is defined by vertices `A`, `B`, `C` and that the normal of the face is defined by `(B - A) x (C - A)`.

Rotating the mesh about its local origin with matrix `R` makes the normal calculation `R(B - A) x R(C - A)`.

~~To my knowledge there is no algebraic property of the cross product that lets us simply do `R((B - A) x (C - A))` to rotate the normal just like all the vertices.~~ The cross product preserves distribution over an orthonormal matrix.

Instead it seems like the normal needs to be entirely recalculated every time the object is rotated. This seems unreasonably expensive for a realtime application so I was curious if game engines have some way to efficiently transform normals, approximate them, or avoid them altogether.

# Answer
> 28 votes
They don't.

When you rotate a mesh, the normals in memory are not changed in any way. All that changes is the object's transformation matrix is updated. The raw mesh vertex and normal data remains unchanged, and can be shared between many instances of the model that get drawn with different positions, orientations, and scales.

These transformations are applied "just in time" during rendering. We need to multiply the vertex positions by the camera's view and projection matrices anyway to figure out where to draw it on screen, so we can just pre-multiply those with the object's transformation matrix (often called either the model matrix or the world matrix) to get a combined "MVP" matrix (model-view-projection), then transform each vertex with just a single matrix multiplication in the vertex shader, as it's being drawn.

The same trick works for normals, it's just that we use the inverse-transpose of the model matrix multiplied by the view matrix (no projection) to map the normal into view space (where we usually want it in deferred rendering, though some lighting systems use a different coordinate space for lighting).

This isn't unduly expensive. A matrix multiplication per vertex isn't breaking the bank when we can do hundreds of them in parallel on modern GPUs, and we'd need to pay that cost anyway every time the camera moves, which in many games is already happening every frame. The ability to combine multiple matrix transformations into a single matrix lets us bake the model's transformation in "just in time" at no added cost per vertex.

For things like CPU-side physics calculations, we can often use the inverse of the model matrix to transform the calculation into the model's local space, rather than transforming all vertex positions and normals into world space. Then once we know which face has been collided with, we can take the one resulting collision normal and transform just it into world space, without having to touch any of the others.

# Answer
> 16 votes
DMGregory's answer explains how this is actually handled, but I'd like to point out a couple of misconceptions:

> Assume that a face of a mesh is defined by vertices `A, B, C` and that the normal of the face is defined by `(B - A) x (C - A)`.

Note that this is only true for “flat shading”, where each triangle forms a visible facet, near-uniformly lit. Most meshes today have **normals explicitly defined per vertex,** which allows them to be interpolated to simulate curved surfaces. The normals will typically be *similar* to the cross product, but not equal — in particular, the 3 vertices of a triangle will have different normals, unless the surface the mesh is approximating is actually flat.

**These normals cannot be calculated from the mesh,** but rather are created at the same time as the mesh, and the algorithm (or author's manual operations) will depend on the intent. For example, a mesh which has the form of a hexagonal tube might be intended to be in fact hexagonal (and the normals will be perpendicular to the faces) or it might be intended to be a low-polygon approximation to a cylinder or wire (in which case the normal of each vertex will point radially outward, so faces have varying normals, and lighting is smooth across the edge between faces).

For game graphics purposes, you should understand normals as a property vertices have, which we wish to **preserve the meaning of under various transformations;** not as something you can derive *from* the mesh except when you are making the particular aesthetic restriction of using only flat shading.

“Face normals” are not used or computed at all (unless you are doing something unusual. Normals are interpolated per-pixel across the surface of a triangle, to approximate curved surfaces.

> To my knowledge there is no algebraic property of the cross product that lets us simply do `R((B - A) x (C - A))` to rotate the normal just like all the vertices.

Yes and no. The matrix *can* be such that `R((B - A) x (C - A))``R(B - A) x R(C - A)`, but in that case, **it is not a rotation matrix** — it is some other less restricted sort of matrix.

But, since normals are not in practice defined by cross products of vertex differences, the cross product doesn't matter. What does matter is that the vertex normals are transformed in a way which matches the transformation of the shape the mesh forms, so they remain appropriate.

In the simple case of a pure rotation matrix, which does not change the angles between vectors, it suffices to rotate the normals with the same matrix. Picture the normals as pins sticking out of the vertices, and understand that we are rotating — or more generally, performing a *rigid transformation* — of the entire object as a whole.

More generally — such as if the matrix contains non-uniform scale — it is necessary to use a different matrix to transform the normals (as DMGregory's answer mentions), and that is what is in fact done in general-purpose renderers.

# Answer
> 0 votes
A few words on *why* people use the inverse transpose when mapping normals: suppose your normal at a point \\$p\_1\\$ on the untransformed object is \\$n\\$ and \\$p\_2\\$ is a nearby point on the object. Suppose also that you are applying the affine transformation matrix \\$M\\$ to your object, so that \\$Mp\_1\\$ and \\$Mp\_2\\$ are the new locations of \\$p\_1\\$ and \\$p\_2\\$ on the transformed object.

You want to transform the normal using a matrix \\$N\\$ so that the angle between \\$n\\$ and \\$p\_2 - p\_1\\$ is preserved:

$$ \begin{align} (Nn) \cdot (Mp\_2-Mp\_1) &= n \cdot (p\_2 - p\_1) \\ n^T N^T M (p\_2 - p\_1) &= n^T (p\_2-p\_1) \end{align} $$ and this equation is true for any choice of \\$p\_2\\$ if \\$N^TM\\$ is the identity, i.e. \\$N = M^{-T}\\$.

---
Tags: geometry, 3d-meshes, mesh, linear-algebra, normals
---


# Question
Title: Is it possible to change the default color of Godot's NavigationMesh3D in the editor?
I'm working on a game that uses a lot of high-intensity and pastel color language, and unfortunately, the navigation mesh is doing the same thing! There's a good bit of eye strain there. If I could switch it to something earthier, it would solve a lot of these issues; but I can't seem to find it anywhere in 3D Gizmos in the Editor Settings.

Is there a manner in which I can change the default light blue to something different, and more contrasting with my visual style?

# Answer
> 1 votes
Go to Project (menu) -\> Project Settings -\> General (tab) -\> Debug -\> Shapes

There you will these categories:

* Navigation
* Avoidance
* Collision
* Paths

Each one with configuration for their corresponding colors.

---
Tags: godot, color, navmesh, editors, settings
---


# Question
Title: Monogame - SpriteFont Exception: Text contains characters that cannot be resolved by this SpriteFont
I'm trying to put text on the screen and if I put anything but an empty string I get "Text contains characters that cannot be resolved by this SpriteFont.\nParameter name: text"

```
_spriteBatch.DrawString(screenText, "A", new Vector2(0, 200), Color.Black);

```

screenText is the name of my SpriteFont variable.

```
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:LocalizedFontDescription">

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Arial</FontName>

    <!--
    Size is a float value, measured in points. Modify this value to change
    the size of the font.
    -->
    <Size>6</Size>

    <!--
    Spacing is a float value, measured in pixels. Modify this value to change
    the amount of spacing in between characters.
    -->
    <Spacing>0</Spacing>

    <!--
    UseKerning controls the layout of the font. If this value is true, kerning information
    will be used when placing characters.
    -->
    <UseKerning>true</UseKerning>

    <!--
    Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
    and "Bold, Italic", and are case sensitive.
    -->
    <Style>Regular</Style>

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->

    <!--
    CharacterRegions control what letters are available in the font. Every
    character from Start to End will be built and made available for drawing. The
    default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
    character set. The characters are ordered according to the Unicode standard.
    See the documentation for more information.
    For localized fonts you can leave this empty as the character range will be picked up
    from the Resource Files.
    -->
    <CharacterRegions>
      <CharacterRegion>
        <Start> </Start>
        <End> </End>
      </CharacterRegion>
    </CharacterRegions>
    <!--
    ResourceFiles control the charaters which will be in the font. It does this
    by scanning the text in each of the resource files and adding those specific
    characters to the font.
    -->
    <ResourceFiles>
        <!-- <Resx>Strings.resx</Resx> -->
    </ResourceFiles>
  </Asset>
</XnaContent>

```

I did build and rebuild the spritefont file using the Content Builder.

# Answer
> 3 votes
The problem lies in your .spritefont file.

```
-->
<CharacterRegions>
  <CharacterRegion>
    <Start> </Start>
    <End> </End>
  </CharacterRegion>
</CharacterRegions>
<!--

```

The region starts with character #32 (Space) and ends with character #32. Change the value to #126. This gives you the normal range of characters. Just rebuild your Content with the new value and all will be well. Good luck, Stoort

# Answer
> 0 votes
Adding my experience here as this was one of the first Google hits.

You could consider making sure you don't get this exception in any case, by defining a default character to be replaced for any character missing from the font.

You can put something like this in your spritefont file:

```
<DefaultCharacter>*</DefaultCharacter>

```

Or you can do `font.DefaultCharacter = '*'` after loading the font.

References: community thread, API documentation.

---
Tags: xna, monogame
---


title: How to create pixel graphics in 3D?

text:
# Question
Title: How to create pixel graphics in 3D?
I stumbled across this game on itch.io: Backland
After trying to find information on how to accomplish the same graphics, I found this tutorial: Youtube Video

**How can I accomplish this 3-dimensional, pixelated look in a game?**

***Other possibly relevant information:***
*I have been using the Godot engine, but I would appreciate information that can be used anywhere*
*I am well versed in programming, but I am new to everything else related to game development*

# Answer
> 4 votes
Some of that pixelated look might be achievable by using normal 3D rendering with low-poly models and low-resolution textures, but render to a small texture instead of the screen, then draw that texture to the screen at a larger size with nearest neighbor filtering so the pixels don't get blurred.

# Answer
> 0 votes
If you want to pixelate a 3D game smoothly, I suggest checking this post on Unity forum I wrote about creating 3D pixel art games.

I know you use Godot engine and that's on Unity forum, but the idea is the same. Basically you render the game on lower resolution (your target pixel art resolution) and upscale it back to native resolution (screen resolution). Then make some calculations so that the pixel art pixels behave smoothly. Hopefully it helps you. I'm also happy to help if you have specific questions.

---
Tags: 3d, rendering, graphics, godot, pixel-art
---


# Question
Title: Game object ownership not transferring and getting destroyed with the master client
I'm using photon pun. I have a spawner script which instantiates the eatables in the gameplay and right after the instantiation, im transferring its ownership to null. The instantiated game objects's photon view component's ownership transfer variable is set to takeover.

But, my instantiated game object is still getting destroyed with the master client, how do i stop this from happening? Also I don't have any `IPunOwnershipCallbacks` in the instantiated game object script.

# Answer
I happened to have solved it. In the create room options, I set the variable `CleanupCacheOnLeave` to false. Now the game objects weren't getting destroyed when the master left and the ownership under the photon view component, I left it to fixed.

I found this post which got it working for me
> 0 votes

---
Tags: unity, c#, multiplayer, photon
---


# Question
Title: Performance Implications of Using Multiple Materials with the Same Texture in a Skinned Mesh Renderer
I have a skinned mesh renderer that uses seven materials, all of which share the same texture and local in difference body part. Will this setup render seven times, and could it potentially impact performance?

# Answer
> Will this setup render seven times?

Yes. Each material you put into the materials list will generate a separate draw call. If your mesh is divided into submeshes for each body part, those draw calls will render just that body part, rather than redrawing all faces in the complete mesh.

You can use the Rendering Statistics overlay to count the draw calls to investigate questions like this yourself.

> could it potentially impact performance?

Yes. More draw calls tends to lead to increased performance cost. There's a certain amount of overhead to each call, and some cost to switching state to the new material while letting shaders executing the previous material finish their work.

These state switches between draw calls can be relatively inexpensive if you're using the same shader variant just with different material properties, and your project is using a Scriptable Render Pipeline (URP or HDRP) thanks to the SRP Batcher. On the built-in render pipeline or when changing shaders between materials, the cost is higher.

But what matters most is how this character stacks up against the rest of your scene. Seven draw calls for one main hero character is usually not a serious problem. 7 calls for each tiny pedestrian in a crowd of hundreds could noticeably bog down rendering.

The best way to learn what performance trade-offs are an issue for your game is to use the Profiler to measure the impact in an example scene, on your target hardware.
> 2 votes

---
Tags: unity
---