# Question
Title: Why is my call to SetDisplayMode not supported?
I have some legacy DirectX code that always returns `DDERR_UNSUPPORTED`.

I originally developed the code using DirectX3, and I am porting it to DirectX7 after spending years away from programming.

The following line is returning `DDERR_UNSUPPORTED` rather than `DD_OK`:

```
hrRetVal = pDDraw->SetDisplayMode(dwWidth, dwHeight, dwBPP, 0, 0);

```

Could someone please take a quick peek and respond if you see why this might be the case? This is not a commercial application... just something to do for fun.

Based on the Microsoft on-line documents, the `SetDisplayMode` method is not deprecated, and should work. A compiled version of my legacy program written with DirectX3 renders graphics on newer OS's such as Windows 10, without issue. I am interested in making some changes.

This Video compilation unit:

* Sets the video mode to 1024 X 768
* Create a DirectX instance, set the cooperative level.
* Which when destroyed will Restore video to original mode, and flip to GDI

```
void Video::Initialize(void)
{

  TRACE("Video::Initialize invoked\n");

  hrRetVal = {0};
  DWORD dwDefaultRefreshRate = 0x0;
  DWORD  dwWidth = 1024, dwHeight = 768, dwBPP = 8, dwRefreshRate = dwDefaultRefreshRate, dwFlags = 0x0;

  try
  {
    Check(hrRetVal); // check for DD_OK

    TRACE("Video: using emulation mode, no hardware\n"); // debugging
    TRACE("Video: DirectDrawCreateEx invoked\n");
    hrRetVal = DirectDrawCreateEx((GUID*)DDCREATE_EMULATIONONLY, (LPVOID*)&pDDraw, IID_IDirectDraw7, NULL);

    Check(hrRetVal); // TRACE value of hrRetVal
    if (DD_OK == hrRetVal)
    {
      TRACE("Video SetCooperativeLevel invoked\n");
      hrRetVal = pDDraw->SetCooperativeLevel(hwnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
      Check(hrRetVal);
      if (DD_OK == hrRetVal)
      {

        // Lets see if the video is supported
        hrRetVal = QueryVideoCapability();
        Check(hrRetVal);

        if (DD_OK == hrRetVal)
        {

          TRACE("Attempting to set video resolution to: %d %d \n", dwWidth, dwHeight);

          hrRetVal = pDDraw->SetDisplayMode(dwWidth, dwHeight, dwBPP, 0, 0); // this line always returns DDERR_UNSUPPORTED

          // hrRetVal == DDERR_UNSUPPORTED after call to SetDisplayMode

          Check(hrRetVal);
          if (DD_OK != hrRetVal)
            throw (VIDEO_EXCEPTION); // with throw an exception since hrRetVal == DDERR_UNSUPPORTED
        }
      }
      else
      {
        Check(hrRetVal);
        throw (VIDEO_EXCEPTION);
      }
    }
    else
    {
      Check(hrRetVal);
      throw (VIDEO_EXCEPTION);
    }
  }

  catch(int exception)
  {
    TRACE("%Xh exception caught by Video::Initialize\n", exception);
    Video::Check(hrRetVal);

    if (exception == VIDEO_EXCEPTION)
    {
      char message[80];
      strcpy_s ( message, "Unable to initialize video. ");
      strcat_s ( message, "\nApplication will now terminate.");
      FatalMessageBox( message );

      TRACE("APP_EXCEPTION thrown by Video::Initialize\n");
      throw (APP_EXCEPTION);
    }
  }
}

```

I'm using Visual Studio 2017 Pro v15.7.2, on Windows 10 Build 1803.

# Answer
The below method works fine to initialize the Video 1024x768x32.

I did not find the code to be deprecated. If you install the "DirectX Control Panel" you can see what video modes are supported.

```
void Video::Initialize(void)
{
    TRACE("Video::Initialize invoked\n");

    try
    {
        hrRetVal = DirectDrawCreateEx(NULL, (LPVOID*) &pDDraw, IID_IDirectDraw7, NULL);

        if (DD_OK == hrRetVal)
        {

            hrRetVal = pDDraw->SetCooperativeLevel(hwnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);

            if (DD_OK == hrRetVal)
            {
                // Lets see if the video is supported
                hrRetVal = QueryVideoCapability();
                if (DD_OK != hrRetVal)
                {
                    Check(hrRetVal);
                }

                hrRetVal = pDDraw->SetDisplayMode(1024, 768, 32, 0, DDSDM_STANDARDVGAMODE);
                if (DD_OK != hrRetVal)
                   throw (VIDEO_EXCEPTION);
            }
            else
               throw (VIDEO_EXCEPTION);
        }
        else
            throw (VIDEO_EXCEPTION);
    }

    catch(int exception)
    {

        TRACE("%Xh exception caught by Video::Initialize\n", exception);
        Video::Check(hrRetVal);

        if (exception == VIDEO_EXCEPTION)
        {
            char message[80];
            strcpy_s ( message, "Unable to initialize video. ");
            strcat_s ( message, "\nApplication will now terminate.");
            FatalMessageBox( message );

            TRACE("APP_EXCEPTION thrown by Video::Initialize\n");
            throw (APP_EXCEPTION);
        }
    }
}

```
> 0 votes

# Answer
Another possible cause is that the old sample apps and the SDK's themselves used ANSI 8 bits 'char' as their character sets and x32 as the apps bitness.

Come to this era and the default is always Unicode and invariably x64.

It pays to 'OutputDebugString' and see the text that is used to set the DX structures, the character set settings could be the problem.
> 0 votes

---
Tags: c++, directx, windows, visual-studio
---


# Question
Title: Generating nav meshes from tile based map (2D)
I'm working on a pathfinder for a MMORPG game, it's not mine; I'm RE it, now I need to create a pathfinder for monsters. But I figured that the client uses tiles for it's pathfinder (for players). Inside map files, there is a set of walkable and not walkable tiles. (Every coord XY is one tile). Now I wan't to implement the server side path finder, but the problem with these tiles is performance, some maps are 500x500 (250000 tiles). I need to reduce the number of tiles, so I guess I should convert them into navigations meshes, either triangles or bigger squares or rectangles. Is there a tool or an example code to do that? Thanks

# Answer
> 0 votes
Well I honestly think that the AStart or similar pathfinding algorithms should be able to work in such large scales, because they are mostly high performant.

Probably this helps you a bit : A-Star Algorithm Here the implementation Java Implementation

But regarding large scale maps... probably this helps you a bit... its quite a good article : http://gram.cs.mcgill.ca/papers/lanctot-06-path-finding.pdf

Or even an other stack overflow question : https://stackoverflow.com/questions/37466738/pathfinding-on-large-map

And this here is the best article I have found : https://twvideo01.ubm-us.net/o1/vault/gdc2018/presentations/Alain\_Benoit\_HierarchicalDynamicPathfinding.pdf

# Answer
> 0 votes
I had same problem and I did precomputation.

I initially planned to brute force check all of the possible mappings between all coordinates however it is quite impossible since there are so many possible pathing.

I did some optimization with initial idea and now it works great.

My biggest map was 192x192 tiles and the software didn't have any problem to process it

The source code and the programming video are fully available. It is in C# but could give you a lot of ideas:

---
Tags: 2d, path-finding, tilemap, maps, navmesh
---


# Question
Title: Algorithm to get all the blocks to the top and right of the current chosen cell in Chomp game
If I have a grid of 4x4, I want to get all the blocks/buttons in java that are to the right and top of the chosen block, how would I write an algorithm for it? For instance if the user picks the block "5" (row 2, column 2), then the blocks 1, 2, 3 and 6, 7 also change their color:

```
0  1  2   3
4  5  6   7
8  9  10  11
12 13 14  15

```

The algorithm should be valid for any grid layout. It should just change the color of the chosen block and all the blocks to the right of it, on top of it and to the top right. Thank you!

# Answer
> 0 votes
All the blocks to the right are easy: keep adding 1 until you get to the end of the row.

All the blocks above is easy: keep subtracting the row width until you get to the first row.

That could look like this:

```
void ChangeButtonColors(int clickedButtonIndex, int numColumns) {

    // Integer division truncates toward zero.
    int startOfRow = (clickedButtonIndex / numColumns) * numColumns;
    int startOfNextRow = startOfRow + numColumns;

    // Walk across the row, starting at the clicked button and moving right
    // one at a time until we run off the end of the row.
    for (int i = clickedButtonIndex; i < startOfNextRow; i++) {
        // Walk up the column of buttons above this one, moving up
        // a row at a time until we go into the negatives (past the first row).
        for (int j = i; j >= 0; j -= numColumns) {
            buttons[j].Color = chosenColor;
        }
    }
}

```

---
Tags: java, algorithm
---


# Question
Title: Calculate index of bottom left block on a mxn grid
I am working on a board game that requires me to color the bottom left corner of the board with random number of rows and columns a different color from the other blocks. Given an m x n grid, how do I calculate the index of the bottom left block? On a 4x4 block, the index is 12, on a 3x3 block the index 6, on a 2x2 block the index is 2, on a 3x4 block the index is 8, and on a 4x3 block the index is 9. Thank you in advance for the help!

I tried the following but it colors the top left box instead of the bottom left:

```
for(int r = 0; r < numRow; r++){
              for(int c=0; c < numCol; c++){
                  if(r==numRow-1 && c==0){
                      buttons[c].setBackground(new Color(250, 0, 0));
                      buttons[c].setEnabled(false);
                  }
              }
          }

```

# Answer
> 1 votes
The numbers in the leftmost column are all multiples of your column count. Taking your 4x3 case as an example:

```
0  1  2
3  4  5
6  7  8
9 10 11

```

The first row starts with zero, and each row after that is `numCol` more than the previous. So the leftmost number in the `n`th row is just `(n - 1)` times your column count:

```
int bottomLeft = numCol * (numRow - 1);

```

Draw a few tables of different sizes to convince yourself that this always matches the bottom-left number.

---
Tags: java, algorithm
---


# Question
Title: Determine line that threw an Exception using Android Logcat
I just installed Android logcat to debug my game from Unity's package manager. I don't fully understand how it works or in what order the logs are shown relative to my code.

The problem I have is that my game works perfectly fine without any errors on the Unity editor, but when testing it on my build, it doesn't work as expected.

When I used the Android Logcat to see what's wrong, it turns out that one of my code's functions does not fully execute (it stops halfway through), and at that point there is a `NullReferenceException` error. But how do I identify the exact line of code the error comes from?

Here's a screenshot of my logcat:

EDIT: Here is the method that calls `GameEnvironment.ObstacleSpawnPoints()`

```
if (CurrentLevel().Equals(1) || levelData.Environment.ObstacleSpawnPoints().IsNullOrEmpty()) return;

    int numberOfObstaclesToSpawn = levelData.Environment.ObstacleSpawnPoints().Length;

    for (int i = 0; i < numberOfObstaclesToSpawn; i++)
    {
        int tagIndex = UnityEngine.Random.Range(0, levelData.Environment.ObstaclePoolTags().Length);
        levelData.m_ObjectPooler.SpawnFromPool(levelData.Environment.ObstaclePoolTags()[tagIndex], levelData.Environment.ObstacleSpawnPoints()[i].position, Quaternion.identity);
    }

```

This is `GameEnvironment.ObstacleSpawnPoints()`

```
public Transform[] ObstacleSpawnPoints()
{
    if (properties.ObstacleSpawnPoints.Equals(null)) return null;
    Transform[] spawnPoints = new Transform[properties.ObstacleSpawnPoints.childCount];
    for (int i = 0; i < spawnPoints.Length; i++)
        spawnPoints[i] = properties.ObstacleSpawnPoints.GetChild(i);
    return spawnPoints;
}

```

# Answer
There's only one thing that could possibly be null in this code, so you don't need to get the line number from Logcat.

`spawnPoints` cannot be null because we define and assign it inside this method itself. So the only thing we access that could possibly throw a `NullReferenceException` is `properties.ObstacleSpawnPoints`.

"But I check whether that's null before using it!"

No, you don't. You try to use it to check whether it itself is null.

`.Equals()` is a member function. To invoke a member function, you need a valid instance to call it on. If you have a null, this is not a valid instance and will fail.

Consider making your null check `if (properties.ObstacleSpawnPoints == null)` instead.

Or, consider structuring your code so that `properties.ObstacleSpawnPoints` cannot be null when this code is called. We'd need to see more of your code to advise on how it's ending up null in the first place though.
> 0 votes

# Answer
You can get the line number of a C# Exception when you build with IL2CPP when using Sentry's SDK: https://docs.sentry.io/platforms/unity/configuration/il2cpp/

The line number will show up on Sentry's dashboard (not on logcat) because it requires the server to process the stack trace with the debug symbols that it collects during build time.

But that means you'll get legible stack traces and line numbers on your production game. From your real users.
> 0 votes

---
Tags: unity, c#, android, debugging
---


# Question
Title: Getting a list of all supported characters in a Font
I am attempting to create my own font fallback system for multilanguage support using UI Toolkit in Unity (Label class). This UI system does not intrinsically support fallback fonts.

I have some stylized English fonts I like which will be primary my first choice for some purposes. I want to make a list of all the unicode/regular characters in each of those fonts.

Then when I try to update a Label with a new string, I want to test the string to make sure it doesn't have any characters outside the list supported by the intended "stylized" English Font. ie. Test each character of the new string against my lists of supported characters.

If the new string has a character outside that list, I will instead assign a more generic backup font which covers most of the full Unicode range.

I see a script here for creating lists of glyphs within a font:

https://stackoverflow.com/questions/61573165/how-to-get-all-unicode-characters-supported-by-fonts

However, I cannot use it in Unity as it seems to rely on System.Windows.Media which is not available in my Visual Studio from Unity.

Is there any default way of doing this for a given Font that you have loaded into Unity? Thanks.

# Answer
> 2 votes
See Font-characterInfo.

```
var font = Resources.Load<Font>("the path of your font file under Assets dir");
foreach (var item in font.characterInfo)
{
    Debug.Log(item.index);//unicode value
}

```

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


# Question
Title: Why does setting blend mode in Unity shader graph to Multiply create artifacts on sprite?
I want my sprite to use a blend mode based on the background (like in Adobe programs) so I set shader graph blend mode to Multiply. The blend works, but I get strange artifacts on my sprite.

In this picture, you can see how sprite looks in scene, the graph, preview, and sprite settings.

Here is my texture:

# Answer
Lerp the colour to white in the transparent areas.

Multiplying by white (1) is the same as doing nothing at all, so this mimics traditional alpha transparency.

It appears that the alpha value is ignored by default in the multiply blend mode, so this change bakes the effect into the colour channel instead.
> 2 votes

---
Tags: unity, alpha-blending, unity-shader-graph
---


# Question
Title: Where should I design skeletons and animations?
I have just finished a course on Unreal Engine 5, where I have been introduced to managing animations through skeletons and different meshes.

My question is, where should I design such animations? Are skeletons and animations designed with external software, such as Blender, and then imported to Unreal Engine, or are these things created later with Unreal once I have a general design of the character from Blender?

Maybe the question is really basic, but I'm not sure which of those options is better or if it doesn't matter at all. Thanks in advance.

# Answer
> 2 votes
Typically you'd create your character model, add a skeleton, rig the model, and create animations all in external software like Blender or Maya.

However, Epic has been extending Unreal's built-in capabilities in these areas. In particular, you can now use control rig and sequencer to create and edit animation sequences in-engine. There's actually a new editor mode just for this in UE5: https://docs.unrealengine.com/5.0/en-US/animation-editor-mode-in-unreal-engine/

Unreal also has some 3D modeling capabilities, but I don't think you can rig your models with a skeleton in the editor just yet.

---
Tags: animation, blender, unreal, skeletal-animation
---


# Question
Title: I have set my animation to play when the player enters a set area a through script but it's not playing
I have set my animation to play through a script I made but it's not playing. I have all the references correct my spelling is correct as well. My code:

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

public class AnimationTrigger : MonoBehaviour
{
    [SerializeField] private Animator myDoor;
    [SerializeField] private string DoorOpen = "DoorOpen";

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Player"))
        {
            myDoor.Play(DoorOpen, 0, 0.0f);
            Debug.Log("Animation Played");
        }
    }

}

```

Picture of my animator window:

# Answer
See Animator.Play.

> When you specify a state name, or the string used to generate a hash, **it should include the name of the parent layer**. For example, if you have a Bounce state in the Base Layer, the name is Base Layer.Bounce.

So try this:

```
[SerializeField] private string DoorOpen = "Base Layer.DoorOpen";

```

\*Playing the animation directly is not recommended, you can try to control the parameters to let the animation state machine control the animation playing.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: Component instance reference in Unreal Engine 4
I'm creating a C++ script and I want to get a reference to a component instance.

For example, imagine that I want to get the player camera, which is a `UCameraComponent`. I would create a `UPROPERTY` like this:

```
 UPROPERTY(EditAnywhere, meta = (AllowPrivateAccess = "true"))
 class UCameraComponent* PlayerCamera;

```

However, I can't assign it in the editor details panel like I would in Unity. I would expect to be able to drag and drop a Component from an Actor on the World Outline to this property but it seems that's not possible. Moreover, when clicking on the dropdown in the details panel, I don't have any available to choose from.

From what I learned, it just isn't possible to do it this way and the Unreal way is to create a `UPROPERTY` to store a reference to the Actor and then get the component in runtime. Although this might work for most cases, it's still a bit memory inefficient since you might not need the Actor reference after getting the Component (yes, I know it's just a pointer, but still...). Plus, how would you handle multiple components of the same class in the same actor? I assume you have to loop over them and try to find the one you want, based on *a priori* knowledge of their order in the hierarchy or based on some of their known properties (maybe with tags)...

All of this seems kind of messy, so I ask you to please shed some light on what's the (best) Unreal workflow for setting component references.

# Answer
To do this in Unreal C++, inside the CPP file you need to do the following:

Make sure to include the header component:

**#include "Camera/CameraComponent.h"**

Then in the class constructor:

**CameraComponent = CreateDefaultSubobject \<UCameraComponent\>("CameraComponent");**

From here you need to set up the attachment which is usually to the mesh if it's a character but can be attached to anything.

**CameraComponent-\>SetUpAttachment(GetMesh());**
> 2 votes

# Answer
I come from Unity as well. The best I've come up with so far is to assign the variable in the construction script of the blueprint.
> 0 votes

---
Tags: unreal-4, unreal, component-based, serialization, entity-component-system
---


# Question
Title: XAudio2 mono source played as a 3D sound is heard only in right speaker, regardless of distance and position
I am having problem setting up a 3D space sound effect in XAudio2. The sound effect that I am using is mono but the result is playing constantly, irrelevant from the distance and positioning of the listener and emitter, always on right channel. Here is the code of the play sound effect function:

```
void SoundSystem::Channel::PlaySoundEffect(Sound& s, float pitch, float volume)
{
    assert(pSource && !pSound);

    s.AddChannel(*this);

    XAUDIO2_VOICE_DETAILS details;
    SoundSystem::Get().pMaster->GetVoiceDetails(&details);

    X3DAUDIO_DSP_SETTINGS DSPSettings = { 0 };
    FLOAT32* matrix = new FLOAT32[details.InputChannels];
    DSPSettings.SrcChannelCount = s.mFormat.nChannels;
    DSPSettings.DstChannelCount = details.InputChannels;
    DSPSettings.pMatrixCoefficients = matrix;

    X3DAudioCalculate(SoundSystem::Get().X3DInstance, &SoundSystem::Get().Listener, &s.Emitter,
        X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_DOPPLER
        | X3DAUDIO_CALCULATE_LPF_DIRECT | X3DAUDIO_CALCULATE_LPF_REVERB
        | X3DAUDIO_CALCULATE_REVERB,
        &DSPSettings);

    pSound = &s;
    xaBuffer.pAudioData = s.pData.get();
    xaBuffer.AudioBytes = s.nBytes;
    pSource->SubmitSourceBuffer(&xaBuffer, nullptr);

    // Apply X3DAudio generated DSP settings to XAudio2
    pSource->SetFrequencyRatio(DSPSettings.DopplerFactor);
    pSource->SetOutputMatrix(SoundSystem::Get().pMaster, s.mFormat.nChannels, details.InputChannels, DSPSettings.pMatrixCoefficients);
    pSource->SetOutputMatrix(SoundSystem::Get().pMaster, 1, 1, &DSPSettings.ReverbLevel);
    XAUDIO2_FILTER_PARAMETERS FilterParametersDirect = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI / 6.0f * DSPSettings.LPFDirectCoefficient), 1.0f }; // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here
    pSource->SetOutputFilterParameters(SoundSystem::Get().pMaster, &FilterParametersDirect);
    XAUDIO2_FILTER_PARAMETERS FilterParametersReverb = { LowPassFilter, 2.0f * sinf(X3DAUDIO_PI / 6.0f * DSPSettings.LPFReverbCoefficient), 1.0f }; // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here
    pSource->SetOutputFilterParameters(SoundSystem::Get().pMaster, &FilterParametersReverb);

    pSource->Start();
}

```

Here is the Listener:

```
void SetListener(const glm::vec3& front, const glm::vec3& up, const glm::vec3& position, const glm::vec3& velocity) {
    Listener.OrientFront = { front.x, front.y, -front.z };
    Listener.OrientTop = { up.x, up.y, -up.z };
    Listener.Position = { position.x, position.y, -position.z };
    Listener.Velocity = { velocity.x, velocity.y, -velocity.z };
}

```

And here is the emitter:

```
void SetEmitter(const glm::vec3& front, const glm::vec3& up, const glm::vec3& position, const glm::vec3& velocity) {
    Emitter.OrientFront = { front.x, front.y, -front.z };
    Emitter.OrientTop = { up.x, up.y, -up.z };
    Emitter.Position = { position.x, position.y, -position.z };
    Emitter.Velocity = { velocity.x, velocity.y, -velocity.z };

    Emitter.pCone->InnerAngle = 0.0f;
    // Setting the inner cone angles to X3DAUDIO_2PI and
    // outer cone other than 0 causes
    // the emitter to act like a point emitter using the
    // INNER cone settings only.
    Emitter.pCone->OuterAngle = 0.0f;
    // Setting the outer cone angles to zero causes
    // the emitter to act like a point emitter using the
    // OUTER cone settings only.
    Emitter.pCone->InnerVolume = 0.0f;
    Emitter.pCone->OuterVolume = 1.0f;
    Emitter.pCone->InnerLPF = 0.0f;
    Emitter.pCone->OuterLPF = 1.0f;
    Emitter.pCone->InnerReverb = 0.0f;
    Emitter.pCone->OuterReverb = 1.0f;

    Emitter.CurveDistanceScaler = 1.f;
}

```

Note that I am using OpenGL as the graphics API and have a right handed coordinate system so I negate the z component. Anything that I am doing wrong and have the sound only on one speaker and in full volume? Thanks in advance

# Answer
> 1 votes
The solution was to remove the line :

> pSource-\>SetOutputMatrix(SoundSystem::Get().pMaster, 1, 1, &DSPSettings.ReverbLevel);

and everything worked out great. For anyone who is struggling with this.

---
Tags: xaudio2
---


# Question
Title: How to programmatically activate the Glow option in a Text Mesh Pro font
I can activate the Glow setting for a Font in Text Mesh Pro by checking the Glow checkbox:

Is there a way I can programmatically do the same thing? I looked in the corresponding shader, and found what I think is the name of the variable: GLOW\_ON. But when I tried to set that variable to 1 using Material Set Float and Set Int, neither one worked. Either I have the wrong variable name, or I'm not setting it the proper way.

Any suggestions on how to programmatically activate the Glow option in a Text Mesh Pro font?

# Answer
> 5 votes
This is a shader variant using `#pragma shader_feature`, See SL-MultipleProgramVariants.

"*TextMeshPro/Mobile/Distance Field*":

```
#pragma shader_feature __ GLOW_ON
...
#ifdef GLOW_ON
...
#endif

```

So use Material.EnableKeyword(and DisableKeyword) in C# code:

```
material.EnableKeyword("GLOW_ON");
material.DisableKeyword("GLOW_ON");

```

And,

> The version of this function that takes a string as a parameter is slower than the version that takes a LocalKeyword. If you call this function more than once, it is best practice to create a LocalKeyword struct, cache it, and use that.

---
Tags: unity, text-mesh-pro
---


# Question
Title: Rectangular Collision Resolution behaving incorrectly on corners
I'm currently writing a simple game engine and encountered an error while trying to resolve rectangular collisions. When an object moves diagonally and collides with a solid object I only correct it in the axis that would require less translation to resolve the collision. The problem with this is that when a diagonally moving object travels "over" a corner the smaller axis flips to the opposite axis before the two objects stop colliding and the non-solid object "teleports" to fix itself.

Here's a piece of the collision resolution method (c++):

```
/*
    0: UP
    1: UP RIGHT
    2: RIGHT
    3: DOWN RIGHT
    4: DOWN
    5: DOWN LEFT
    6: LEFT
    7: UP LEFT
*/
switch(lastDir){
    case 0:
    {
        rect.y = (other->rect.y+other->rect.height)+fixed(0.0078125);
        //0.007 is padding amount, fixed is fixed point number class due to hardware constraints, rect is rectangle with x, y, width, height
        break;
    }

    case 1:
    {
        fPoint l1(rect.x, rect.y); //fPoint is Point using fixed
        fPoint r1(rect.x+rect.width, rect.y+rect.height);
        fPoint l2(other->rect.x, other->rect.y);
        fPoint r2(other->rect.x+other->rect.width, other->rect.y+other->rect.height);
        fixed distX = abs(min(r1.x, r2.x)- max(l1.x, l2.x));
        fixed distY = abs(min(r1.y, r2.y) - max(l1.y, l2.y));

        if(distX > distY){
            //if y is shorter correct y
            rect.y = (other->rect.y-rect.height)-fixed(0.0078125);
        }
        else if(distY > distX){
            //if x is shorter correct x
            rect.x = (other->rect.x-rect.width)-fixed(0.0078125);
        }
        break;
    }

    case 2:
    {
            rect.x = (other->rect.x-rect.width)-fixed(0.0078125);
            break;
    }
//continues for directions 3-7
}

```

# Answer
> 0 votes
Not exactly a solution to this problem, but I solved my problem by changing to a different resolution method. In my new one we check to see if our previous tick was within the width or height range of the solid object and then continuously correct based on that.

---
Tags: c++, 2d, collision-detection, movement, collision-resolution
---


title: Passing callback to animation function?

text:
# Question
Title: Passing callback to animation function?
I have the following class that animates a 'fade to black' effect:

```
#pragma once
#include <SDL.h>

class Renderer {
public:
    explicit Renderer(SDL_Renderer *renderer) : renderer(renderer) {}

    void Update(double deltaTime) {
        this->dt = deltaTime;
    };

    void Render() {
        if (fadeout) {
            fadeValue += secondeSteps*dt;

            if (fadeValue > 255) {
                fadeValue = 255;
                fadeout = false;
                //callback?
            }
            SDL_SetRenderDrawColor(renderer, 0,0,0, (int)fadeValue);
            SDL_RenderFillRect(renderer, &screen);
        }
    };

    void FadeOut(SDL_Rect rect, int duration = 1500) {
        fadeout = true;
        secondeSteps = (255.0f/duration)*1000; // opacity change per seconde
        screen = rect;
    }

private:
    float fadeValue {};
    float secondeSteps{};
    bool fadeout = false;
    SDL_Rect screen;
    double dt;
    SDL_Renderer *renderer;
};

```

It is run every frame until a desired value is reached, and then a flag is set to indicate we are done (`fadeout = false;`).

But what I would like is to pass a callback, so that after the effect is done, something like a GameState is changed to a new value, like this:

`gameRenderer->FadeOut(SDL_Rect{0,0,windowWidth,windowHeight}, GameState::STATE_LOAD);`

Right now, the `Renderer` class is a `unique_ptr` inside my `Game` class, but has no knowledge of the Game object itself.

I've seen many suggestions about using Lambdas or passing function pointers, but I'm not sure what to pick, and what is the most modern solution for,say, c++ compiler 20. There's also async (https://en.cppreference.com/w/cpp/thread/async) functions, could that be useful in this scenario here as well?

Or maybe it's just as easy as passing the current instance of my `Game` to the `Renderer` class? That seems kind of messy.

Would gladly hear some suggestions about how to approach this.

# Answer
I found a solution that works, using Lambda functions..if anybody can add some additional background as to what is happening, or has a better solution, I'll pick that as the answer.

Adding argument to the FadeOut:

```
bool FadeOut(SDL_Rect rect, const std::function<void()> &f, int duration = 1500) {

```

Calling the FadeOut with a Lambda:

```
gameRenderer->FadeOut
    (SDL_Rect{0,0,windowWidth,windowHeight},
    // less_than
     [&]() {
         ChangeState(GameState::STATE_LOAD);
     }
);

```
> 0 votes

---
Tags: c++
---


# Question
Title: Line-of-sight algorithm for tile-based tactics
I've tried Bresenham line and Raycasting, but they don't quite give the results I need (examples in the screenshot).

'&' - character

'+' - cells that can be attacked by the character

'#' - walls

Supercover:

Bresenham:

As can be seen in the screenshot, a character can attack a cell, but if moved to it, it cannot attack from there to its original position.

Is there a fair algorithm so that a character who can attack an enemy can be attacked by the enemy in return.

Perhaps the problem is in my code?

```
void FieldOfSight(Field &field, const Vector2i &player, float distance,
                  int type)
{
    Vector2i endPosition;
    float    radians = 0;
    float    step    = M_PI / (distance * 10);

    while (radians < 2 * M_PI) {
        endPosition.x = player.x + round(cos(radians) * (distance));
        endPosition.y = player.y + round(sin(radians) * (distance));
        if (endPosition.y >= field.GetHeight())
            endPosition.y = field.GetHeight() - 1;
        else if (endPosition.y <= 0)
            endPosition.y = 0;
        if (endPosition.x >= field.GetWidth())
            endPosition.x = field.GetWidth() - 1;
        else if (endPosition.x <= 0)
            endPosition.x = 0;
        radians += step;

        switch (type) {
        case (0):
            SupercoverLine(field, player, endPosition);
            break;
        case (1):
            WalkLine(field, player, endPosition);
            break;
        case (2):
            BresenhamLine(field, player, endPosition);
            break;
        }
    }
}

void SupercoverLine(Field &field, int x0, int y0, int x1, int y1)
{
    int dx = x1 - x0, dy = y1 - y0;
    int nx = abs(dx), ny = abs(dy);
    int sign_x = dx > 0 ? 1 : -1, sign_y = dy > 0 ? 1 : -1;

    int px = x0, py = y0;

    field.SetFG(px, py, 8);

    for (int ix = 0, iy = 0; ix < nx || iy < ny;) {
        int decision = (1 + 2 * ix) * ny - (1 + 2 * iy) * nx;
        if (decision == 0) {
            px += sign_x;
            py += sign_y;
            if (field[py - sign_y][px] == 1 && field[py][px - sign_x] == 1)
                break;
            ++ix;
            ++iy;
        } else if (decision < 0) {
            px += sign_x;
            ++ix;
        } else {
            py += sign_y;
            ++iy;
        }
        if (sqrt((x0 - px) * (x0 - px) + (y0 - py) * (y0 - py)) > 5 ||
            field[py][px] == 1)
            break;
        field.SetFG(px, py, 8);
    }
}

void WalkLine(Field &field, int x0, int y0, int x1, int y1)
{
    int dx = x1 - x0, dy = y1 - y0;
    int nx = abs(dx), ny = abs(dy);
    int sign_x = dx > 0 ? 1 : -1, sign_y = dy > 0 ? 1 : -1;

    int px = x0, py = y0;
    for (int ix = 0, iy = 0; ix < nx || iy < ny;) {
        if ((0.5 + ix) / nx < (0.5 + iy) / ny) {
            px += sign_x;
            ix++;
        } else {
            py += sign_y;
            iy++;
        }
        if (sqrt((x0 - px) * (x0 - px) + (y0 - py) * (y0 - py)) > 5 ||
            field[py][px] == 1)
            break;
        field.SetFG(px, py, 8);
    }
}

void BresenhamLine(Field &field, int x0, int y0, int x1, int y1)
{
    int dx    = abs(x1 - x0);
    int sx    = x0 < x1 ? 1 : -1;
    int dy    = -abs(y1 - y0);
    int sy    = y0 < y1 ? 1 : -1;
    int error = dx + dy;
    int x = x0, y = y0;

    field.SetFG(x0, y0, 8);

    while (true) {
        if (x0 == x1 && y0 == y1)
            break;

        int e2 = 2 * error;

        if (e2 >= dy) {
            if (x == x1)
                break;
            error += dy;
            x += sx;
        }
        if (e2 <= dx) {
            if (y == y1)
                break;
            error += dx;
            y += sy;
        }

        if ((field[y - sy][x] == 1 && field[y][x - sx] == 1) ||
            sqrt((x0 - x) * (x0 - x) + (y0 - y) * (y0 - y)) > 5 ||
            field[y][x] == 1)
            break;
        field.SetFG(x, y, 8);
    }
}

```

Sorry for the code without comments

# Answer
> 1 votes
As the answer by Tim C explained, it's not possible in a tile-based world to guarantee that a character who can see a tile can also see it from any point which counts as part of that line-of-sight. The reason is that tiles don't offer sufficient resolution. You would need floating-point positions for that to work.

But if you want fairness in the sense that "if A can attack B, then B can attack A", then one solution would be to calculate both the sight-line from A to B and then from B to A, and only consider it unbroken if both are unbroken (or if one of them is unbroken, if you want to be more liberal).

What you can also do to fake a higher resolution for sightline calculation is to use floating-point-precision raycasting, but not just cast the rays from the center of the character. Cast rays from multiple points of the character, and cast them to multiple points on the target.

In this example, I am using 3 points per character and calculate 9 lines of sight of which 4 connect and 5 are broken. The more points you use, the more accurate and predictable the results. The computational cost increases quadratically with the amount of points you sample, but in case of a turn-based game on modern hardware, that should not be too much of a problem.

You can also use this method to *quantify* visibility. For example, in this case you could say that 9/5 obstructed lines of sight means that the target is 56% in cover, and feed that information into your combat or stealth mechanics.

# Answer
> 3 votes
This is a partial answer. I can explain the cause of the problem you're seeing, but I don't have any proposal to fix it.

# Subsets of valid sightlights are not guaranteed to be valid sightlines

This is, I think, the property that's causing you trouble (and resulting in your asymmetry). I'll illustrate with a diagram.

Consider a line pointing 9 tiles to the right, and 1 square up:

```
##########
.....xxxxx
@xxxx.....
##########

```

Now add a wall right before the crossover point. Walking through the supercover algorithm, this line of sight is still valid. `decision` is exactly 0 at the crossover point (nx = 9, ny = 1, ix = 4, iy = 0), so it will make the diagonal step.

```
##########
....#xxxxx
@xxxx.....
##########

```

However, the following, shorter sightline is **not** valid, despite being a subset of the other sightlight.

```
##########
....#x....
@xxxx.....
##########

```

## Why does this matter?

These algorithms are symmetric end-to-end. If you can see an endpoint, the endpoint can see you. However, there is no guarantee that every point *along* that sightline can see you. For example, in the following

```
##########
....#@...b
a.........
##########

```

The Supercover algorithm will not allow any sightline from `@` to reach `a`, even though `a` can see `@` through its sightline to `b`

I believe this is the reason you are seeing the behavior that you are.

Described mathematically, "You can see a space if you can draw a line from the center of your space to the center of another space, which *passes through any part* of the intervening space." If you take this to the limit as vision range increases, the meaningfulness of the distant target space falls away and the definition becomes result would be, "You can see a space if you can draw a line from the *center* of your space to *any part* of the target space"

Because your sight-lines are from the center, but you allow visibility by even the smallest corner, the result will be asymmetric visibility even when using symmetric line-rasterizing algorithms.

---
Tags: c++, 2d, raycasting, line-of-sight
---


# Question
Title: How do I accomplish viewing a 2D game board in 3D space?
So I'm making a 2D board game in 3D space and I don't want to use paper2D because I'm not really using sprites.

What I want is to be able to make a grid of cubes positioned such that I can have a camera facing the grid and it will only show the one face of all the cubes. The idea is that to the player it will just look like a 2D board.

The problem I'm having is, If I make a Cube and move it up/down/left/right, the Camera sees more than just one face despite it being manually positioned to be looking head on at the cube.

So then I remembered that I probably want an orthographic view, so I set the camera to that and unfortunately its just wireframe.

**So my question is, how do I accomplish this? Does UE5 not support this kind of thing at all?**

# Answer
This may be the same as other reported errors with UE5 ortho camera preview:

> ...the Orthographic camera seems to be only outputting wireframes in preview mode…I did a verify and a full reinstall and this issue is still here. Further I initiated a camera shake when damage is taken which for SOME reason outputs flashing lights as opposed to JUST a camera shake.
>
> When I switch the camera to perspective and apply damage the Camera shake works as normal.

Some similar problems were reported and verified in UE4, but have yet to be resolved. It was initially reported in April 2014 and reportedly still broken in August 2020.

It's possible someone else will know of & post a workaround; just because I didn't happen to find one doesn't mean it doesn't exist. Theoretically, if the final rendering is fine, you could just put up with it in preview mode & use intermittent release quality builds to judge the visuals. Up voting &/or posting the issue on the forum might help signal to the developers that this is something you would like them to prioritize.
> 1 votes

---
Tags: 2d, 3d, camera, unreal-5
---


title: Using native SDK's inside Unity

text:
# Question
Title: Using native SDK's inside Unity
First of all, I would like to point out that I am not a Unity developer. Most of the programming is related to web programming, but my friends and I set out to create an MVP of one product inside Unity, but unfortunately we can't find any real help, because we get thousands of different information.

We would like to connect a sensor - an accelerometer with an nRF52 chip to Unity, which would serve as a control device. The sensors we bought have iOS/Android native SDKs, but unfortunately they do not support Unity. That's why I'm interested in what would be the fastest and most cost-effective solution. Can native SDKs be used within Unity?

# Answer
In the past I have created separate programs to run in the background that interface with sensors or other hardware. These separate programs communicate with my unity program through UDP or TCP sockets, streaming data.

So the unity program tries to connect to the sensor program. And if successful, it opens a new thread that writes the streaming data to a data object in a thread safe manner. The unity main thread can then read from this data object every frame.

This is obviously a bit of a workaround compared to importing a library directly, but I’ve found it worked great for cases where sensors had python or otherwise incompatible SDKs. Might also work in your case if you can’t import the DLLs into your project. The lag on a localhost Connection is negligible compared to the time of a frame (usually around 16ms).
> 1 votes

---
Tags: unity, input
---


# Question
Title: Rotate 'left' from the perspective of the space ship
I'm stuck on the following math problem for my game project. I have a space ship which position and orientation is saved in the following class:

*(The examples are in C# using types from the System.Numerics namespace)*

```
class Transform
{
  Quaternion Rotation;
  Vector3 Position;
}

```

If I want to move the space ship forward, as seen from the reference frame (perspective) of the space ship I can do the following

```
transform.Position += Vector3.Transform(new Vector3(0, 0, -1), Rotation);

```

If I want to turn my space ship left (yaw 90 degrees counter clockwise). I could do:

```
var relativeUp = Vector3.Transform(new Vector3(0, 1, 0), Rotation);
var rotation = Quaternion.CreateFromAxisAngle(relativeUp, PI / 2);
transform.Rotation = rotation * transform.Rotation;

```

But I want to write this method:

```
void RotateInReferenceFrame(Quaternion q);

```

Where the input quaternion `q` is constructed as `Quaternion.CreateFromYawPitchRoll((PI/2, 0, 0)` (so unaware of the current orientation of the space ship) but the resulting rotation is done in the reference frame of the space ship (so the result is the same as the 2 step example above).

Is this possible?

# Answer
DMGregory is absolutely right, but I had an error in my unit tests that put me on the wrong path. The following code is correct.

```
using System.Numerics;

readonly struct Transform
{
    readonly Vector3 Position;
    readonly Quaternion Rotation;

    Quaternion Rotate(Quaternion offset)
    {
        return  Quaternion.Multiply(offset, this.GetRotation());
    }

    Quaternion RotateInLocalReferenceFrame(Quaternion offset)
    {
        return Quaternion.Multiply(this.GetRotation(), offset);
    }

    Vector3 GetForward()
    {
        return Vector3.Transform(-Vector3.UnitZ, this.Rotation);
    }
}

```

The behavior makes sense when seen from a simple smoke test

```
using static Xunit.Assert;

class TransformTests
{
    [Fact]
    public void SmokeTest()
    {
        Transform t = default;

        // Rolling the ship counter clockwise makes the nose point up
        t = t.RotateInLocalReferenceFrame(Quaternion.CreateFromYawPitchRoll(0, MathF.PI / 2, 0));
        // Helper method that checks if all the elements of a vector are within 0.001 of the expected value
        AlmostEqual(new Vector3(0, 1, 0), t.GetForward());

        // Yawing the ship in a local reference frame makes the nose point left. If this was done from
        // a global reference frame this would not have changed where the nose points.
        t = t.RotateLocalInReferenceFrame(Quaternion.CreateFromYawPitchRoll(MathF.PI / 2, 0, 0));
        AlmostEqual(new Vector3(-1, 0, 0), t.GetForward());

        // Rolling the ship in a gobal reference makes the nose point down. If this was done from
        // a local reference frame this would not have changed where the nose points
        t = t.Rotate(Quaternion.CreateFromYawPitchRoll(0, 0, MathF.PI / 2));
        AlmostEqual(new Vector3(0, -1, 0), t.GetForward());
    }
}

```
> 1 votes

---
Tags: c#, rotation, quaternion
---


# Question
Title: Rotating a command relative to the body of a drone
Suppose you have a drone the shape of a cube with rotors on each face, it's completely unable to control its roll-pitch-yaw, but it can accelerate along any of its 3D orthogonal vectors (see image below). However, there's also a gravitational force that accelerates the drone down in the -Z axis of the world frame.

**Given the quaternion representing the rotation of the drone, how would you construct a command such that it eliminates the acceleration caused by gravity?** This command is applied along the drone's orthogonal vectors in the form \[x,y,z\]. For the sake of this question let's say the vector that completely opposes gravity is given as \[0,0,1\] in the world frame.

Just to clarify what I mean by "command", if the drone was completely aligned with the world axis the command needed to counteract gravity would just be \[0,0,1\]. If the drone was rotated forward such that it's +Z-axis is aligned with the world's +X-axis and the drone's +X-axis is aligned with the world's -Z-axis (see image above) the command needed would be \[-1,0,0\].

For my approach, which obviously isn't working, I tried solving this by rotating the vector \[0,0,1\] by the quaternion with rotquat(vec(0,0,1,0),Q) in the following lua code:

```
vec = function(x,y,z,w) return {x=x,y=y,z=z,w=w} end

function mquat(Q,R)
    return vec(
    R.w*Q.x+R.x*Q.w-R.y*Q.z+R.z*Q.y,
    R.w*Q.y+R.x*Q.z+R.y*Q.w-R.z*Q.x,
    R.w*Q.z-R.x*Q.y+R.y*Q.x+R.z*Q.w,
    R.w*Q.w-R.x*Q.x-R.y*Q.y-R.z*Q.z)
end

function rotquat(V,Q)
  return mquat(mquat(Q,V),vec(-Q.x,-Q.y,-Q.z,Q.w))
end

```

This kind've works for the first few seconds, the commands are applied perfectly along the world +z-axis. However, as the drone begins to naturally rotate the commands slowly shift off the +z-axis and it zips off in the wrong direction.

Any ideas on what I should do to fix this?

# Answer
I've adapted some of my code that helps me make objects face in a certain direction. If I didn't make any errors translating it, it should work.

```
var currentUp = drone.Up; // the current up vector for your drone
var desiredUp = ... // The up vector that you would like to have

var dot = Vector3.Dot(currentUp, desiredUp);
if (Math.Abs(dot + 1.0f) < 0.000001f)
{
    // vector a and b point exactly in the opposite direction,
    // so it is a 180 degrees turn around the x-axis (or z-axis if you prefer)
    return new Quaternion(new Vector3(-1, 0, 0), PI);
}
if (Math.Abs(dot - 1.0f) < 0.000001f)
{
    // vector a and b point exactly in the same direction
    // so we return the identity quaternion
    return Quaternion.Identity;
}

// The cross product gives us a vector perpendicular to the two vectors
var axis = Vector3.Normalize(Vector3.Cross(currentForward, desiredForward));

// The dot product gives us the distance we need to rotate over that axis
var angle = Math.Acos(dot);

var rotation = Quaternion.CreateFromAxisAngle(rotAxis, rotAngle);

drone.Quaternion = rotation * drone.Quaternion;

```

In some cases this rotation leads to unwanted rotations over other axes. (For example a reorientation that you as a pilot would solve by yawing includes an unnecessary roll. If you want to you can use a different method to create a **constrained** rotation. Basically it rotates without going over the specified axis.

```
var currentUp = drone.Up; // the current up vector for your drone
var desiredUp = ... // The up vector that you would like to have
var locked = ... // A vector that should stay roughly the same during the rotation

var dot = Vector3.Dot(Vector3.Normalize(target - this.Position), locked);

if (Math.Abs(dot) < 0.99f)
{
    var matrix = Matrix4x4.CreateLookAt(drone.Position, target, locked);
    if (Matrix4x4.Invert(matrix, out var inverted))
    {
        var quaternion = Quaternion.CreateFromRotationMatrix(inverted);
        drone.Quaternion = quaternion;
    }
}

```

Note that this might mean that the drone will not always be able to right itself if you're not clever in picking the locked axis.

Hope this helps, a word of caution, all this code was adapted from my original code that does this for the forward vector instead of up vector. Quaternions ara black magic, so I might have made a mistake.
> 0 votes

---
Tags: movement, vector, quaternion
---


# Question
Title: better way to store user purchase information?
I use Player Prefs to store the user purchase information in Android and iOS, but I'm not sure it's safe enough. What is the right or better way to store user purchase information?

```
public void OnPurchaseComplete(Product product)
    {
        if (product.definition.id == purchaseid)
        {
            PlayerPrefs.SetInt("iap", 1);
        }
    }

```

# Answer
No, PlayerPrefs are not safe, because it's well-documented where Unity stores them and with that knowledge it's trivial for any player who has a basic technical understanding of their operating system to edit that information.

But **any** form of data storage on the user's device is unsafe. If your game can read and write that information, then so can any other program. Encryption won't help either, because in order to encrypt and decrypt the information, your game needs to contain both the algorithm and the key, which a determined hacker can find, extract and put into their own cheating tool.

The only real solution is to store this data server-sided. Either on a server you control, or by using the purchase verification functionality of the platform you use for IAP.
> 3 votes

---
Tags: unity
---


# Question
Title: How can I make text-based combat more engaging?
I'm making a text based adventure in Java, and currently I have a fairly limited combat system where you can do one of 3 things:

1. attack with your sword
2. attack with magic(if its unlocked)
3. drink a health potion

This system works but is fairly boring and uninspired. I want to make the combat enjoyable yet given the limitations of a text based game, but I don't know how to accomplish this. If anyone knows how to make this system more engaging/fun, it would be greatly appreciated.

# Answer
Basically, you are looking for ways to improve the player's choices; the ways to do that are to make the choices more interesting &/or meaningful. By meaningful, I'm referring to the impact a choice has to the overall experience. Without knowing more about the game's other systems, narrative, etc, I'm going to set aside the meaningful part as out of scope for this answer. Instead, I'm focusing on some ways to add measured uncertainty & complexity to the combat system to make it more interesting.

Based on the information presented, I suspect that there's more or less a clear strategy for combat, probably something along the lines of:

* If health is low & potion is available, drink potion
* Otherwise, select most damaging attack option

These sorts of patterns don't take long to discover & once found the game play consists of going through the motions. You've already tried a couple of solutions:

* There's a bit of push your luck regarding when to use a potion (Hmmm, how low is low?)
* Damage is randomized, which leads to a bit of anticipation (Did I roll good numbers?)

Here are some ways that you can add complexity to the system with the intent of making decisions more interesting:

* Create situation where the answer isn't always obvious:
    + An attack that damages multiple enemies a little bit vs. damaging one enemy a lot
    + An attack that does less damage now, but adds an effect like, damage over time, chance to stun, reduce enemy accuracy, etc
* Add some uncertainty to the potion system:
    + Potions degrade overtime, creating more uncertainty about when best to use them
    + Potions provide variable healing over time (up to some cap)
    + Health potions also temporarily increase player damage, thus encouraging earlier use in combat
* Create systems that encourage the player to push their luck
    + Mana points only regenerate when the player is below 50% health
    + Health potion can be cashed in for some reward (XP, stat bonus, etc)
* Create systems that reward mastery
    + Player estimates # of round combat will take, if their guess is close, they get bonus XP

It's possible to add complexity, uncertainty & encourage the player to take risks. i.e. give the potions a random number from 0-9. Potions heal more based on how closely their # matches the last digit of damage most recently dealt to the player.

Since GDSE is more about Q&A than opinions, I want to emphasize that the examples are just that. The core answer is to find ways to make the system(s) in question interesting, without making it too complex, arbitrary or inscrutable. If you need additional opinions on how to make that happen, you may need to go to GDSE chat or a gdev forum like TIG Source.
> 54 votes

# Answer
One time I played a game which had one of the best text-based 2 characters combat systems I ever played (the game was awful in every other regard, so I forgot its name):

* Each side had a number of attacks to choose from
* The damage inflicted by each attack was based on one stat of the attacker and one stat of the defender.
* Each attack caused a stat-modifying effect on the attacker and a different one on the defender. Both effects could be good or bad.
* The status effects lasted for a number of rounds. Receiving the same status effect again did *not* stack. It just reset the timer.

Why did this system offer a lot of depth?

First, it is not always obvious which attack does the most damage right now, because you have to look at the status effects currently affecting the attack-stat and the opponents defense-stat for the attack. Well, when the player completely understood the game mechanics this is just a simple calculation, but very few players will analyze your algorithms so deeply and will just make educated guesses.

Second, even if you *do* figure out the most damaging attack, you have to look at what impact its status effects have. For example, using the attack which boosts the enemies STR might be bad, but on the other hand the enemy only got one STR-based attack and that attack targets DEX, and DEX is your best stat, so it might not be that bad. The attack also boosts your INT, which sounds good, but you still have 3 rounds of INT boost left, so you might rather want to use the opportunity to get a boost for a different stat.

I am not saying that you should copy this system. What I want to say is that if you want to design a deep turn-based combat system, make sure that

1. There are many (but not overwhelmingly many) options to decide between
2. Each decision has multiple long- and short-term consequences
3. The impact of these consequences depends on previous decisions, so the ideal decision is not always obvious.
4. Most importantly, there must not be one option which is always or almost always the ideal choice.
> 15 votes

# Answer
It's often said that games are most fun when their **choices are meaningful**. If your mechanics too simple, your choices become obvious (e.g. health low -\> drink health potion), and the game becomes unengaging. One way to make choices meaningful is to make them require skills such as **observation**, **prediction** or **planning**.

A great example of this in action is *Chrono Trigger*, a JRPG with the following features and necessary skills:

* Enemies have various abilities like *regeneration*, *vulnerabilities*, *counterattacks*, such that it's not obvious which attacks should be used on which, or which order. Players need to **observe** how the enemies behave in order to formulate a strategy.
* Some enemies had *triggered vulnerabilities*, e.g. a creature has very high defense, until you hit it with a magic spell. Players need to **plan** their attacks, to trigger its vulnerability first before following up with normal attacks.
* Some enemies had *timed vulnerabilities*, so players need to **predict** when this happens, and attack accordingly.
* Players control a party of characters, and the most powerful attacks involve multiple characters attacking together. But to pull this off, those characters can't be doing something else, like healing, or using a spell to trigger an aforementioned vulnerability. Because of this *contention*, players had to **plan** their character actions in advance, so that the right characters are available together to pull off these powerful attacks.

To build on all this, the game gives you different *equipment*, throws different *enemies* and *enemy compositions* at you, and sometimes even forces you to change your *party members*, all of which affects the relative efficiency of different strategies, and how you play the game.

But this is just one example, and what *mechanics* they use isn't the important part, it's the **skills** they need the player to learn. Other examples of skills include **timing/reflexes** (typical of action games), **deduction** (puzzle games), **long-term planning** (strategy games), or **yomi** (fighting games). Focus on the skills to make a boring game into a more engaging one.
> 7 votes

# Answer
The MUD gemstone 3 had great text based combat.

Being a MUD, it had real time combat and was multiplayer.

One of the more memorable things was that it had stances. You could be defensive, neutral or offensive, and would change stances during a fight.

There was also the concept of round time for your attacks. Heavier weapons and armor (and less strength, or lack of a haste spell) meant longer round times.

So, you would have a round time of X seconds, and the thing you were fighting would have a round time of Y. (Assuming a single opponent)

Since you and your opponent could only act when your round time timer wasn't going, a good fighter would "stance dance".

The goal would be to be in offensive stance whenever you attacked, and to be in defensive stack whenever you got attacked.

You'd have to time things based on your round time and theirs.

It was pretty fun, and a good challenge of skill. Pretty nice for a text game imo.
> 7 votes

# Answer
You could make it time sensitive. So you could say "The troll is swinging his club at your head..." and have the ... appear incrementally (say 0.5 seconds each). If by the time the last . appears the user hasn't ducked then the club will hit them and you say "The club hit your head, you should have ducked!"

Your defensive moves could be

* The troll is swinging his club at your head = Duck
* The troll is swinging his club at your legs = Jump
* (For both of the above a step back isn't good enough; club is too long)
* The troll is swinging his fist at your head = Duck / Step back
* The troll is swinging his fist at your body = Step back / Block

Ensure that different attacks require different defences, so the player can't just type "block" every time and must instead react to the stimulus (the described attack).

As the fight starts you might let the user get in a punch to the head, but the 2nd attack will be blocked if it is another punch to the head. So you'd punch head, kick legs. This will also get the user to think a little about their attacks - having some kind of pattern recognition and having the character try to guess the next move would be good too, rather than just disallowing repetition. Persisting that learning tree would make for very interesting play too :)
> 2 votes

# Answer
I was working on a text-based game with a combat engine and I had the best results with system inspired by *OGRE BATTLE*, if you remember that title for the Super Nintendo. In my case, you controlled a party of three and could face up to five enemies at a time.

Basically, you set the tactics for your team and the combat sequence becomes automatic for a set number of iterations. Do you want to target the enemies with the lowest health, or the highest? Do you want to target the enemy that will take the most damage? Or do you want to target their leader? Save potions at all cost, or use them at a % threshold?

The sequence would progress with multiple attack exchanges, and then a prompt with come back up and you could re-evaluate and change your tactics. Like you commanding a team, not participating yourself.

Ultimately it comes down to what Pikalek is saying - it's only interesting if the choices require some thought.
> 2 votes

# Answer
## Try something new.

**Note: this may be long but I promise you it'll be worthwhile**

If you're going to do something innovative and able to stray from the traditional multi-option combat system. I'd suggest a text based fighting system, which aren't many out there beside the MUDs (e.g: casting spells or attacks by typing their names), which is a great way to make the game **way** more engaging.

---

however as any other system it has its own pros and cons, here is a list for your convenience:

### Pros:

* Typing gives a text based game something that's very unique to games of the genre, which is the action element. Especially when combined with time limitations, what's a better feeling for a gamer than to blaze through the keyboard while killing a boss and feeling like a boss?
* It forces the player to actually remember his attacks and spell names rather than casually clicking buttons. Which when combined with a good story/meaning (which I believe is essential for a text based game) or some sort of pseudo language makes the player feel way more immersed in the game. In addition, it makes the community of the game fans (which I'll hope you'll get for your project ) much more stable since they'll have a common factor for further discussion on the game, and if you succeed at this you'll have what I like to call a **Fanbase expansion factor (FEF)**, It's basically a feature in games that leads the fans to have a common associative point with an aspect that's unique to the game. Which is really great since it'll add passively more volume to the game, here is a good visualization of the possible outcomes of a FEF: **Starting point** Users play game =\> users learn the FEF =\> users discuss the FEF with other users IRL/online =\> further expansion of the volume of the game related content on the internet =\> more third parties are exposed to the game =\> more users are likely to play the game =\> elevated **starting point**. A good example of successful FEFs of that game are the dovah language in Skyrim or the unique bugs/sense of humor in goat simulator.
* I think the last two points are more than enough to prove the worthiness of such system (at least before the cons). However I will add the third point which is difficulty. By integrating this system you ensure that the player would be challenged enough and that his successfulness in the game would be based more on skill rather than some unsigned integer values. Whether the difficulty would be an effective/ineffective addition is based solely on the implementation. For example the game OSU, while it's a highly challenging game and relativity popular too it scares away a lot of potential players/beginners who initially like the game.

### Cons:

* It's a lot of work. Of course building such a system that's provided with a large database of keywords isn't as simple as sticking a few buttons in the GUI (without even mentioning the issues to be considered while building such a system such as combinations, typos, keyboard handling, etc...)
* Typos. What can be more irritating and a more rage quit leading factor than being killed because of a clumsy keyboard or user, of course this could be corrected by some algorithms / integrated as a unique game element (for example, dealing less damage upon typo) but it requires a much greater deal of time and effort to implement which is an important factor when developing a game.
* It's not for everyone. Especially if the game skills/spells are implemented in a specific language, not everyone types fast and an English native is more likely to type the spells with better spelling *by dum tss* or faster than any other person (same goes for all languages unless your making the skills in Esperanto). This would require the developer to provide an alternative language (or some nonsense) and would probably result in the target audience shrinking + it would make the game unplayable for really small children (which I assume isn't a target audience for a text based game)\*

---

.\* You might say "but hey what about Pokémon?". Give me a break, you know you know no one reads past the initial dialogues.

\** Read the whole post if you want to know what that is.
> 2 votes

# Answer
Both player and opponent pick simultaneously, both decisions are revealed simultaneously and acted upon.

feint high.

feint low.

swing high.

swing low.

block high.

block low.

* If you swing, and your opponent doesn't block, you do damage.
* High swings do more damage than low swings.
* If you swing, and your opponent blocks the correct height, you have a 50% chance that your next action will be wasted (coin flip is performed after your next actions are revealed).
* If you feint, and your opponent blocks that height, they have fallen for your clever ruse, the person who blocked has a 50% chance to lose their next action (coin flip performed after next actions revealed).

Of course, more interactions will be needed for group fights, magic, potions. You can always add more options (power swing high/low), which does more damage if it connects, but leaves you vulnerable for the next 1+ turns.

A.I. choices can be as simple or as complex as you like, but should have some element of random in there. Basically, when people feel threatened (surrounded, low health), make them more likely to block. If their opponent is off balance, low health, surrounded, make them more likely to swing out. Also have them respond to the info the players give them - if a player always swings high, have them probably block high.
> 1 votes

# Answer
What you describe sounds to me like a text-only version of the old school JRPGs combat system.

@Pikalek does a very good job describing why these systems may be boring and how adding depth keeps them engaging. Still, I see two issues with this combat type:

* There may be too much micromanaging. If combat is common, this may become boring fast.
* Although engaging for hard combats, the system may have too much overhead for simple battles. When you clearly overpower your enemy it becomes a drag to play a combat.

Here is where some lateral thinking may be useful. One such example is how Final Fantasy XIII radically changed the traditional FF combat system.

In FF XIII combats happen in real time and player characters are AI controlled^. The player input is a "paradigm shift" that assigns roles to characters, instead of specific actions. Roles determine which skills each character use, and are very general behaviours such as warrior, mage, tank, medic, etc.

This system has pros and cons but I found it to be very effective and engaging.

On the negative side, you lose the fine control of your character actions, you need a pool of skills/roles big enough to be effective and probably is harder to implement.

On the positive side being real time battles are much faster and engaging, easy battles can be dispatched quickly. Also I feel that combat becomes more about strategy (how to set up your party and paradigms) and the tactical flow of battle rather than micromanaging actions, e.g.: start with a buff/debuff round, switch to warrior/mage, is there a big attack coming? quick, switch to all tank!, etc.

Implementing such a combat system is a big commitment and would impact a lot of areas of the game, so take it with a pinch of salt. Still I feel is a very compelling and underused system that I would like to play more, and seems like a good fit for a text only game.

^ To be precise, you can either manually control the main character, or set it to full auto.
> 1 votes

# Answer
Being a text based system, I would suggest that instead of there being the exact same set of choices every time, that a pool of possible phrases be used for the attack and defense options. These phrases could be weapon dependent, and could lend more of a sense of "in the middle of a changing combat". Thus when the prompt for action appears, the exact phrase for the 'attack choice' and the phrase for the 'defense choice' will be different each time.

Also, perhaps introduce a "threatened" mechanic where if one is in a dangerous position, they don't have the option of drinking a potion - or if they drink while "threatened", then they give the opponent a free attack. This could be random, or it could always be based on some circumstance of your choosing.

This should also carry over into combat result descriptions - different random/changing descriptions for hits, misses, weapon types, and amounts of damage.
> 1 votes

# Answer
Just a little tip about health I learned today from Mark Brown:

You can award a player by a health potion of different sizes for a different game styles.

See full video: How Games Do Health
> 0 votes

# Answer
# By making more stats.

If you have character has only one stats that defines entire survival rate (HP) even introducing cost for attacking you essentially makes players to constantly "Use the most HP damaging attack".

Even introducing randomization in damage, and other costs (ammunition, mana, etc.) you still use your most powerful attack until it is depleted, and then second-powerful, etc.

Basically your opponent HP stat will just go down until dead.

But! There is a better alternative: first, let us introduce more ways to damage opponent. For example you could add:

* Willpower. Will cause mental breakdown, when depleted (X-COM, I am looking at ya!)
* Concentration. When lost, it will immediately cancel all spells that are cast by the character
* Stamina. When melee fighter is tired his damage stats get lowered drastically
* Pain. Will make opponent "give-in" to it, rendering him or her incapacitated
* Fear. Will make opponent run for his live and give up the fight
* etc.

Now mix in some special buff/debuffs, possible with dire effects:

* Bleeding: causing losing HP until tended to
* Burning: causing severe pain each turn until extinguished
* etc.

And now we can go into the interesting things:

Each of your fighting-based skills should be useful against given stat. That way, let say if you encounter powerful mage floating 40 stories above ground with powerful shield you could try to wither his defenses, or cast a simple D&D-like "annoying bee" 0-level spell, that makes him lose enough concentration just to fall down and die. It actually happen to me recently in video game and - as player - I felt vastly rewarded from the game for my thinking (even it it was as simple as applied effect).

This system will guarantee that player will have to take different routes against different opponents and even trying unorthodox strategies when in unusual encounter.
> 0 votes

---
Tags: game-design, combat
---


# Question
Title: How do I get my mouse-based input system to work on Android?
I am developing the ball breaker game in unity and right now my game work with mouse click button. but i want my game work in android. so what changes i want to do in this code? So when i set the arrow and its jump ball and hit the brick. Here is the code with image :-

BallController.cs

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

public class BallController : MonoBehaviour {

    public enum ballState {
        aim,
        fire,
        wait,
        endShot
    }

    public ballState currentBallState;

    public Rigidbody2D ball;
    private Vector2 mouseStartPosition;
    private Vector2 mouseEndPosition;
    private float ballVelocityX;
    private float ballVelocityY;
    public float constantSpeed;
    public GameObject arrow;

    // Use this for initialization
    void Start () {
        currentBallState = ballState.aim;

    }

    // Update is called once per frame
    void Update () {
        switch (currentBallState) {
        case ballState.aim:
            if (Input.GetMouseButtonDown (0)) {
                MouseClicked ();
            }
            if (Input.GetMouseButton (0)) {
                MouseDragged ();

            }
            if (Input.GetMouseButtonUp (0)) {
                ReleaseMouse ();
            }
             break;

        case ballState.fire:

            break;

        case ballState.wait:

            break;

        case ballState.endShot:

            break;
        default:
            break;

        }

    }

    public void MouseClicked(){
        mouseStartPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Debug.Log (mouseStartPosition);
        //didClick = true;
    }

    public void MouseDragged(){
    //  didDrag = true;
        //Move the Arrow
        arrow.SetActive(true);
        Vector2 tempMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float diffX = mouseStartPosition.x - tempMousePosition.x;
        float diffY = mouseStartPosition.y - tempMousePosition.y;
        if (diffY <= 0) {
            diffY = .01f;

        }
        float theta = Mathf.Rad2Deg * Mathf.Atan (diffX / diffY);
        arrow.transform.rotation = Quaternion.Euler (0f, 0f, -theta);
    }
    public void ReleaseMouse(){
        arrow.SetActive (false);
        mouseEndPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        ballVelocityX = (mouseStartPosition.x - mouseEndPosition.x);
        ballVelocityY = (mouseStartPosition.y - mouseEndPosition.y);
        Vector2 tempVelocity = new Vector2 (ballVelocityX, ballVelocityY).normalized;
        ball.velocity = constantSpeed * tempVelocity;
        if (ball.velocity == Vector2.zero) {
            return;
        }
        currentBallState = ballState.fire;

    }

}

```

# Answer
I think you should look this: MobileInputUnity. You must change the method for the touch alternative using the phase property of Input.touch:

```
if (Input.GetMouseButtonDown (0)) {   //e.g. if (Input.GetTouch(0).phase == TouchPhase.Began)
            MouseClicked ();
        }
        if (Input.GetMouseButton (0)) {  //e.g. if (Input.GetTouch(0).phase == TouchPhase.Moved)
            MouseDragged ();

        }
        if (Input.GetMouseButtonUp (0)) {  //e.g. if (Input.GetTouch(0).phase == TouchPhase.Ended)
            ReleaseMouse ();
        }

```

And there is a property for the postition too, so when you access to Input.mousePostion you only must change to Input.GetTouch(0).position. If your game can use more than one finger, unless use Input.GetTouch(0), you must control all the touches, for example, with a for bucle:

```
for (int i = 0; i < Input.touchCount; ++i)
    {
        if (Input.GetTouch(i).phase == TouchPhase.Began)
               // Some code ...
    }

```
> 0 votes

# Answer
I've recently added native Mouse & Keyboard input support for Android & iOS / iPadOS. Works just like it does on PC.

https://assetstore.unity.com/packages/tools/input-management/mobile-input-capture-221017

* InputCapture.GetMouseScroll()
* InputCapture.GetMouseVelocity()
* InputCapture GetMouseButton, GetMouseButtonDown, GetMouseButtonUp
* InputCapture GetKey, GetKeyDown, GetKeyUp
* InputCapture.isMouseCaptureSupported: check if device is supported
* InputCapture.isMouseCaptureEnabled: check if capture active
> 0 votes

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


# Question
Title: How can I make a gradual slope with Unity Terrain tool?
As the question title states, I am trying to make a gradual slope in Unity Terrain. I want it to be many 100's metres long for a golf course and it will slope in a few directions hopefully in places.

How could this be done with Unity Terrain?

# Answer
> 0 votes
Have you tried smoothing your relief out?

You can also set the hardness of your terrain sculpting bush to have a smoother looking, more gradual slope instead of a harsh bump on your terrain. Try also playing with the opacity of it so you can gradually build up the terrain.

# Answer
> 0 votes
I know this is a few years old. But for anyone new looking for the solution.

The unity registry has Terrain Tools which lets you installed additional brushes and tools to the existing Unity Terrain.

Here's a link to the documentation: https://docs.unity3d.com/Packages/com.unity.terrain-tools@2.0/manual/effects-slope-flatten.html

---
Tags: unity, terrain
---


# Question
Title: Why does GetSoundDuration() always return the same wrong value in my Portal 2 Vscript?
I am trying to write a Vscript for an instance in Portal 2; the goal of which is to play `ambient_generic` entities directly after one-another in sequence.

To do this, I need to have the script figure out the length of the audio files. But for some reason, it always returns `2.24426` regardless of which sound path I put into `GetSoundDuration()`. Is this a bug in the source engine or is this something I'm doing wrong?

I have several `PATH_#` variables that I've already verified are set correctly to the paths of the audio files.

(`4_PATH <- "vo/david/placeholder/crash_intro_04.wav";` for example)

This is the code I am running which produces the incorrect result:

```
PATH_1 <- "";
PATH_2 <- "";
PATH_3 <- "";
PATH_4 <- "";
PATH_5 <- "";
PATH_6 <- "";
PATH_7 <- "";
PATH_8 <- "";
PATH_9 <- "";
PATH_10 <- "";
SPACING <- 0.5;

sound1dur <- 0;
sound2dur <- 0;
sound3dur <- 0;
sound4dur <- 0;
sound5dur <- 0;
sound6dur <- 0;
sound7dur <- 0;
sound8dur <- 0;
sound9dur <- 0;
sound10dur <- 0;

//this is the function I use to play the stuff with
function Play(){

    //its stupid beyond belief that i have to surround string variables with quotes so they'll be recognized as strings, but its source engine, so what did i expect?
   sound1dur = Entities.FindByName(null,self.GetName() + "_sound_1").GetSoundDuration("\"" + PATH_1 + "\"","")
   sound2dur = Entities.FindByName(null,self.GetName() + "_sound_2").GetSoundDuration("\"" + PATH_2 + "\"","")
   sound3dur = Entities.FindByName(null,self.GetName() + "_sound_3").GetSoundDuration("\"" + PATH_3 + "\"","")
   sound4dur = Entities.FindByName(null,self.GetName() + "_sound_4").GetSoundDuration("\"" + PATH_4 + "\"","")
   sound5dur = Entities.FindByName(null,self.GetName() + "_sound_5").GetSoundDuration("\"" + PATH_5 + "\"","")
   sound6dur = Entities.FindByName(null,self.GetName() + "_sound_6").GetSoundDuration("\"" + PATH_6 + "\"","")
   sound7dur = Entities.FindByName(null,self.GetName() + "_sound_7").GetSoundDuration("\"" + PATH_7 + "\"","")
   sound8dur = Entities.FindByName(null,self.GetName() + "_sound_8").GetSoundDuration("\"" + PATH_8 + "\"","")
   sound9dur = Entities.FindByName(null,self.GetName() + "_sound_9").GetSoundDuration("\"" + PATH_9 + "\"","")
   sound10dur = Entities.FindByName(null,self.GetName() + "_sound_10").GetSoundDuration("\"" + PATH_10 + "\"","")

   printl(sound1dur + " is sound 1's duration even though its really supposed to be 5.84")
   printl(sound2dur + " is sound 2's duration even though its really supposed to be 2.13")
   printl(sound3dur + " is sound 3's duration even though its really supposed to be 9.59")
   printl(sound4dur + " is sound 3's duration even though its really supposed to be 8.88")
   printl(sound5dur + " is sound 3's duration even though its really supposed to be 9.86")

   EntFire(self.GetName() + "_sound_1","PlaySound","",0)
   EntFire(self.GetName() + "_sound_2","PlaySound","",sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_3","PlaySound","",sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_4","PlaySound","",sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_5","PlaySound","",sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_6","PlaySound","",sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_7","PlaySound","",sound6dur + sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_8","PlaySound","",sound7dur + sound6dur + sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_9","PlaySound","",sound8dur + sound7dur + sound6dur + sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
}

//the following gets appended to the script during the compilation //process of the map; via Teamspen210's hammer addons.

8_PATH <- "common/null.wav";
3_PATH <- "vo/david/placeholder/crash_intro_03.wav";
4_PATH <- "vo/david/placeholder/crash_intro_04.wav";
10_PATH <- "vo/david/placeholder/crash_intro_01.wav0";
5_PATH <- "vo/david/placeholder/crash_intro_05.wav";
2_PATH <- "vo/david/placeholder/crash_intro_02.wav";
6_PATH <- "common/null.wav";
1_PATH <- "vo/david/placeholder/crash_intro_01.wav";
7_PATH <- "common/null.wav";

```

The output (the "supposed to be" numbers are the actual length of the audio files in question, measured using Adobe Audition):

```
2.24426 is sound 1's duration even though it's really supposed to be 5.84
2.24426 is sound 2's duration even though it's really supposed to be 2.13
2.24426 is sound 3's duration even though it's really supposed to be 9.59
2.24426 is sound 3's duration even though it's really supposed to be 8.88
2.24426 is sound 3's duration even though it's really supposed to be 9.86

```

For a minimal example that has the same issue, try:

```

sound1dur = self.GetSoundDuration("error.wav","")

printl(sound1dur + " is sound 1's duration even though its really supposed to be 2.24")

```

note that while creating this example, I realized a part of the problem: getsoundlength seems to be getting the length of error.wav no matter the path it is fed. error.wav being the engine's fallback when it can't find something.

# Answer
> 1 votes
the answer was unfortunately just as complex as the question and came down to bad logic in my scripts and a few typos. my working full script:

```
SPACING <- 0;

sound1dur <- 0;
sound2dur <- 0;
sound3dur <- 0;
sound4dur <- 0;
sound5dur <- 0;
sound6dur <- 0;
sound7dur <- 0;
sound8dur <- 0;
sound9dur <- 0;
sound10dur <- 0;

function Init(){

}

function Stop(){
    EntFire(self.GetName() + "_sound_*","StopSound","",0);
}

function Play(){

   sound1dur = self.GetSoundDuration(PATH_1,"")
   sound2dur = self.GetSoundDuration(PATH_2,"")
   sound3dur = self.GetSoundDuration(PATH_3,"")
   sound4dur = self.GetSoundDuration(PATH_4,"")
   sound5dur = self.GetSoundDuration(PATH_5,"")
   sound6dur = self.GetSoundDuration(PATH_6,"")
   sound7dur = self.GetSoundDuration(PATH_7,"")
   sound8dur = self.GetSoundDuration(PATH_8,"")
   sound9dur = self.GetSoundDuration(PATH_9,"")
   sound10dur = self.GetSoundDuration(PATH_10,"")

   EntFire(self.GetName() + "_sound_1","PlaySound","",0)
   EntFire(self.GetName() + "_sound_2","PlaySound","",sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_3","PlaySound","",sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_4","PlaySound","",sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_5","PlaySound","",sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_6","PlaySound","",sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_7","PlaySound","",sound6dur + sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_8","PlaySound","",sound7dur + sound6dur + sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
   EntFire(self.GetName() + "_sound_9","PlaySound","",sound8dur + sound7dur + sound6dur + sound5dur + sound4dur + sound3dur + sound2dur + sound1dur + SPACING)
}

PATH_1 <- "common/null.wav";
PATH_2 <-"common/null.wav";
PATH_3 <-"common/null.wav";
PATH_4 <-"common/null.wav";
PATH_5 <-"common/null.wav";
PATH_6 <-"common/null.wav";
PATH_7 <-"common/null.wav";
PATH_8 <-"common/null.wav";
PATH_9 <-"common/null.wav";
PATH_10 <-"common/null.wav";

```

note that the `PATH_#` vars are set in-map via hammer logic

---
Tags: source-engine, valve
---


# Question
Title: Make Inventory that receives Purchased Items from the Shop system
I want to make Items purchased from my game shop like decoration to go to Inventory after I purchase them.

I have created a shop system with purchase buttons and stuff but I don't know how to make inventory receive the items these are the scripts I have for the shop and the inventory:

**SHOP SYSTEM**

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

public class ShopManager : MonoBehaviour
{

    public int[,] shopItems = new int[9, 9];
    public float coins;
    public Text CoinsTXT;

    void Start()
    {
        CoinsTXT.text = "" + coins.ToString();

        //ID's
        shopItems[1, 1] = 1;
        shopItems[1, 2] = 2;
        shopItems[1, 3] = 3;
        shopItems[1, 4] = 4;
        shopItems[1, 5] = 5;
        shopItems[1, 6] = 6;
        shopItems[1, 7] = 7;
        shopItems[1, 8] = 8;

        //Price
        shopItems[2, 1] = 10;
        shopItems[2, 2] = 20;
        shopItems[2, 3] = 30;
        shopItems[2, 4] = 40;
        shopItems[2, 5] = 50;
        shopItems[2, 6] = 65;
        shopItems[2, 7] = 110;
        shopItems[2, 8] = 150;

    }

    public void Buy()
    {
        GameObject ButtonRef = GameObject.FindGameObjectWithTag("Event").GetComponent<EventSystem>().currentSelectedGameObject;

        if (coins >= shopItems[2, ButtonRef.GetComponent<ButtonInfo>().ItemID])
        {
            coins -= shopItems[2, ButtonRef.GetComponent<ButtonInfo>().ItemID];
            CoinsTXT.text = "Coins:" + coins.ToString();
        }

    }
}

```

**INVENTORY SYSTEM**

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

public class Inventory {

    private List<Item> itemList;

    public Inventory()
    {
        itemList = new List<Item>();

        Debug.Log("Inventory");
    }

    public void AddItem(Item item)
    {
        itemList.Add(item);
    }
}

```

**What should I add to make it receive the purchased items?**

# Answer
> 0 votes
There are a few ways you could get this functionality. I would use the following method. You could have an event for when an item if purchased, then have the inventory subscribe to the event. You haven't shown any items or any way for the inventory to access any instance of the Item class, but I'll assume you have that mostly figured out since both your classes seem to use the Item class without issue.

For example, you could add the following event to your ShopManager class.

```
public static delegate PuchaseItemDelegate(Item item);
public static event OnPurchase;

```

Now that you have that event, you can have the inventory system subscribe to it, and have the inventory system call the AddItem method whenever an item is purchased. In your Inventory constructor, add the following line.

```
ShopManager.OnPurchase += AddItem;

```

Since OnPurchase is static, you don't need to have a reference to an instance of the class.

Now, all you have to do is invoke the OnPuchase event in your ShopManager class whenever an item is puchased, and it will call the AddItem method in the Inventory class. To do that, you use the same syntax you would use for a normal method. So within the if statement of the Buy method in your ShopManager class, add the following (where itemPurchased is the item related to the selected item id).

```
OnPurchase(itemPurchased)

```

Alternatively, you could change the method signatures to have one int type parameter instead of an Item, then change the AddItem method in Inventory figure out what to do with the Id. I can't give you the most solid response on that since you haven't provided the code for the Item class.

To learn more about Events, you could read up on the documentation here

Sebastian Lague also has a great couple of videos on events and delegates

Video 1

Video 2

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


title: How can I disable a RigidBody?

text:
# Question
Title: How can I disable a RigidBody?
I have tried to set Rigibody enabled to false with this code but I get multiple errors. What is the correct version of this code?

```
GetComponent<RigidBody>().Enabled = false;

```

# Answer
Normally, it helps if you actually post the errors you're getting.

In this case, however, the problem seems straightforward: RigidBody does not have a member named `Enabled`.

It sounds like you want to set both `isKinematic` and `detectCollisions` to `false`.
> 6 votes

# Answer
@user1430's answer is good, but you actually set `isKinematic` to `true` to disable the rigidbody, per isKinematic docs.

```
// Let animation control the rigidbody and ignore collisions.
void DisableRagdoll()
{
    rb.isKinematic = true;
    rb.detectCollisions = false;
}

```

I would have added this as a comment to @user1430's answer but don't have enough reputation.
> 2 votes

# Answer
In Unity 4.0+ rigidbody.active is deprecated and may no longer be available but you can do this:

```
this.gameObject.GetComponent<Rigidbody>().detectCollisions = false;

```
> -2 votes

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


# Question
Title: How can I update vSync settings after creating an SDL_Renderer?
I have an `SDL_Renderer` which I set to use or not use vSync depending on the user). In my options menu I have an option for enabling/disabling vSync. Can I edit my renderer to update the vSync preferences so that I don't have to destroy and recreate it? Doing so would invalidate a lot of renderer pointers in my game, so I would like to find an alternative solution.

# Answer
Ok, I asked on the SDL Forums too:

* There is no way to edit vSync settings after renderer creation without using OpenGL.
* Destroying the renderer and re-creating it, is not an option because it will destroy every texture created with it.

So vSync shouldn't be an user-editable setting (at least for now).
> 2 votes

# Answer
Since 2.0.18 you can use SDL\_RenderSetVSync:

> Toggle VSync of the given renderer.
>
> **Syntax**
> `int SDL_RenderSetVSync(SDL_Renderer* renderer, int vsync);`

`vsync` can be set 1 for on or 0 for off (other values are reserved).
> 1 votes

# Answer
**EDIT**: The following only works when executed before calling `SDL_CreateRenderer`. Seems like SDL has made a simple and trivial task quite hard.

SDL wiki suggests that calling `SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1" or "0");` should do the trick. You might also want to try SDL\_SetHintWithPriority, which will override any possible environment variables that have been set that could prevent that value passed in to `SDL_SetHint` to have an effect.
> 0 votes

---
Tags: sdl2, vsync
---


# Question
Title: How do you determine which 4 pixels to interpolate, using bilinear interpolation?
I read about bilinear interpolation on Wikipedia and many sources, but I still don't understand how do you determine which four pixels to interpolate.

For example, if I have 5 pixels(y=0), do I interpolate pixel 1 with pixel 2, pixel 3 with pixel 4, but how about pixel 5? Do I interpolate pixel 5 or not? All the examples shown to me are all perfect quads of 2x2.

# Answer
Conventionally, the pixels (or "texels") in a texture are arranged in a 2D grid. Let's say it looks like this:

```
↑
2   I   J   K   L
|
1   E   F   G   H
|
0   A   B   C   D

    0---1---2---3---→

```

Here I've laid out 12 texels labelled A-L on two coordinate axes, starting at 0,0 in the bottom left-hand corner and increasing by 1 for each texel to the right or above.

For simplicity, I've located the texels themselves at the integer corner points of this lattice, but note that in some contexts the texels are treated as sitting in the centers of each square. You can subtract 0.5 from each coordinate to convert back to integer points.

We can use this coordinate system to specify our sampling location within this grid. For instance, sampling the point (2, 1) would get us 100% the value of texel G.

But our sampling point can also have a fractional component. I could sample from the point (1.7, 0.2). Flooring to the closest integer below, that means the bottom-left of our 2x2 sampling block will be texel B, but we'll also want to blend in the texels right and above that: F, G, and C. So the 2x2 block we're in looks like:

```
F     G

    .    ← sample point somewhere near here
B     C

```

We can get the bilinear blending weights from the fractional component of our sample coordinate. 1.7 has a fractional component of 0.7, which means we want 70% of the value of the texel to the right, and 30% of the value of the texel to the left.

In the top row of our sampling quad, that's

```
Lerp(F, G, 0.7)

```

And in the bottom row it's

```
Lerp(B, C, 0.7)

```

The fractional component of the vertical coordinate gives us the blending weight between these two lerps:

```
Lerp(
   Lerp(B, C, 0.7),
   Lerp(F, G, 0.7),
   0.2
)

```

In the event that you have just a single row of texels, then "bilinear interpolation" really reduces to just "linear interpolation" or a single lerp between the two texels left and right of your sample position. There are no texel value differences on the vertical axis, so you don't need a nested outer lerp at all. (Or you could consider that the single row repeats infinitely above and below, and apply bilinear interpolation that reads the two left & right texels twice each)

```
A   B • C   D

```

Sampling this row at (1.5, 0.1) would give you:

```
Lerp(
    Lerp(B, C, 0.5),
    Lerp(B, C, 0.5),
    0.1
)

```

...which is the same as just `Lerp(B, C, 0.5)` (any interpolation of a value with itself just returns itself)
> 2 votes

---
Tags: 2d, image, interpolation
---


# Question
Title: Seamless random morphing hex tiles' vertices in Unity3D?
I have a **hex based, fully flat tilemap** the tiles' mesh currently isn't generated, but a static mesh file containing 6 vertices, UV mapping, etc.

Then I saw this picture on Unity Answers:

I'd like achieve this. Which is:

* To morph my hexes' vertices **randomly in every direction**
* while they are **all seamlessly still connected**.

(But without having a height for now for simplicity's sake. But that could be a future step.)

So if I move a **vertex0 of Hex A**, the corresponding, **opposing index, vertex3 of the neighbouring Hex B** will move accordingly, like they are all part of one big mesh.

Water tiles would be an exception

* They would be flat: their vertices' Y (up axis) would be constant zero,
* thus I would set every *shore tile*'s water neighbouring borders' vertices' Y to 0 as well. *(now that's an ugly sentence)*

As you can see I have some vague, high level idea about how I would try to achieve parts of this, but code-wise I'm pretty lost. Could you help me? Thanks in advance!

# Answer
> 2 votes
Myself, I would implement this in the shader.

Use a vertex colour to mark which vertices should be displaced vs. not (so for example, paint all interior land vertices red, and all shore or water vertices black).

Inside the vertex shader, compute the worldspace position of the vertex. Run that position through a noise function like Simplex or Perlin Noise to generate a pseudo-random 2D offset vector. Multiply that vector by the displacement mask stored in the vertex colour (so it gets zero'd out for water vertices), then add it to the vertex position before projecting it to the screen.

This gives you uneven, random-looking warping of the land hexes, without needing tons of unique mesh variants (just one for each combination of water adjacencies). Since the offset vector depends on worldspace position, wherever two vertices coincide at the same position (like two tiles meeting at a shared corner), both vertices will get the same offset, so they'll move as though glued together, even if they're rendered as two completely different meshes with no knowledge of one another. And you'll get the same result frame to frame, so it won't move or animate (unless you want it to).

You can get away with even cheaper, discontinuous noise functions, if your vertices are always *perfectly* positioned to match up, or you do a quick bit of rounding before applying the noise. The continuous noise functions just give you a bit more leeway for small alignment errors to produce only small offset differences (hopefully sub-pixel-sized), and if you're using a shader graph, they're directly available as nodes to use for quick prototyping.

---
Tags: unity, procedural-generation, 3d-meshes, mesh
---


# Question
Title: Unity set RectTransform width independent from height
The usual way to set the width or height for a `RectTransform` is this one as far as I know : `RectTransform.sizeDelta = new Vector2(...);` . I want to set the width of my object in an EditorScript, so if I would use the mentioned method, I would automatically lock my height value in the editor. But I want to freely adjust my height and at the same time let the width be calculated from my script. So my problem is, that `RectTransform.sizeDelta = new Vector2(...);` is locking both values in the Editor.

# Answer
> 3 votes
You can read current height and set it again without changing. When you change height in the editor, it'll be changed between your code executions.

```
RectTransform.sizeDelta = new Vector2(calculatedWidth, RectRansform.sizeDelta.y)

```

# Answer
> 2 votes
This is a very common problem, actually. Unity provides `SetSizeWithCurrentAnchors()` for setting either width or height, ignoring the current anchors (which is almost certainly what you want).

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