title: How to activate a button?

text:
# Question
Title: How to activate a button?
Develop a timer script, the idea of this script is that after an amount of time has passed, a button that I have in the scene is activated, this script also uses this script uses DontDestroyOnLoad, but I cannot activate it because of the following error:

"MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. DigitalRubyShared.Timer.Update () (at Assets / DIC / Scripts / Timer.cs: 53)) "

From what I understood is that this button object is destroyed when I change scenes, so how can I keep this object?

```
 public static float currentTime;
        public static float endTime = 0f;
        public static bool startTime = false;
        public static string recibir;
        public static Timer estadoTimer;
        public string tiempoEscena;
        public string nombreEscena = "Mapa_Izquierdo";

        public GameObject aceptar;
        [SerializeField] Text Contador;

        void Start()
        {
            currentTime = 0f;
        }

        void Awake()
        {
            if(estadoTimer == null)
            {
                estadoTimer = this;
                DontDestroyOnLoad(gameObject);
            }else if(estadoTimer != this)
            {
                Destroy(gameObject);
            }

        }

        void Update()
        {

            if (startTime != false)
            {
                currentTime += 1 * Time.deltaTime;
                Contador.text = currentTime.ToString("0");

                if (Contador.text.Equals(tiempoEscena))
                {
                    //SceneManager.LoadScene(nombreEscena);
                    aceptar.SetActive(true);
                    currentTime = endTime;
                    stopTiempo();
                }

            }
            else
            {
                Contador.text = currentTime.ToString("0");
            }

    }

```

# Answer
Its looks like this problem well only occur when you reload the scene after first time? if i am correct please let me know about it.

**Reason:**

As you have made this class as a singleton class and set it to "DoNotDestroy", that's the reason which generates the error. Basically what happen when you load this scene for the first time this game object is set to Do not destroy and for the class it is set up to singleton so when you reload the scene at the second time or after that this

```
if(estadoTimer == null)
            {
                estadoTimer = this;
                DontDestroyOnLoad(gameObject);
            }else if(estadoTimer != this)
            {
                Destroy(gameObject);
            }

```

will destroy destroy the game object . i know I have not presented the problem reason really well but i tried. But solution will work :).

**Solution:**

When ever you are trying to disable the button before that you check for it if the button is available, if it is available then just enable or disable it.

if the button is null then first Find the button with tag or name but i prefer to use Tag instead of name, here is how i do it:

**Finding object with Tag:** More information

> GameObject.FindGameObjectsWithTag("*YourButtonTag*");

**Finding by Name:** More information

> GameObject.Find("*YourButtonName*");

Your Code will become some thing like this:

**Note:** Before you do this add Tag to the button. Any thing you want.

```
public static float currentTime;
public static float endTime = 0f;
public static bool startTime = false;
public static string recibir;
public static Timer estadoTimer;
public string tiempoEscena;
public string nombreEscena = "Mapa_Izquierdo";

public GameObject aceptar;
[SerializeField] Text Contador;

void Start()
{
    currentTime = 0f;
}

void Awake()
{
    if(estadoTimer == null)
    {
        estadoTimer = this;
        DontDestroyOnLoad(gameObject);
    }else if(estadoTimer != this)
    {
        Destroy(gameObject);
    }

}

void Update()
{

    if (startTime != false)
    {
        currentTime += 1 * Time.deltaTime;
        Contador.text = currentTime.ToString("0");

        if (Contador.text.Equals(tiempoEscena))
        {
            //SceneManager.LoadScene(nombreEscena);
            if(aceptar!=null)
            {
                   aceptar.SetActive(true);
            }
            else
            {
                   aceptar =  GameObject.FindGameObjectWithTag("Your Button Tag Here");
                   aceptar.SetActive(true);
             }
            currentTime = endTime;
            stopTiempo();
        }

    }
    else
    {
        Contador.text = currentTime.ToString("0");
    }

```

}

I hope this will help...
> 1 votes

---
Tags: unity
---


# Question
Title: Struggling to smoothly implement 4-directional movement in Unity2D
This is my code so far:

```
public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;

    public Rigidbody2D rb;
    public Animator animator;

    Vector2 movement;

    void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
        movement = movement.normalized;

        if (movement.x != 0)
        {
            movement.y = 0;
        }

        else if (movement.y != 0)
        {
            movement.x = 0;
        }

        animator.SetFloat("Horizontal", movement.x);
        animator.SetFloat("Vertical", movement.y);
        animator.SetFloat("Speed", movement.sqrMagnitude);
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    }
}

```

I'm trying to restrict diagonal movement. The issue is that whenever up/down is being pressed, you can press left/right at the same time, and the object will then move left/right. When moving left/right, however, pressing up/down at the same time still has you continue left/right. Switching the position of the if/else if statements causes the same issue with converse directions. I'd prefer to have the player go in whatever the latest key press was for either direction!

I've tried making both statements if statements, as well as separating +/- values for both axes, but nothing changed! Any help is appreciated.

# Answer
This code will store the last pressed direction key. When it's released, the key resets to `None`.

You'll need a field to store it, initialized with `None`:

```
KeyCode key = KeyCode.None;

```

Put this in `Update`:

```
if      (Input.GetKeyDown (KeyCode.W))  key = KeyCode.W;
else if (Input.GetKeyDown (KeyCode.A))  key = KeyCode.A;
else if (Input.GetKeyDown (KeyCode.S))  key = KeyCode.S;
else if (Input.GetKeyDown (KeyCode.D))  key = KeyCode.D;

if (Input.GetKeyUp (key))  key = KeyCode.None;

```

After this code you can set animator variables or move your character. The `key` variable will store the last pressed direction key or `None`. Handling may be done like this:

```
Vector2 direction; // (0, 0) by default
switch (key) {
    case KeyCode.W:  direction.y =  1;  break;
    case KeyCode.A:  direction.x = -1;  break;
    case KeyCode.S:  direction.y = -1;  break;
    case KeyCode.D:  direction.x =  1;  break;
}
// here you use direction variable to set animator params etc.

```
> 0 votes

# Answer
Assuming you want you character to move exclusively in the first direction it was told to go in:

You can store the movement state of the player across each tick of the game loop.

```
//Player variables stored somewhere
bool forwardHeld;
bool backwardHeld;
bool leftHeld;
bool rightHeld;

```

For your code itself, you will need to check what state it was in before and act based on that. For example:

```
//Was forward being held down last frame?
if(forwardHeld == true)
{
    //Yes, check if it is still being held down
    if(yourKeyboardVariableName.forwardKeyPressed == true)
    {
        //forward is still pressed, ignore further inputs.
    }
    else
    {
        //Forward is no longer pressed, reset its variable
        forwardHeld = false;

        //Is backward being pressed?
        if(yourKeyboardVariableName.backwardKeyPressed == true)
        {
            //Yes, set backward to true
            backwardHeld = true;
        }
        else
        {
            //No, are left or right (exclusive) being pressed?
               yourKeyboardVariableName.LeftKeyPressed !=
               yourKeyboardVariableName.RightKeyPressed)
            {
                if(yourKeyboardvariableName.LeftKeyPressed == true)
                {
                    leftHeld = true;
                }
                else
                {
                    rightHeld = true;
                }
            }//left/right?
        }//backward?
    }//forward still held
}//forward held
else if (backwardHeld)
{
    //Repeat for backward, etc.
}
...

```

After one of the four branches have executed, only one of the variables for forward/backward/left/right will be true and you can act on it as normal.
> 0 votes

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


# Question
Title: Can Mobile Games use Fragments instead of SurfaceViews?
All the tutorials of mobile games for android (such as this one), use the to display game objects. Most other applications tend to use an `Activity > Layout Resource` architecture.

The guide explains why he uses a `Activity > SurfaceView Subclass` architecture because of threading and canvasing at this point in the video.

* Could you use fragments to have take care of threading and displaying game objects?
* If you can, why is using a SurfaceView preferred?

# Answer
From my experience in game developing, when making a game for multiple platforms, its easier to organise everything in such a way that works for most of them.

In this case, using a `SurfaceView` is like telling to android "Give me a rectangular area on the screen, where I will draw custom graphics". This is very similar to how game development is being done on other platforms, by creating a window, or otherwise asking the OS for an area on the screen to show all the graphics.

I don't have much experience with fragments, but from what I remember, they are very tied to android's app lifecycle. Using fragments means one has to develop primarily on android, and be familiar with how it works. In theory, that works, and if someone is familiar enough, they could use fragments.

However, most people out there use libraries or tools, that already work in a platform-agnostic way, which would make it more cumbersome to make them work with fragments instead.

At the end of the day, if they work for you, use them. In the past I've made a video game that was using android's `Activity`, without any subclasses. Why? Because I found it a fun thing to do.
> 1 votes

---
Tags: java, android, architecture, mobile
---


# Question
Title: Various unreproducible crashes caused by asset bundles
We recently released a game on iOS and Android, and a bunch of crash reports have started coming in on iOS through Crashlytics that appear to be due to problems with shaders in asset bundles and other asset bundle problems (such as loading models, textures, basically anything and everything in an asset bundle). We haven't been able to reproduce this problem, so we aren't sure what we can do about them other than do a new release with new builds of the asset bundles and hope that they work. We're using Unity 2108.2.12f1.

Is there anything we can do to try to resolve this problem?

For reference, here are some of the places where it has crashed. All of these are internal to Unity apparently. There's nothing specific to our game in the stack trace. I'm not sure how useful these different stack traces are.

```
Crashed: UnityPreload
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000000

__bzero + 28

SerializeTraits.h - Line 488
SerializeTraits<dynamic_array<unsigned char, 0ul> >::ResizeSTLStyleArray(dynamic_array<unsigned char, 0ul>&, int)

StreamedBinaryRead.h - Line 77
void StreamedBinaryRead::TransferSTLStyleArray<dynamic_array<unsigned char, 0ul> >(dynamic_array<unsigned char, 0ul>&, TransferMetaFlags)

SerializeTraits.h - Line 481
void PackedFloatVector::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

CompressedMesh.h - Line 155
void CompressedMesh::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

SerializeTraitsBase.h - Line 54
void Mesh::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

SerializedFile.cpp - Line 2164
SerializedFile::ReadObject(long long, ObjectCreationMode, bool, TypeTree const**, bool*, Object&)

PersistentManager.cpp - Line 2330
PersistentManager::ReadAndActivateObjectThreaded(int, SerializedObjectIdentifier const&, SerializedFile*, bool, bool, PersistentManager::LockFlags)

PersistentManager.cpp - Line 1785
PersistentManager::LoadObjectsThreaded(int const*, int, LoadProgress&, bool)

dynamic_array.h - Line 146
LoadSceneOperation::perform()

PreloadManager.cpp - Line 281
PreloadManager::processSingleOperation()

PreloadManager.cpp - Line 338
PreloadManager::Run()

PreloadManager.cpp - Line 187
PreloadManager::Run(void*)

Thread.cpp - Line 42
Thread::RunThreadWrapper(void*)

```

And a dozen similar ones.

```
Crashed: UnityPreload
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000028

StringStorageDefault.h - Line 31
std::__1::vector<ShaderLab::SerializedSubProgram::StructParameter, std::__1::allocator<ShaderLab::SerializedSubProgram::StructParameter> >::__append(unsigned long)

type_traits - Line 3615
void resize_trimmed<std::__1::vector<ShaderLab::SerializedSubProgram::StructParameter, std::__1::allocator<ShaderLab::SerializedSubProgram::StructParameter> > >(std::__1::vector<ShaderLab::SerializedSubProgram::StructParameter, std::__1::allocator<ShaderLab::SerializedSubProgram::StructParameter> >&, unsigned int)

vector - Line 1467
void StreamedBinaryRead::TransferSTLStyleArray<std::__1::vector<ShaderLab::SerializedSubProgram::StructParameter, std::__1::allocator<ShaderLab::SerializedSubProgram::StructParameter> > >(std::__1::vector<ShaderLab::SerializedSubProgram::StructParameter, std::__1::allocator<ShaderLab::SerializedSubProgram::StructParameter> >&, TransferMetaFlags)

SerializeTraits.h - Line 260
void ShaderLab::SerializedSubProgram::ConstantBuffer::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

iterator - Line 1190
void StreamedBinaryRead::TransferSTLStyleArray<std::__1::vector<ShaderLab::SerializedSubProgram::ConstantBuffer, std::__1::allocator<ShaderLab::SerializedSubProgram::ConstantBuffer> > >(std::__1::vector<ShaderLab::SerializedSubProgram::ConstantBuffer, std::__1::allocator<ShaderLab::SerializedSubProgram::ConstantBuffer> >&, TransferMetaFlags)

SerializeTraits.h - Line 260
void ShaderLab::SerializedSubProgram::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

iterator - Line 1190
void StreamedBinaryRead::TransferSTLStyleArray<std::__1::vector<ShaderLab::SerializedSubProgram, std::__1::allocator<ShaderLab::SerializedSubProgram> > >(std::__1::vector<ShaderLab::SerializedSubProgram, std::__1::allocator<ShaderLab::SerializedSubProgram> >&, TransferMetaFlags)

SerializeTraits.h - Line 260
void ShaderLab::SerializedPass::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

iterator - Line 1190
void StreamedBinaryRead::TransferSTLStyleArray<std::__1::vector<ShaderLab::SerializedPass, std::__1::allocator<ShaderLab::SerializedPass> > >(std::__1::vector<ShaderLab::SerializedPass, std::__1::allocator<ShaderLab::SerializedPass> >&, TransferMetaFlags)

SerializeTraits.h - Line 260
void ShaderLab::SerializedSubShader::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

iterator - Line 1190
void StreamedBinaryRead::TransferSTLStyleArray<std::__1::vector<ShaderLab::SerializedSubShader, std::__1::allocator<ShaderLab::SerializedSubShader> > >(std::__1::vector<ShaderLab::SerializedSubShader, std::__1::allocator<ShaderLab::SerializedSubShader> >&, TransferMetaFlags)

SerializeTraits.h - Line 260
void ShaderLab::SerializedShader::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

SerializeTraits.h - Line 480
void Shader::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

SerializedFile.cpp - Line 2164
SerializedFile::ReadObject(long long, ObjectCreationMode, bool, TypeTree const**, bool*, Object&)

PersistentManager.cpp - Line 2330
PersistentManager::ReadAndActivateObjectThreaded(int, SerializedObjectIdentifier const&, SerializedFile*, bool, bool, PersistentManager::LockFlags)

PersistentManager.cpp - Line 1785
PersistentManager::LoadObjectsThreaded(int const*, int, LoadProgress&, bool)

dynamic_array.h - Line 146
LoadSceneOperation::perform()

PreloadManager.cpp - Line 281
PreloadManager::processSingleOperation()

PreloadManager.cpp - Line 338
PreloadManager::Run()

PreloadManager.cpp - Line 187
PreloadManager::Run(void*)

Thread.cpp - Line 42
Thread::RunThreadWrapper(void*)

```

And a dozen similar ones

```
Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000b253c034
libsystem_platform.dylib
_platform_memmove + 352

CachedReader.cpp - Line 98
CachedReader::Read(void*, unsigned long)

StreamedBinaryRead.h - Line 88
void StreamedBinaryRead::TransferSTLStyleArray<core::basic_string<char, core::StringStorageDefault<char> > >(core::basic_string<char, core::StringStorageDefault<char> >&, TransferMetaFlags)

SerializeTraits.h - Line 237
void NamedObject::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

SpriteFrame.cpp - Line 134
void Sprite::Transfer<StreamedBinaryRead>(StreamedBinaryRead&)

SerializedFile.cpp - Line 2164
SerializedFile::ReadObject(long long, ObjectCreationMode, bool, TypeTree const**, bool*, Object&)

PersistentManager.cpp - Line 2330
PersistentManager::ReadAndActivateObjectThreaded(int, SerializedObjectIdentifier const&, SerializedFile*, bool, bool, PersistentManager::LockFlags)

PersistentManager.cpp - Line 1663
PersistentManager::ReadObjectThreaded(int, PersistentManager::LockFlags)

PersistentManager.cpp - Line 1390
PersistentManager::ReadObject(int, AwakeFromLoadMode)

AssetBundleUtility.cpp - Line 143
ForcePreload(AssetBundle&, dynamic_array<int, 0ul>, bool)

dynamic_array.h - Line 114
ProcessAssetBundleEntries(AssetBundle&, std::__1::pair<std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<core::basic_string<char, core::StringStorageDefault<char> >, AssetBundle::AssetInfo>, std::__1::__tree_node<std::__1::__value_type<core::basic_string<char, core::StringStorageDefault<char> >, AssetBundle::AssetInfo>, void*>*, long> >, std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<core::basic_string<char, core::StringStorageDefault<char> >, AssetBundle::AssetInfo>, std::__1::__tree_node<std::__1::__value_type<core::basic_string<char, core::StringStorageDefault<char> >, AssetBundle::AssetInfo>, void*>*, long> > > const&, ScriptingSystemTypeObjectPtr, dynamic_array<Object*, 0ul>&, bool)

dynamic_array.h - Line 471
LoadNamedObjectFromAssetBundle(AssetBundle&, core::basic_string<char, core::StringStorageDefault<char> > const&, ScriptingSystemTypeObjectPtr)

AssetBundle.bindings.gen.cpp - Line 265
AssetBundle_CUSTOM_LoadAsset_Internal(Il2CppObject*, Il2CppString*, Il2CppObject*)

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 3860516

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 7811508

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 21918336

Il2CppInvokerTable.cpp - Line 4336374932
RuntimeInvoker_Void_t1185182177_RuntimeObject_IntPtr_t(void (*)(), MethodInfo const*, void*, void**)

Runtime.cpp - Line 521
il2cpp::vm::Runtime::Invoke(MethodInfo const*, void*, void**, Il2CppException**)

ScriptingApi_Il2Cpp.cpp - Line 245
scripting_method_invoke(ScriptingMethodPtr, ScriptingObjectPtr, ScriptingArguments&, ScriptingExceptionPtr*, bool)

ScriptingInvocation.cpp - Line 341
ScriptingInvocation::Invoke(ScriptingExceptionPtr*, bool)

ScriptingInvocation.h - Line 71
Coroutine::InvokeMoveNext(ScriptingExceptionPtr*)

Coroutine.cpp - Line 257
Coroutine::Run(bool*)

MonoBehaviour.cpp - Line 742
MonoBehaviour::TryCreateAndRunCoroutine(ScriptingObjectPtr, ScriptingMethodPtr, Coroutine**)

MonoBehaviour.cpp - Line 760
MonoBehaviour::StartCoroutineManaged2(ScriptingObjectPtr)

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 3882300

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 26739188

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 1768320

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 1768580

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 2599928

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 2602580

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 2037840

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 21782776

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 21782776

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 26101624

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 22342724

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 22341516

unsigned long long flatbuffers::HashFnv1a<unsigned long long>(char const*) + 22339732

Il2CppInvokerTable.cpp - Line 99434
RuntimeInvoker_Void_t1185182177(void (*)(), MethodInfo const*, void*, void**)

Runtime.cpp - Line 521
il2cpp::vm::Runtime::Invoke(MethodInfo const*, void*, void**, Il2CppException**)

ScriptingApi_Il2Cpp.cpp - Line 245
scripting_method_invoke(ScriptingMethodPtr, ScriptingObjectPtr, ScriptingArguments&, ScriptingExceptionPtr*, bool)

ScriptingInvocation.cpp - Line 341
ScriptingInvocation::Invoke(ScriptingExceptionPtr*, bool)

MonoBehaviour.cpp - Line 571
MonoBehaviour::CallUpdateMethod(int)

Behaviour.cpp - Line 176
void BaseBehaviourManager::CommonUpdate<BehaviourManager>()

PlayerLoop.cpp - Line 340
ExecutePlayerLoop(NativePlayerLoopSystem*)

PlayerLoop.cpp - Line 357
ExecutePlayerLoop(NativePlayerLoopSystem*)

RecursionLimit.h - Line 45
PlayerLoop()

LibEntryPoint.mm - Line 299
UnityPlayerLoopImpl(bool)

UnityAppController+Rendering.mm - Line 280
UnityRepaint

UnityAppController+Rendering.mm - Line 77
-[UnityAppController(Rendering) repaintDisplayLink]
QuartzCore
CA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long) + 632

```

And again, a dozen similar ones.

# Answer
> 0 votes
Turned out this was a Unity bug that they have fixed in the latest Unity update.

# Answer
> 0 votes
The first thing to do is try to narrow down why `EXC_BAD_ACCESS` errors are occurring. A common cause is attempting to access a deallocated object, also known as a dangling pointer error.

You can check for this in XCode by enabling zombie objects. Doing so allows deallocated objects to be kept around as 'zombies' for debugging purposes. Accessing a zombie will still result in a EXC\_BAD\_ACCESS. However, it will give you more information about what object you were trying to access, which makes debugging easier.

If that doesn't help, the next step is to have Xcode analyze your project. This will generate a list of issues. These are warnings about things that *may* need attention. One approach is to filter through the issues & their linked code looking for things that seem most relevant to the problem at hand. If time / resources permit it might be better to go through them and address/correct as many as possible.

Note: sometimes the warnings will not be applicable to your particular situation. However, keep in mind that your code is crashing; don't be quick to convince yourself that you are right & the analysis tool is wrong.

# Answer
> 0 votes
I would recommend running with Address Sanitizer. In Xcode's scheme settings for your app, select the "Run" tab on the left, then the "Diagnostics" tab on the top. The first checkbox is "Address Sanitizer." (If it's grayed out, turn off "Malloc Guard Edges" or other settings in that group.) Check the box for Address Sanitizer and check the box for "Detect use Of stack after return". Rebuild, and run. Do whatever it is that triggers serialization. Address Sanitizer will likely stop your application and point out any address misuse you have. It's possible that even though it's not crashing on your system, you may still trigger Address Sanitizer when you read or write past the end of an array, or something similar.

---
Tags: unity, ios, assetbundle
---


# Question
Title: How much memory does a Game Boy game have for save data?
Is there a standard number of bytes a Game Boy game would have to store (battery backed up) save data?

If not a standard, is there an common size, or a few examples of save data sizes?

If Game Boy is not known, I'd be happy with the same information for NES.

Thanks!

# Answer
> 2 votes
Here's a map of the cartridges. It notes that

> MBC2 has 512 * 4 bit of internal memory used as back-up memory. It is accessed using A8..A0 and D3..D0.

and that

> The back-up memory is preserved by a 3V lithium battery together with a NV-RAM controller.

This reference of Game Boy information may be of use to you.

# Answer
> 0 votes
I do not know what you mean by battery backed up, since (as far as I know) cartridges use capacitors to save the bits. The game progress is stored inside the cartridges.

ROM: On-CPU-Die 256-byte bootstrap;\[26\] 32 KiB, 256 KiB, 512 KiB, 1 MiB, 2 MiB, 4 MiB and 8 MiB cartridges

https://en.wikipedia.org/wiki/Game\_Boy (source wikipedia)

If you mean internal storage these specifications may help you http://gameboy.mongenel.com/dmg/asmmemmap.html

Also see the reply of HardToFocus on how to save to cartridges: https://retrocomputing.stackexchange.com/questions/6405/game-boy-save-problem

---
Tags: console, homebrew
---


title: creating 2d array texture with mipmap

text:
# Question
Title: creating 2d array texture with mipmap
these day i am working with texture2d array with mipmapping. so this is how i tried so far. my approach

1. load multiple(not textureArray form) textures that i want to set as array from computer folder.
2. Ceate Texture2dArray interface with mipmap setting
3. using staging texture, copy multiple texture and write into the interface
4. Create SRV and Call 'GenerateMipMap' function.

and the result is that only first element of texture has right color values along with all mipmap level. but other elemets only have black, although they have same mipmap level which is black too.

this is my code(i checked all HRESULT/DirectX Debug checking, all good)

```
std::string key = ...;
std::vector<std::string> fileNames = ...;
UINT miplevel = ...;

    const UINT spriteCount = fileNames.size();

    std::vector<ID3D11Resource*> ori_resources(spriteCount);
    for (int i = 0; i < spriteCount; ++i)// 1------------------------------------
    {
        ID3D11Resource* newResource = nullptr;
        std::wstring wFileName = std::wstring(fileNames[i].begin(), fileNames[i].end());
        r_assert(
            DirectX::CreateWICTextureFromFile(
                DX_Device,
                (L"Data\\Texture\\" + wFileName).c_str(),
                &newResource,
                nullptr)
        );

        ori_resources[i] = newResource;

    }

    ID3D11Texture2D* newTex = nullptr;
        r_assert(
            ori_resources[0]->QueryInterface(IID_ID3D11Texture2D, (void**)&newTex)
        );
    D3D11_TEXTURE2D_DESC ori_desc;
        newTex->GetDesc(&ori_desc);

    D3D11_TEXTURE2D_DESC arr_desc; // 2------------------------------------------
    arr_desc.Format = ori_desc.Format;
    arr_desc.ArraySize = spriteCount;
    arr_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
    arr_desc.CPUAccessFlags = 0;
    arr_desc.Width = ori_desc.Width;
    arr_desc.Height = ori_desc.Height;
    arr_desc.MipLevels = miplevel;
    arr_desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
    arr_desc.SampleDesc.Count = 1;
    arr_desc.SampleDesc.Quality = 0;
    arr_desc.Usage = D3D11_USAGE_DEFAULT;

    ComPtr<ID3D11Texture2D> arrTex;
    r_assert(
        DX_Device->CreateTexture2D(
            &arr_desc, nullptr, arrTex.GetAddressOf())
    );

    for (int i = 0; i < spriteCount; ++i) // 3-----------------------------------
    {
        ComPtr<ID3D11Texture2D> stagTex;
        D3D11_TEXTURE2D_DESC stagDesc = ori_desc;
        stagDesc.BindFlags = 0;
        stagDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
        stagDesc.Usage = D3D11_USAGE_STAGING;
        r_assert(DX_Device->CreateTexture2D(&stagDesc, nullptr, &stagTex));

        // use staging texture to read and paste image
        // because for copying, we should match miplevels between dest and src
        DX_DContext->CopyResource(stagTex.Get(), ori_resources[i]);

        D3D11_MAPPED_SUBRESOURCE mapped;
        r_assert(DX_DContext->Map(stagTex.Get(), 0, D3D11_MAP_READ, 0, &mapped));
        // use 'UINT' because format of images from file is one of 8888
        UINT* arr = new UINT[(mapped.RowPitch/sizeof(UINT)) * ori_desc.Height];
        ZeroMemory(arr, mapped.RowPitch * ori_desc.Height);
        CopyMemory(arr, mapped.pData, mapped.RowPitch * ori_desc.Height);
        DX_DContext->Unmap(stagTex.Get(), 0);

        DX_DContext->UpdateSubresource(
            arrTex.Get(), i,
            nullptr,
            arr,
            mapped.RowPitch, mapped.DepthPitch);
        delete[] arr;
    }

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; // 4--------------------------------
    srvDesc.Format = ori_desc.Format;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
    srvDesc.Texture2DArray.ArraySize = spriteCount;
    srvDesc.Texture2DArray.FirstArraySlice = 0;
    srvDesc.Texture2DArray.MipLevels = miplevel;
    srvDesc.Texture2DArray.MostDetailedMip = 0;
    ID3D11ShaderResourceView* integratedSRV = nullptr;
    r_assert(DX_Device->CreateShaderResourceView(arrTex.Get(), &srvDesc, &integratedSRV));
    DX_DContext->GenerateMips(integratedSRV);

    SRVs.insert(std::pair<std::string, ID3D11ShaderResourceView*>(key, integratedSRV));

```

any advice would be really helpful for me now. thanks

# Answer
> 0 votes
```
DX_DContext->UpdateSubresource(
            arrTex.Get(), i,
            nullptr,
            arr,
            mapped.RowPitch, mapped.DepthPitch);

```

subresource parameter was wrong. a subresource is actually combination of mipmap level and array element. so we can use the formula 'curArrayelementIdx\*totalmiplevel + curmiplevel' or `d3d11calcsubresource`

---
Tags: 2d, textures, directx, mipmaps
---


# Question
Title: Moving an Enemy Toward the Player but only in cardinal+diagonal directions
I am working on a "quick project" to get my feet wet and to put something finished in my projects. I want to make an enemy that constantly tries to be aligned with the player object, but doesn't always move directly toward it, and which only moves in 8 cardinal directions. The idea is that if the enemy is not aligned with the player on the X axis, then the enemy will attempt to rectify by moving on the X axis until the player and enemy object are on the same x axis. At that point, the enemy should not move at all on the X axis unless the player changes its own X-position.

I coded this as the following:

```
    void OnEnable()
    {
        playerRef = FindObjectOfType<Player>();
    }

 void Update()
    {
        if (playerRef != null)
        {
            UpdatePlayerLocation();

            TryMove(playerPosition);
        }
        else
        {
            playerRef = FindObjectOfType<Player>();
        }
    }

    void UpdatePlayerLocation()
    {
        playerPosition = playerRef.transform.position;
    }

    Vector3 GetUpdatedFacing(Vector3 playerPosition)
    {
        Vector3 newFacing = Vector3.zero;

        if (transform.position.x != playerPosition.x)
        {
            newFacing.x = transform.position.x < playerPosition.x ? 1 : -1;
        }
        else { newFacing.x = 0; }

        if (transform.position.z != playerPosition.z)
        {
            newFacing.z = (transform.position.z < playerPosition.z ? 1 : -1);
        }
        else { newFacing.z = 0; }

        return newFacing;
    }

    void TryMove(Vector3 playerPosition)
    {
        //update facing
        transform.forward = GetUpdatedFacing(playerPosition);

        MoveTowardPlayer();
    }

    void MoveTowardPlayer()
    {
        transform.position += transform.forward * movementSpeed * Time.deltaTime; //movementSpeed = 5f for now
    }

```

This works to a point, except that as soon as the enemy becomes aligned with the player object (on either axis), rather than stop moving in the now-aligned axis, the enemy proceeds to rapidly move and rotate back and forth between the positive and negative facings of that aligned axis. For practical needs of the enemy, it is aligned and shouldn't be moving on that axis anymore. Despite this, it seems to rapidly go back and forth between being misaligned in very small increments.

I tried implementing a solution to this, namely, I expanded the check for the correction in movement to add a "buffer" of being off by 0.1f. Meaning that, if the enemy is within 0.1f in either direction of the player, then the enemy will ignore that input direction. This seems to produce the intended effect.

```
Vector3 GetUpdatedFacing(Vector3 playerPosition)
{
    Vector3 newFacing = Vector3.zero;

    if (transform.position.x != playerPosition.x)
    {
        newFacing.x += transform.position.x < playerPosition.x - 0.1f ? 1 : 0;
        newFacing.x += transform.position.x > playerPosition.x + 0.1f ? -1 : 0;
    }
    else { newFacing.x = 0; }

    if (transform.position.z != playerPosition.z)
    {
        newFacing.z += transform.position.z < playerPosition.z - 0.1f ? 1 : 0;
        newFacing.z += transform.position.z > playerPosition.z + 0.1f ? -1 : 0;
    }
    else { newFacing.z = 0; }

    return newFacing;
}

```

My only concerns are that:

1. I would prefer based on how I'm seeing it, that the enemy weights movements in cardinal directions above those in diagonal directions. At a future implementation, I intend to do that by having a "wall check" which will prevent movement in a given direction if a wall is blocking the path ahead. That said, I was looking to encourage cardinal movement more than others. Call it a peculiar desire if you want, I would like to see some ideas for how that could be done.
2. I am concerned about the 0.1 buffer being needed. Maybe less that the buffer is 0.1f, the real issue to me is that the buffer is needed at all. I am looking to see if any different implementation of the concept could improve the behavior so that this buffer wasn't necessary.

Maybe this is a bit more open-ended than some questions, if this is inappropriate, then I apologize for the format.

# Answer
The reason you see the rapid back and forth movement as it tried to align itself to the player's axis is because of overshoot, as you probably guessed. I reconstructed what I believe you are trying to do using Vector3.MoveTowards instead. This function is useful because it does not overshoot. Unfortunately this code is untested so let me know if it works.

To make it easier on myself, any instance where I refer to the "Target" you can think of it as the player, and I have chosen to define your 8 directional movement as "Ordinal directions". I'm also not sure why the formatting is so weird on this, I apologize.

Transform Target;
float speed = 5f;
Vector3 direction;

void OnEnable(){
    Target = GameObject.Find("Player").GetComponent();
}

void Update()
{
    if (Target != null{
        direction = GetOrdinalDirection(Target.position);

```
    MoveTowardsTargetAxis();
}
else{
    Target = GameObject.Find("Player").GetComponent<Transform>();
}

```

}

Vector3 GetOrdinalDirection(Vector3 targetPosition){
    Vector3 directionToTarget = (targetPosition - transform.position).normalized;
    Vector3 ordinalDirection = Vector3.zero;
    if (directionToTarget.x != 0f){
        ordinalDirection.x = directionToTarget.x / Mathf.Abs(directionToTarget.x); //If not 0, divide by the absolute of itself to make it 1 or -1
    }
    if (directionToTarget.z != 0f){
        ordinalDirection.z = directionToTarget.z / Mathf.Abs(directionToTarget.z); //If not 0, divide by the absolute of itself to make it 1 or -1
    }

```
return ordinalDirection.normalized; //normalize the ordinal direction to make sure diagonal speed isn't faster

```

}

void MoveTowardsTargetAxis(){
    Vector3 targetXaxis = new Vector3(Target.position.x, transform.position.y, transform.position.z);
    Vector3 targetZaxis = new Vector3(transform.position.x, transform.position.y, Target.position.z);

```
//Here you use Vector3.MoveTowards to make your x position move directly towards the Player's x axis, and your z position directly
// towards their z. Vector3.MoveTowards does not overshoot so you will not see your vibrating effect from before.
transform.position = new Vector3((Vector3.MoveTowards(transform.position, targetXaxis, speed * direction.x * Time.deltaTime)).x,
                                  transform.position.y,
                                 (Vector3.MoveTowards(transform.position, targetZaxis, speed * direction.z * Time.deltaTime)).z);

```

}

Edit: This does not include a weighted result towards a path that goes in cardinal directions. To be honest that's a bit of a strange concept because preferring cardinal directions would just mean you are always moving cardinally, since any point can be reached that way.
> 1 votes

---
Tags: unity, rotation, ai, game-loop
---


# Question
Title: Mixamo: can animations ("without skin") be re-used on any Mixamo rigged model?
I've discovered Mixamo very recently. I plan to use its auto-rigging capability on all my unrigged characters.

The download option can either include the skin or just obtain the animation.

My understanding is that an animation is "simply" applying a composite timeline where each bone is modified separately.

Am I right to believe that downloading an animation from Mixamo makes it compatible with every Mixam-rigged character? Or am I to download the same animations for each variation in my skeletons (arm length, hip width, neck size, etc.) ?

**Quick heads up: Mixamo**

Mixamo is an auto-rigging tool. For instance, this Blender character will be imported as a .zip (containing my .obj and .mtl)

You are just expected to place the following colored circles on your humanoid:

After the auto-rigging completes, you can either download your static, rigged character (as an .fbx) or animate it using one of the many free animations. After applying an animation (one at a time), you can either download the character (mesh) plus its anim or simply the bare skeletal animation.

Thanks!

# Answer
You're right, each Mixamo character has the same bone structure. So you can use any animation on any character.
> 1 votes

---
Tags: skeletal-animation, mesh
---


# Question
Title: 3D Collisions - Walking below a slope pushes me through the floor
Here's a really short video (less than 30s) of this issue : https://www.youtube.com/watch?v=JrKbpTY8cMU

When I move the player towards a slope (the player is below it), it pushes the player inside the floor Collider instead of blocking it.

I've searched the Internet for a while but haven't found anything about it

Do you have something in mind ?
Thanks for your time

Info : I move the player using `rigidbody.MovePosition()`

The collision of the player is a Capsule.

# Answer
> 1 votes
for these types of controlling objects you shouldnt use RigidBody that has non-Deterministic Behaviour. instead you have to use character controller. its simply works with Colliders and doesnt let character move byond them but has no physics in it. then you can use:

```
  characterController.Move(moveDirection * Time.deltaTime);

```

https://docs.unity3d.com/ScriptReference/CharacterController.Move.html

---
Tags: unity, collision-detection, 3d
---


# Question
Title: Can a character interact well with surroundings in-game?
I don't have any experience in game programming, but I am currently on programming-related degree, although on a different branch to game design.

I thought about how an environment can come more alive with player movement. For example, currently in many games once you hit a wall you would continue walking into that wall in one spot. I wanted to know, if there is a possibility to make interaction instead, etc. program a certain way to push towards the wall and listen, or lean against the wall, depending on joystick feedback. I wanted to push this even further to how player interacts with an object. For example, walking into a chair wouldn't just make the character be stuck on walking into the chair, but also make certain interactions like a strong fall if player runs into it and make the body of the player respond to what's happening as well. A further example would be placing something heavy on a chair for example, like a rock, and then if a player tries to push it requires more force which builds up, makes the chair make heavier sounds, and have the rock slightly rocking with the force.

Is this at all feasible in gaming and doable for a project? I have no experience in games, so it is hard to say what can be realised with today's tools like Unity or Unreal Engine.

# Answer
> 2 votes
Yes. This is all doable.

Limitations in games most of the time come from features being too heavy for the physics engine ("we can't simulate that many bodies at once, otherwise it trashed the framerate"), or simply because the feature does not add much to the look and feel of game (while taking more time from the dev team to figure out what needs to be done, how to do it, test it, etc.; it also adds risk).

So if the game does not really focus on this kind of behaviour, it's not added.

But really, if you wanted to have that as the main focus, it all doable.

# Answer
> 0 votes
The more you add conditions and reactions to certain actions like "if player hits a rock and position of joystick is in that direction" the more your code will be heavy.

You'll have to program even more animations which take a lot of time to actually draw and implement, and it will be multiplied by the number of different characters that could happen to make that animation.

If time and resources are not a problem, and if you are good enough at programming to know how to reduce the complexity of your algorithms, then you will totally be able to do what you want.

---
Tags: graphics-programming, objects
---


title: ANSI C Video Game Item System

text:
# Question
Title: ANSI C Video Game Item System
I am looking to program my own little **Role Playing Game** using...

* ANSI C or "standard C", (NOT C++) as my programming language
* The SDL2 development library

I have got a very basic and simple type of game up and going,
(I am learning ANSI C as I develop this hobby game).

I want to implement an item system to the game, so I have been looking through the internet for advice, but it seems like the closest I can get are solutions to C++, Java and other *object oriented languages*. I can't seem to find a good implementation in C, other than **THIS** guide, so I thought I could post this question specifically for ANSI C both for me and for others that might be looking to achieve the same goal.

My attack plan is to create a struct to lay out a blue print of what an item is, much like a class in an OOP language. Then, perhaps create an array that defines objects of this type and fills in the details for each item.

---

This is what I have so far:

```
#ifndef ITEMS_H_INCLUDED
#define ITEMS_H_INCLUDED

/* Create a structure that represent an item.
   @see https://www.tutorialspoint.com/cprogramming/c_structures.htm */
typedef struct Item {
    //Unique ID to be used as a reference to the item.
    unsigned int id;

    //Name of the item.
    char name[20];

    //Brief description about the item.
    char description[50];

    //Defines the category of the item; equipment, consumable, etc...
    unsigned char type;

    //Used for equipment; defines the strength of the weapon/armor.
    unsigned char stats[4];

    //The X and Y coordinates of the starting point of the sprite.
    unsigned int sprite[2];
}item;

#endif // ITEMS_H_INCLUDED

```

The **id-attribute** will be used to spawn the item in different locations, such as...

* In the player's inventory
* In a store
* On the floor to be picked up

I'm looking to hard code the item DATA in the source file, but I'm also open for solutions like reading item information from a file, and such.

# Answer
As for the way to store informations regarding items and stuff, there is nothing closer from a class in C than a struct. I would recommend using it.

As for retrieving datas from a file, I advise checking the Stack Overflow part of Stack Exchange considering it is dedicated to programming techniques and issues. A dozen of topics are about using files in C since its a bit tricky and can easily be done wrong (as everything in C I guess).
> 1 votes

---
Tags: rpg, c
---


# Question
Title: Mesh getting offset on combine because of worldmatrix
When I try to combine my mesh, it get offset to an other position, but the collider is still at the same place (because i dont delete and add it again). I saw a fix on internet that is to do:

```
Matrix4x4 myTransform = transform.worldToLocalMatrix;
combine[i].transform = myTransform*meshFilters[i].transform.localToWorldMatrix;

```

which worked in one of my script, but I just cant get it to work in this one. How can it be fixed ?

```
Vector3 cb = Vector3.zero;
Vector3 n = hit.normal;
Vector3 p = hit.point;

if(n == new Vector3(1.0f,0.0f,0.0f) | n == new Vector3(-1.0f,0.0f,0.0f))
{
    cb = new Vector3((n.x*0.5f)+p.x,Mathf.Round(p.y),Mathf.Round(p.z));
}
if(n == new Vector3(0.0f,1.0f,0.0f) | n == new Vector3(0.0f,-1.0f,0.0f))
{
    cb = new Vector3(Mathf.Round(p.x),(n.y*0.5f)+p.y,Mathf.Round(p.z));
}
if(n == new Vector3(0.0f,0.0f,1.0f) | n == new Vector3(0.0f,0.0f,-1.0f))
{
    cb = new Vector3(Mathf.Round(p.x),Mathf.Round(p.y),(n.z*0.5f)+p.z);
}
GameObject cub = Instantiate(cube,cb,Quaternion.identity);
GameObject dupli = Instantiate(hit.collider.gameObject,hit.collider.gameObject.transform.position,Quaternion.identity);
MeshFilter[] meshFilters = new MeshFilter[]{cub.GetComponent<MeshFilter>(),hit.collider.gameObject.GetComponent<MeshFilter>(),dupli.GetComponent<MeshFilter>()};
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
Matrix4x4 myTransform = meshFilters[2].transform.localToWorldMatrix;
combine[0].mesh = meshFilters[0].sharedMesh;
combine[1].mesh = meshFilters[1].sharedMesh;
combine[2].mesh = meshFilters[2].sharedMesh;
combine[0].transform = meshFilters[0].transform.localToWorldMatrix;
combine[1].transform = meshFilters[1].transform.localToWorldMatrix;
combine[2].transform = meshFilters[2].transform.localToWorldMatrix;
meshFilters[2].mesh = new Mesh();
Vector3 sP = meshFilters[2].gameObject.transform.position;
meshFilters[2].gameObject.transform.position = Vector3.zero;
meshFilters[2].mesh.CombineMeshes(combine);
meshFilters[2].gameObject.transform.position = sP;
Destroy(meshFilters[0].gameObject);
Destroy(meshFilters[1].gameObject);

```

# Answer
> 1 votes
This code is doing all sorts of stuff it doesn't have to, and as I've told you before, still is not the correct way to build your chunks.

If you want to keep doing this the way you have, here's what we can fix:

The first part can be drastically simplified - we don't need `if` statements to check the direction of the normal, and we can name our variable descriptively.

```
var placementPosition = hit.point + hit.normal * 0.5f;
for(int i = 0; i < 3; i++)
    placementPosition[i] = Mathf.Round(placementPosition[i]);

```

Next, we know we only need to combine two meshes: the mesh we started with, and the mesh we're adding. You can pre-allocate one array as a member variable:

```
CombineInstance[] _combinedPair = new CombineInstance[2];

```

Then just re-use it each time you call your block-spawning function, to save an unnecessary allocation.

```
var filter = hit.gameObject.GetComponent<MeshFilter>();

// Reproduce the existing mesh, exactly where it is already.
_combinedPair[0].mesh = filter.sharedMesh;
_combinedPair[0].transform = Matrix4x4.identity;

// Add a cube to it, at an offset from its center.
_combinedPair[1].mesh = cubeMesh;
_combinedPair[1].transform = Matrix4x4.Translate(filter.transform.InverseTransformPoint(placementPosition));

```

Here using a public variable to store our cube mesh, as shown in this answer, so we don't need to instantiate dummy cube objects only to later destroy them.

Then just combine your meshes into your current chunk and be done with it.

```
var chunkMesh = new Mesh();
chunkMesh.CombineMeshes(_combinedPair);
filter.sharedMesh = chunkMesh;

```

And if you need to apply the result back to your collision representation too:

```
((MeshCollider)hit.collider).sharedMesh = chunkMesh;

```

Note that this still:

* Allocates a whole new mesh every time you add a single cube.
* Includes all internal faces, without any hidden surface removal.

But at least we don't create and destroy sacrificial objects each time, so that's a slight improvement.

So again, please don't do it this way. Just use the answer I've linked you to twice now. But if you're going to do this inefficiently, at least be inefficient as efficiently as possible. ;)

---
Tags: unity, c#, mesh, meshcollider
---


# Question
Title: 2D sprite sorting and draw order relative to camera rotation
I'm having trouble working out how to recalculate 2D sprite sorting / draw order based on camera rotation.

In the example below:

**Screen 1** shows a non-rotated typical "top down 2D" scene, where the grey objects can be sorted based on their screen Y position, drawn from top to bottom, so in this case B, A, C.

**Screen 2** shows the situation after the player/camera rotates clockwise, with the original screen up vector (green) and the new up vector (red). In this situation, sorting by object Y position will not work, because A should now be drawn after C.

What I need to do is to sort the objects not only by their Y position, but also relative to the new up vector and/or camera rotation, but I'm unsure how to handle this.

# Answer
It turns out I was probably overthinking this quite a lot. The solution in the end was to just calculate the rotated position of the object by rotating their current position Vec2 by the inverse of the camera rotation. I could then sort by this rotated Y value.
> 1 votes

---
Tags: 2d, vector
---


# Question
Title: How do I model / diagram turn-based combat?
I'm developing a turn-based combat system for an RPG, and I'd like to know if there is any kind of best practice around diagrammatically modelling something like this.

The ideal modelling paradigm would capture quite a few things, including:

* entities (and their stats/status)
* entity actions / interactions
* positioning
* terrain effects
* temporal effects

Do I use something from UML? BPMN? A combination? Do I home-bake something?

To clarify: I'm not looking for any advice on designing the system. I'm already quite far along with that. I'm looking for a good way to diagram the model.

# Answer
> -1 votes
I would use OOP and detailed UML diagrams. Obviously a class diagram will help you a lot, but the more you use, the more you will have an accurate idea of what you will have to do and how it works. I would also recommend a Use-Case and State diagram too, if you are willing to spend a little bit of time concepting the thing.

You will never find one perfect diagram to visualise everything; you'll probably have to do a bit of everyting, because each diagram has its particular meaning and usefulness.

If you are not familiar with these concepts and want to have a quick look, here is a quick sum of the more used diagrams and why you should work on them.

> A UML diagram is a diagram based on the UML (Unified Modeling Language) with the purpose of visually representing a system along with its main actors, roles, actions, artifacts or classes, in order to better understand, alter, maintain, or document information about the system

---
Tags: game-design, turn-based, combat
---


# Question
Title: Centralized ResourceManager Class for every type of Asset in an Game Engine
I am trying to Implement resource manager for my hobby game engine. The problem I am trying to solve is that I want one centralized resource manager, which delegates resource loading to a bunch of "subsystems" which are each responsible for managing their own type of resource, like in the code below.

```
struct Resource {
    std:: extensionType;
    std::string path;
    int refCount;
};

class ResourceLoader {
    virtual ResourceType* loadResource(std::string) = 0;
    virtual void unloadResource(ResourceType*) = 0;
};

class ResourceManager {
    std::map<std::string, ResourceLoader*> _loaders;

    void addResourceLoader(std::string extensionType, FileLoader* loader);
    template<typename T>
    T* loadResource(std::string filePath);
    void reloadAll();
}

class TextureResource: public Resource {
    TextureHandle* handle;
};

class TextureLoader: public ResourceLoader {
    ResourceType* loadResource(std::string); //load + return a TextureResource
    void unloadResource(ResourceType*); //unload texture
};

//Later on, to use:
int main(int argc, char* argv[]) {
     ResourceManager resourceMgr;
     TextureLoader textureLoader;
     resourceMgr.addResourceLoader(textureLoader);
     TextureResource* texture = resourceMgr.loadResource<TextureResource*>("SOMETEXTURE.PNG");
     return 0;
}

```

This is just an example of my implementation. My problem shows up with more specific types of resources like Shaders. I want to store shaders as a ShaderSet or ShaderProgram ( in OpenGL every shader program has its own ID ), so when I am loading ShaderProgram, I need to specify at least vertex shader and fragment shader ( vertex filepath and fragment filepath ), but with my current logic I can't think of an elegant solution for this problem.

for example to have something like this:

```
T* loadResource(std::string vs_filePath, std::string fs_filepath);

```

I can't figure out how can I have ShaderProgram saved in the same resource manager class, any Ideas?

# Answer
Another way would be to implement type-erasure with inheritance and to implement the loading parameters with variadic templates. I think the end result is fairly clean, but offers no protections (you could probably write them yourself with `dynamic_cast`ing and proper type trait usage) against trying to load a shader with a single string parameter.

Note that I didn't test this in actual use, but the following should compile and give you the basic idea of how type-erasure is used here:

```
#include <string>
#include <map>

enum class ResourceType {
    Texture,
    Shader
};

struct Resource {
    std::string Path;
};

struct TextureResource : Resource {
    int ID;
    static constexpr auto Type = ResourceType::Texture;
};

struct ShaderResource : Resource {
    int Program, VertexShader, FragmentShader;
    static constexpr auto Type = ResourceType::Shader;
};

struct ResourceLoaderBase {
};

template <typename ResourceT, typename... Arguments>
struct ResourceLoaderImplBase : ResourceLoaderBase {
    virtual ResourceT* load(Arguments... arguments) = 0;
};

struct TextureLoader : ResourceLoaderImplBase<TextureResource, std::string> {
    TextureResource* load(std::string path) override {
        // ...
        return nullptr;
    }
};

struct ShaderLoader : ResourceLoaderImplBase<ShaderResource, std::string, std::string> {
    ShaderResource* load(std::string vert, std::string frag) override {
        // ...
        return nullptr;
    }
};

struct ResourceManager {
    std::map<ResourceType, ResourceLoaderBase*> loaders;

    void addResourceLoader(ResourceType type, ResourceLoaderBase* loader);
    template <typename ResourceT, typename... Arguments>
    ResourceT* loadResource(Arguments... arguments)
    {
        return static_cast<ResourceLoaderImplBase<ResourceT, Arguments...>*>(loaders.at(ResourceT::Type))->load(arguments...);
    }
};

```
> 2 votes

# Answer
You could always use a variadic template for your arguments. I wrote a similar system for fun a while back and it had something like this:

```
template<typename Resource, typename... Args>
struct ContentLoader : public ContentLoaderBase
{
    ContentLoader(std::function<Resource(const std::string&, Args...)> l)
    {
        load = l;
    }
    std::function<Resource(const std::string&, Args...)> load;
};

```

To which you could then create a ContentLoader

```
std::function<Shader(const std::string & name, const char* vertFilePath, const char* fragFilePath)> loadShader =
            [](const std::string& name, const char* vertFilePath, const char* fragFilePath)
        { // ... };

```

Then register it with your manager:

```
m_ContentManager.manage<Graphics::Shader>(new ContentLoader(loadShader));

```

With client usage:

```
auto shader = m_ContentManager.load<Graphics::Shader>("BasicShader", "./resource/shaders/basic.vert", "./resource/shaders/basic.frag");

```

You could then access all your ContentLoaders inside your manager and call load on them with a variadic template. This way you can pass in whatever you want as arguments. My take on this looks like this:

```
...
auto loader = static_cast<ContentLoader<T, Args...>*>(m_Loaders[std::string(typeid(T).name())]);
auto resource = std::make_shared<T>(static_cast<T>(loader->load(name, args...)));
...

```

Where I essentially just store all my loaders in a map to be retrieved later.

It's slightly different then your approach with inheritance and I am not quite happy with how my solution turned out in the end (it's a bit gnarly and registering loaders looks a bit funky to me) but it does meet the requirement of having an arbitrary number of arguments for your loader and I am sure you can adapt it to fit your scheme.
> 1 votes

# Answer
In my opinion shaders have too many dependencies to load it as separate resource. It's better to have a resource Material that will contain shaders, input layout, textures (as separate resources) and etc.
> -1 votes

---
Tags: c++, assets, resource-management
---


title: How to stop scrolling of text in OpenGL

text:
# Question
Title: How to stop scrolling of text in OpenGL
I want to set a time limit for scrolling text in OpenGL & GLUT. How can I stop scrolling at 250? Here is my code. I try with the if condition but it's not working. The scrolling is not stopping in 250, it scrolls infinitely.

```
#include<fstream>
#include<iostream>
#include<stdlib.h>
#include<glut.h>

using namespace std;
float yr = 0;
float translate =0.0f, angle = 0.0f;

//identifiers
void introscreen();
void screen();

void specialKey(int key, int x, int y) {
    switch (key) {
    case GLUT_KEY_UP:
        translate += 1.0f;
        break;
    case GLUT_KEY_DOWN:
        translate -= 1.0f;
        break;
    case GLUT_KEY_LEFT:
        angle += 1.0f;
        break;
    case GLUT_KEY_RIGHT:
        angle -= 1.0f;
        break;
    }
    glutPostRedisplay();
}
void SpeedText() {

    GLfloat y;
    GLfloat y2;
    GLfloat fSize[5];
    GLfloat fCurrSize;
    fCurrSize = fSize[2];
    for (y = 0.0f; y <= 250.0f + yr; y += 5.0f) {
        glLineWidth(fCurrSize);
        glBegin(GL_LINES);
        glVertex3f(-200.0f, y + translate, 0);
        glVertex3f(-180.0f, y + translate, 0);
        glEnd();
        fCurrSize += 1.0f;
        introscreen();
    }
    if (y + translate >= 50) {
        y == 50;
    }
    }
void renderbitmap(float x1, float y1, void *font, char *string) {
    char *c;
    glRasterPos2f(x1, y1);
    for (c=string; *c != '\0'; c++) {
        glutBitmapCharacter(font, *c);
    }
}

void introscreen(void) {
    glColor3f(0, 1, 0);
    char buf[10] = { '\0' };
    for (int row = 0.0f; row <= 250+yr; row +=5.0f) {
        sprintf_s(buf,"%d", row);
        renderbitmap(-220, (translate +row), GLUT_BITMAP_TIMES_ROMAN_24, buf);
    }
 }
int main(int arg, char** argv) {
    glutInit(&arg, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(width, height);
    glutInitWindowPosition(50, 100);
    glutCreateWindow("HUD Lines");
    display();
    SpeedText();
    glutSpecialFunc(specialKey);
    glutMainLoop();
    return 0;
}

```

# Answer
```
if (y + translate >= 50) {
    y == 50;
}

```

This doesn't actually do anything. `y` goes out of scope right after.

Instead you want to limit the value of `translate`.
> 1 votes

---
Tags: opengl, c++, rotation, scrolling
---


# Question
Title: Does Animator.SetBool take precedence over Animator.SetTrigger in Unity's Animator?
I've got an Animator with transitions from Idle to Walk or Dash. Walk requires isGrounded to be true and a float MoveX to be greater than .2. The Dash animation requires Dash trigger is returned. In my code, when the shift key is pressed I call anim.SetTrigger("Dash"), if a Walk key is pressed, I set anim.SetBool("Idle") to false and begin increasing MoveX. The problem I'm noticing is that when I play, and hit the dash button, it first starts walking and then after playing that animation it will then perform the dash animation. Looking in the animator as this is happening, it's clear that the walk animation plays in full before moving to the dash animation. What can I do to give priority to the Dash animation when that button is pressed?

# Answer
To me its looks like "has exit time" is check. so set your transition from walk to dash like this:

also apply same settings for transition Idle to Dash.

**"Has Exit Time"**: Exit Time is a special transition that doesn’t rely on a parameter. Instead, it relies on the normalized time of the state. Check to make the transition happen at the specific time specified in Exit Time.

For more information read unity manual here.

**Reason 2:**

Its looks like there is no direct transition from walk to dash. So first it complete walk animation then it goes back to idle and then dash. Just my assumption. If i am right then create direct transition from walk to dash whit 0 "exit time" and unchecked "has exit time", So when dash occurs animator will directly jump to the dash with out any delay.

I Hope this will help...
> 1 votes

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


# Question
Title: How can I make bullets come from a character's eyes, but look like they come from the gun?
How can I make bullets in a first person shooter look like they come from the gun, but actually come from the eyes of the character? The problem is that since the camera (the character's eyes) are in a different position than the gun, bullet animations coming from the gun won't end up at the crosshairs. This guy manages to do it, and it's more obvious at 5:17 when the bot is shooting at him. This also happens in CS:GO

I was thinking that maybe the final destination of the bullet is calculated, and then the path is traced backwards to the gun from there, but it's just a guess.

# Answer
> 2 votes
The reason that bullets coming from the gun don't work with the cross hair is because the cross hair represents where the bullet would go at an infinite distance.

You can't make the bullet look like it comes from the gun but actually come from the eyes without causing some problems. Specifically, where the bullet looks like it's going and where it hits won't be the same place.

**The Problem**

Here's a set of illustrations that show how/why I say this...

First, this is a representation of a player shooting from the hip. The red dot represents where the cross hair aim point. The horizontal green line is the view from eye to aim point (through cross hair). The red line coming from the gun is the actual bullet travel line.

Here is the same setup if the shooter is holding the gun up (iron sights). This is what's happening in the example you reference in the video at 5:17.

Now let's go back to the first case, but add a target that's in front of the player, and fairly close.

You can see now how where the cross hair looks like it's targeting and where the shot hits isn't the same. And that's a problem, because it might actually mean a miss if the hit boxes are more complex, or if you are rendering a hit decal at the impact point. Either the player shoots at what looks like a perfect target and misses, or the player shoots and hits, but the hit indicator isn't where they shot.

But of course if they are holding the gun up to their eyes (iron sights), it's just fine...

**The Solution**

First, here's the problem we want to solve. We want to hit the spot that the cross hair is on, like this...

The first thing you need to do is calculate where the point is that your eye is on the target. In other words, calculate where the line drawn from eye to aim spot (cross hair) would hit.

Once you have this point, there are two things you should do.

First, when you draw the streak of the bullet, draw it from the tip of the gun to this newly calculated point...

It's not super clear in my illustrations, but the problem is though your gun isn't quite pointing the same way as the shot. And the closer the target is to you, the worse it will be. So the second thing to do is rotate the first person gun model up a bit so it's pointing at the impact point, like this...

And now, everything is all good!

It might look a little bit off if the target were literally right in front of the player - like if they were face into a wall. You can actually fix this by having the player lift the gun up more as the target gets closer, so the rotation is less.

**Alternate Solution** If the gun has a laser sight, then you will always be calculating that point where the laser (coming from the gun) illuminates the target. When the player shoots, the bullet hits where the laser sight is. It is maybe a little disconcerting that the cross hair and the laser illumination dot aren't in the same spot, but it does help a bit.

# Answer
> 0 votes
You just need to use basic geometry.

If you know the distance to the target and you know the distance between your character's eyes and, for example, the weapon's muzzle, you simply apply the Pythagorean Theorem and get the distance from the two points (muzzle and target).

Then you get the direction vector by

```
Vec3 direction = (targetPosition - muzzlePosition).normalized()

```

Now you can spawn a bullet in the position of the muzzle with that direction vector.

You can calculate whether the bullet would hit or not by raycasting from the eye's position and how much time the bullet would need to get from the muzzle to the target by using the formula

```
Time = distance ÷ speed

```

Having that time you can play around with bullet spawning, special effects, sound, etc.

Hope it helps. Update the question and comment if there's anything else or unclear.

# Answer
> 0 votes
It's relevant to note that most games do not use the bullet object to detect hit, as bullets move in very high speed and are expensive to check collisions with.

Instead, animate the bullet coming out in a way that looks good and calculate the hit point by using something like a raycast.

That way you won't face the problem highlighted on the other answer that involves the reticle being at the infinite distance.

Also, while this may seem like it can only work for instant shooting (the bullet travels at infinite speed and hit all it's trajectory at once). However, you can shoot these days with limited length and every *x* frames you can angle the shot down (to simulate bullet travel) and send a new raycast.

Important to note, this "angling down" is just in the variable space, the visual of the bullet does not matter for this.

---
Tags: first-person-shooter
---


# Question
Title: How to set the force applied to RigidBody2D depending on the time user holds touch on screen?
I trying to make an object jump from 1 point to another point. How far it jumps depends on how long the player holds the touch anywhere on the screen. It jumps when player releases his touch.

At the code below,I able to detect the moment player release his finger.

```
if (Input.touchCount > 0) {
    Touch touch = Input.GetTouch(0);

    // Handle finger movements based on touch phase.
    switch (touch.phase) {
        // Finger start touching the screen
        case TouchPhase.Began:
            print("Start tapping");
            break;

        // Finger leaving the screen
        case TouchPhase.Ended:
            //when finger release, the object jump
            float rightForce = Time.deltaTime * 10000 / 2;
            float jumpForce = Time.deltaTime * 30000 / 2;
            box2D.AddForce(new Vector2(rightForce, jumpForce), ForceMode2D.Force);
            break;
    }
}

```

As you can see I able to get the `Time.deltaTime` which is I assume is how long the player hold the screen.

What I want to do is calculate the `rightForce` and `jumpForce` added to the object depending on the Time user hold the touch.

```
float rightForce = Time.deltaTime * 10000 / 2;
float jumpForce = Time.deltaTime * 30000 / 2;

```

Because if I use the 2 line of code above, the result will be almost the same everytime.

So what is the correct way to determine the `rightForce` and `jumpForce` depending the `time` user hold touch?

# Answer
> 3 votes
> As you can see I able to get the Time.deltaTime which is I assume is how long the player hold the screen.

Your assumption is wrong. `Time.deltaTime` gives you the time elapsed between the last frame and current frame.

Your question boils down to "How do I measure touch time across multiple frames?". And the answer is simple: You accumulate the delta time between frames.

```
public float touchTime;

private void Update() {
    if (Input.touchCount < 1)
        return;

    var touch = Input.GetTouch(0);

    switch (touch.phase) {
        case TouchPhase.Began:
            touchTime = 0;
            break;
        case TouchPhase.Ended:
            Debug.Log($"The player touched the screen for {touchTime} seconds.");
            break;
        default:
            touchTime += Time.deltaTime; //<<<<<The bit you are misunderstanding and missing
            break;
    }
}

```

This should be enough for you to understand what's wrong and how to fix it. Learning from the code above to make your own code work is left as an exercise for you.

Note that you can simplify this by making the system based on timestamping rather than accumulation. For that, `Time.time` gives you the time in seconds since the start of the game. But again, that is left as an exercise for you.

Have fun.

---
Tags: unity, physics, rigidbody
---


# Question
Title: C++ Passing Functions to Objects/Projectile system woes
I am new to C++ development and I am trying to create a more flexible projectile system.

In my current system I apply a equation to move the point down the bullet path.

```
class Bullet{
    public:
      float x;
      float y;
      float speed;
      float angle;

     void Update(){
     x=(speed*cos(angle)) + x;
     y=(speed*sin(angle)) + y;
     };
}

```

This works fine for moving a bullet on an angle, however I would like to generate much more complex paths, without over complicating the bullet class.

My idea was to pass a function to the bullet class that would be used to move the object but I have not found any way to do this.

Example of what I want to do:

```
class Bullet{
    public:
      function dostuff();
      float x;
      float y;
      float angle;

     void Update(){
     dostuff(x,y,angle,speed);
     };
};

class Enemy{
    public:
      float x;
      float y;
      float speed;
      float angle;

     void shoot(){
      Bullet bullet;

      auto movangle = [](float x, float y, float angle,float speed)
      {
         x=(speed*cos(angle)) + x;
         y=(speed*sin(angle)) + y;
      };
      bullet.dostuff = movangle;
      bullet.Update();
     };
};

```

If anyone knows of any ways to implement a system like this, or ideas on alternatives that could produce similar results It would be appreciated as I am somewhat stumped.

# Answer
The specific feature you're looking for in C++ is std::function. I am not saying that this is the best way to implement the actual feature you've asked for (though it's a perfectly sufficient one for some games!), but it is the solution you've asked for help implementing. :)

```
class Bullet{
    public:
      std::function<void(float x, float y, float angle, float speed)> dostuff;
      float x;
      float y;
      float angle;

     void Update(){
       dostuff(x,y,angle,speed);
     };
};

```

For functions that are reused in many places, it can be handy to make a type alias for convenience:

```
using DoStuffFunction = std::function<void(float x, float y, float angle, float speed)>;

class Bullet{
    public:
      DoStuffFunction  dostuff;

      ...
};

```

Other approaches might include sub-classes and virtual as the other answer suggested, using an `enum` that controls different behaviors, or decomposing `Bullet` into different data structures (e.g. in an ECS architecture). Each of these have pros and cons.
> 1 votes

# Answer
You could use a new class `BulletPath` (or something) which would handle all the movement angles and stuff of the bullets. It would be created by the object who fires and used in the class `Bullet` to control its movement. The advantage is that you could make a different path for any kind of `Enemy`. You'll just have to add it as a parameter in the `Bullet` class. Any `Enemy` could have its own `BulletPath` depending of what you want to do.

```
class BulletPath { // can be extended
    float x;
    float y;
    // all the parameters you need
    public void move(Bullet bullet)
    {
           // move it
    }
     // you could use BulletPath
     // as an interface too to be even
     //  even more flexible.
}

class Enemy {
    private BulletPath path; //initialize it

    public void shoot() {
        path.move(new Bullet());
        // do what you want
    }
}

```

If you are a bit used to C++, you could also use functors, which principle and utilisation is explained here on StackOverflow. To sum it up, it allows you to have a class which also can be used as a function. You just call `Bullet()` when you need it to move and handle the movements in a function in `Bullet` (which will be a function overriding the operator `()`).
> 0 votes

---
Tags: c++
---


title: Unity Jumping bug

text:
# Question
Title: Unity Jumping bug
I'm working on a basic movement system for the player in a 3D Box platformer and for a month I've been having problems with the double jump system. The one bug that I still can't figure out is whenever I press the jump button, it has a force that is also pushing the box to the negative direction of the x-axis.

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

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;

    [SerializeField] private float force;
    [SerializeField] public float jumpForce;

    float doubleJumpCount = 0;

    bool doubleJump;

    bool jump;
    bool forward;
    bool backwards;
    bool left;
    bool right;

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.collider.name == "Floor")
        {
            doubleJumpCount = 0;
        }
    }

    // Update is called once per frame
    void Update()
    {
        jump = Input.GetButtonDown("Jump");
        left = Input.GetButton("Left");
        right = Input.GetButton("Right");
        forward = Input.GetButton("Up");
        backwards = Input.GetButton("Down");

        if(jump)
        {
            Debug.Log("doubleJumpCount = " + doubleJumpCount);
        }
    }

    void FixedUpdate()
    {
        if(right) rb.AddForce(Vector3.right * force * Time.deltaTime);
        if(left) rb.AddForce(Vector3.left * force * Time.deltaTime);
        if (forward) rb.AddForce(Vector3.forward * force * Time.deltaTime);
        if (backwards) rb.AddForce(Vector3.back * force * Time.deltaTime);

        if (jump)
        {
            Jump();
        }
    }

    void Jump()
    {
        if(doubleJumpCount >= 2)
        {
            return;
        }
        else
        {
            rb.velocity = Vector3.zero;
            rb.AddForce(Vector3.up * jumpForce * Time.deltaTime);
            doubleJumpCount++;
        }
    }
}

```

I have a suspicion that it might have something to do with the settings i have set for the jump button in the project settings. Or maybe should I use the transform class instead of using a RigidBody3D class to manipulate movement?

# Answer
The center of mass of your rigidbody might be messed up, resulting in unexpected behavior when applying a force to it.

Try setting the velocity of the rigidbody instead of adding a force when jumping:

```
void Jump()
{
    if(doubleJumpCount >= 2)
        return;
    else
    {
        rb.velocity = Vector3.up * jumpForce;
        doubleJumpCount++;
    }
}

```

Hope this helps!
> 1 votes

---
Tags: unity, physics, scripting
---


# Question
Title: How to Make Different Instances of an Object Have Different Sprites
In Game Maker, I am trying to make it so that three instances of an object have three different sprites. Using DnD, what would be the optimal way to do this? If it helps, the three instances are different sizes and are in separate, fixed places.

EDIT: I have added the following, and it gives an error that the global variable has not been set.

# Answer
**To do this, you will need:**

* 1 controller/administrator/creator object (`obj_Hades` in my project)
* 1 global variable (`global.number` in my project)

The controller object (`obj_Hades`) will basically serve for you to declare the global variable (`global.number`).

**Note that a sprite contains 3 images/frames:**

**In the controller object (obj\_Hades):**

Be careful to place the controller object to be initialized first (see lower left corner of image above).

**In the object to have three different shapes:**

Remember to set the `image_speed` variable to 0, so that you don't run an animation.

**Result:**

**Reference:**

https://docs.yoyogames.com/source/dadiospice/002\_reference/001\_gml%20language%20overview/variables/global%20variables.html

---

**If you have separated the images:**

Just make use of `IF'S`.

---

**EDIT 1**

**Test done with your project:**

I deleted the 3 objects and added them again. I realized that the ones you had placed in the room were different sizes, I don't know where you modified them, but apparently that was the cause of the problem.
> 0 votes

---
Tags: sprites, gameobject, game-maker-dnd
---


# Question
Title: Casting Civilization V based Hex Grid on Unity Terrain and Select Certain Areas of Grid
I am looking for approach for casting hex based grid on terrain which is for now pre-made but eventually it will be procedural for my exploration game where you can scan planet and elements will be highlighted/hex grid selected. What could be the approach towards making this kind of hex grid as my terrain will be un-even.

I have seen approaches like mesh creation, using tile-map, unity projectors but eventually I feel like this should be something using shaders but what about selection?

Can someone please guide me in a right direction.

# Answer
> 9 votes
There's a useful isomorphism we can exploit between hex grids and square grids: with a simple shear transformation, we can transform one into the other.

We'll use this in two ways:

* We'll use the regular tiling of these square tiles (and their symmetries) to chart out the hexagonal grid lines we need to draw.
* We'll use the square grid layout to store our mask of selected tiles into a conventional 2D texture, where each texel maps to one hex tile, letting us read an arbitrary selection shape in our shader.

This requires a little kijiggery: squares aren't hexagons, after all. So even after we've done our shearing, we need to nip off a couple corners of the square and "donate" them to adjacent tiles - and accept donated corners from our neighbours - to restore the desired hexagonal shape.

Here's a utility function we can use to do most of this magic in our shader. This takes a 2D coordinate in the range \[0, 1\]x\[0, 1\], representing our position within one of these square tiles. It returns an offset to which square tile "owns" the hexagon this point belongs in, and while it's at it, computes the distance to the closest edge of the hex grid, so we can use this to draw the grid lines.

To save ourselves some cases, we'll use the symmetry of the tile:

First we'll "fold" the tile along the diagonal line y = x: if our point is in the upper-left triangle of the tile, we'll pretend it's in the lower-right instead, and adjust the offset we report back to compensate.

Then if we're in the upper-right half of the triangle remaining, we'll fold again to consider only the bottom quarter of the square. That means we need to look at just one diagonal edge instead of 4. :)

```
float2 ClosestHexShift(float2 p, out float edgeDistance) {

     // If we don't do any folding, we're already in the bottom quarter.
     // So if we need to donate this point to an adjacent tile,
     // it will be the one below us.
     float2 shift = float2(0, -1);

     // If we're in the top-left half, fold down to the bottom-right half
     // along the line y = x (so our "bottom" neighbour is really to our left)
     if (p.y > p.x) {
        p.xy = p.yx;
        shift = float2(-1, 0);
     }

     // If we're in the top-right of what remains, fold down to the bottom quarter
     // along the line y = 1 - x (so our "bottom" neighbour is now to our right/above)
     float2 complement = 1.0f - p;
     if (p.y > complement.x) {
        p = complement.yx;
        shift += 1.0f;
     }

     // Compute a signed distance from the diagonal edge.
     edgeDistance = ((p.x - 0.5f) / 2.0f + p.y);

     // Check if we're above the diagonal, in the "body" of the hex.
     // If so, our closest edge is either the diagonal itself,
     // or the line through our bottom-right corner.
     if (edgeDistance > 0.0f) {
        edgeDistance = min(edgeDistance, (1.0f - p.x + p.y) / 2.0f) * sqrt(3.0f);
        return (float2)0; // No shift required!
     }

     // Otherwise, this is a corner we need to clip off and donate to a neighbour.
     // Our closest edge is either the negative diagonal,
     // or the edge through our bottom-left corner
     edgeDistance = min(-edgeDistance, (p.x - p.y)/ 2.0f) * sqrt(3.0f);
     return shift;
}

```

You can use this in a shader - say a surface shader where you've added a `worldPos` value to the `Input` struct to expose the worldspace coordinates of the fragment being shaded inside the surface function.

```
void surf (Input IN, inout SurfaceOutputStandard o)
{
    // Project our worldspace position into the XZ plane,
    // and scale so the tiles have the desired (outer) radius / edge length.
    float2 hexSpace = IN.worldPos.xz / _TileRadius;

    // Apply our shear to map our hexagons into the square grid.
    // You can also apply an offset here to change where the origin sits in your texture.
    float2 squareSpace = float2(
                         2.0f/3.0f * hexSpace.x,
                        -1.0f/3.0f * hexSpace.x + 1.0f/sqrt(3.0f) * hexSpace.y);

    // Round down to the closest integer, to identify which square tile this represents.
    // Then subtract, to get our position within the tile.
    float2 cell = floor(squareSpace);
    float2 fraction = squareSpace - cell;

    // Shift our "owning" tile using our corner-clipping function.
    float edgeDistance;
    cell += ClosestHexShift(fraction, edgeDistance);

    // Look up our tile's info in our texture (mine happens to be 128x128 pixels).
    // For a simple demo, I'll pipe this out the albedo so we can see what we're getting.
    // Be sure you disable mipmaps and set filtering to "point" to avoid blending.
    fixed4 tileInfo = tex2D(_MainTex, cell / 128.0f);
    o.Albedo = tileInfo.rgb;

    // Calculate how many pixels we are from the edge of our grid line,
    // for a smooth anti-aliased effect.
    float2 velocityX = ddx(hexSpace);
    float2 velocityY = ddy(hexSpace);
    float speed = sqrt(dot(velocityX, velocityX) + dot(velocityY, velocityY));

    float pixelDistance = (edgeDistance - _LineThickness) / speed;

    float edgeStrength = 1.0f - saturate(pixelDistance);
    o.Emission = edgeStrength * _Color;

    // Leaving this as-is at their defaults from the shader template.
    o.Metallic = _Metallic;
    o.Smoothness = _Glossiness;
    o.Alpha = tileInfo.a;
}

```

Here's the results we have so far, using a texture full of random coloured pixels as a stand-in for our selection mask:

From here, you can duplicate the math for mapping from world space to texture space in a C# script, to translate a raycast hit from a mouse click into a pixel in the selection texture that you need to change. You can also adjust the shader to do something a bit nicer for selected pixels, like applying a highlight or glow blended on top of the base terrain texture.

---
Tags: unity, grid
---


# Question
Title: How does one make models that are proportionate to the other game assets you've made?
As a programmer, I am not very good (yet) at making game art. One of the many issues that often causes me trouble is asset creation.

Often I will want to create a house that a player could enter, and when the asset is made in blender, it looks right. But then once the asset is imported into whichever engine I am using I will find that the proportions of the doors or windows look completely inconsistent with all the other assets. Sometimes even the entire buildings proportions are off in comparison to the rest of the buildings.

Even worse, I find that my player model is either dwarved or enlarged by the scale of my models. Resizing the models doesn't help because of the proportions.

The question is, how does one design consistently proportioned assests that fit the scale of the player?

# Answer
> 1 votes
---

## Preventing bad proportions

Aside form using actual measures (which is what, being and engineer, I would do for architectural and mechanical designs), there are a few practices that would help an artist keep proportions:

* Always add a "measure of a man" model. That is a humanoid model of the right size and proportion of the avatar in game to use as reference. It does not need to have any detail – all that matters is that it has the proportions you need. You can move it around to see if it fits doors and if windows are at the right height. In fact, you can have multiple (standing vs sitting, child vs adult, and so on). *This also means you will not be exporting the whole file, just export a selection.*
* Have multiple models that need to work together in a single file. You are exporting selections anyway, thus, if you need multiple things to work together, then work on them together... this ensure they are consistent. *This also means that any models that need to be worked together get assigned to the same artist.*
* Decide on width/height ratios, document it. In particular, you can use the golden ratio (which is not uncommon in architecture). Make sure that elements such as doors and windows follow the proportions you decided. *See also the standard paper sizes (ISO 216).*
* Have a minimum thickness for elements (walls and bevels in particular). In games, this could help with visual artifacts (such as shadows effects). *It is also vital if you were doing models for 3D printing.*
* For modeling complex things, in particular organic things, I would argue for using photo references (or even tangible references). *And no, using references is not "cheating".*

Also check is the field of view of the perspective camera, if you are working with a different field of view in the editor than in the game, you could be making the wrong judgment.

**Addendum**: About the "measure of a man" model, sometimes a simple block will do. For most cases a block for the head, a block for each arm, and a couple blocks for the legs is all you need. However, if you have a rigged low-poly model, why not use that?

---

## Checking for bad proportions

Aside from using actual measures and from having a reference model you can use to compare...

Change to orthographic projection to check. I mean, in your 3D editor. While humans are very good at guessing proportions in perspective, we are also capable of tricking ourselves. Which reminds me, do not forget to inspect the model from different angles and zoom levels. *However, I am guessing you already do that.*

If all else is failing... I suppose the next best thing is to import often as part of the modeling proccess.

---
Tags: assets, 3d-modeling, asset-creation
---


# Question
Title: Angle between character and mouse, and giving bullets velocity in the correct direction
I've been trying to work for a few days, on a little weapon system where you can aim with your mouse and shoot bullets in the direction you're aiming. This is all in 2D to be clear.

Right now, I can calculate the spawn point of the bullet at the tip of the gun quite well and the angle of the sprite is correct and pointing at the mouse however, I believe I am actually calculating the angle somehow inversely and because of this, I can't find a good way to give the bullets; when spawned; the correct starting velocity to fire in the correct direction as well as the correct sprite rotation.

I am calculating and setting the angle of the sprite to the angle given between the mouse position and the character position like so: (Following code is in the Vector2 class)

```
double
Vector2::AngleRad(Vector2* other) {
    return atan2(other->y - y, other->x - x);
}

double
Vector2::AngleDeg(Vector2* other) {
    return radiansToDegrees(AngleRad(other));
}

```

and calculating the bullets spawn point (which works right now with the given angle, even though it's reversed) like so: (Following code is in the weapon class)

```
void
Weapon::CalculateBulletExit()
{
    double centerX = GetPos()->x + GetCollisionBox()->W() / 2;
    double centerY = GetPos()->y + GetCollisionBox()->H() / 2;
    double radius = GetCollisionBox()->W() / 2;

    double radiansDeg = degreesToRadians(entityAngle);

    pointOfExit->x = (centerX + radius * cos(radiansDeg));
    pointOfExit->y = (centerY + radius * sin(radiansDeg));
}

```

So now I want to spawn a bullet at the correct position (the tip of the gun) with the right sprite rotation, and the the correct object velocity. Right now this is how I am doing that: (Following code is in the bullet class)

```
bool
Bullet::Spawn(double heading, Vector2* spawnPoint, double bulletSpeed)
{
    if (mat->dead) {
        //Make the bullet alive and then return true that the bullet has been spawned
        mat->dead = false;

        //Set position and initial velocity
        double xGoPos = spawnPoint->x - GetCollisionBox()->W() / 2;
        double yGoPos = spawnPoint->y - GetCollisionBox()->H() / 2;

        entityBox->X(xGoPos);
        entityBox->Y(yGoPos);

        linearVelocity->x = xGoPos + cos(degreesToRadians(heading)) * bulletSpeed;
        linearVelocity->y = yGoPos + sin(degreesToRadians(heading)) * bulletSpeed;

        entityAngle = heading;

        return true;
    }
    else {
        return false;
    }
}

```

But this is spawning the bullet with a sprite rotation facing 180° backwards, and a velocity weirdly pointing downwards and away. Plus the velocity seems to always towards the right even when I am aiming left.

What is the easiest and fastest way of giving a bullet a velocity in the direction of the mouse (aiming direction) and am I actually calculating the angle correctly or horrifically wrong? :P

From what I've researched and read, there's heaps of ways of getting the angle between two vectors but all I am able to precisely know is the character's bounding box as x, y, w, h. The weapon bounding box as x, y, w, h. And the mouse position as an x, y vector2 class I made. Thanks for any suggestions and help that I get!

# Answer
> 1 votes
To inverse the spawn point and other useful methods:

```
// renamed
double Vector2::AngleRadOther(Vector2 other)
{
    return atan2(y - other->y, x - other->x);
}

// renamed
double Vector2::AngleDegOther(Vector2* other)
{
    return radiansToDegrees(AngleRadOther(other));
}

double Vector2::AngleRad()
{
    return atan2(y, x);
}

double Vector2::AngleDeg()
{
    return radiansToDegrees(AngleRad());
}

double Vector2::GetLength()
{
    return sqrt(x * x + y * y);
}

void Vector2::Normalize()
{
    double length = GetLength();
    x /= length;
    y /= length;
}

```

Fix for velocity:

```
bool Bullet::Spawn(Vector2* headingVec, Vector2* spawnPoint, double bulletSpeed)
{
    if (mat->dead)
    {
        double headingDeg = headingVec->AngleDeg();

        //Make the bullet alive and then return true that the bullet has been spawned
        mat->dead = false;
        //Set position and initial velocity
        double xGoPos = spawnPoint->x - GetCollisionBox()->W() / 2;
        double yGoPos = spawnPoint->y - GetCollisionBox()->H() / 2;
        entityBox->X(xGoPos); entityBox->Y(yGoPos);

        // Normalize vector so that its length is 1
        headingVec->Normalize();

        linearVelocity->x = headingVec->x * bulletSpeed;
        linearVelocity->y = headingVec->y * bulletSpeed;

        //linearVelocity->x = xGoPos + cos(degreesToRadians(heading)) * bulletSpeed;
        //linearVelocity->y = yGoPos + sin(degreesToRadians(heading)) * bulletSpeed;

        entityAngle = headingDeg;
        return true;
    }
    else
    {
        return false;
    }
}

```

You didn't post the code that calls `Spawn` but the `Vector2 headingVec` argument should be `mousePosition - entityPosition` entityPosition beeing the position of the entity from which the projectile is launched.

My c++ skills are *very* lacking so watchout for syntax errors!

---
Tags: physics, vector, sdl2, bullet-physics
---


# Question
Title: What are the "axes of a matrix" exactly?
I am currently learning about game engines, and for the engine math, there are functions called GetXAxis, GetYAxis, and GetZAxis that returned the X, Y and Z axes for a matrix. These functions return the x, y and z components of the first three rows of the 4x4 matrix as a normalized Vector3. The actual functions are simple enough, but I am having trouble conceptually understanding what exactly the axes of a matrix are. Are they the forward, left, and up vectors of a transformation?

# Answer
> 0 votes
A matrix can be represented as a set of its basis vectors (that is local, X, Y and Z), so that if we have a matrix `m` with vectors represented as `a`, `b` and `c`, to transform vector `v` with matrix `m`, we need to sum multiplication product of each coordinate of a vector with the corresponding axis vector of the matrix:

`transformed_v = m.a*v.x + m.b*v.y + m.c*v.z`

2D graphical representation of the process is demonstrated here

---
Tags: matrix, transformation, terminology
---


title: Unity Event Pause/Unpause & jump frame

text:
# Question
Title: Unity Event Pause/Unpause & jump frame
Hello, I would like to get in a script the event whenever we click on the pause button, or the Jump frame button.

I have already manage the Pause button:

```
private void OnEnable()
{
    EditorApplication.playmodeStateChanged += HandleOnPlayModeChanged;
}

private void OnDisable()
{
    EditorApplication.playmodeStateChanged -= HandleOnPlayModeChanged;
}

private void HandleOnPlayModeChanged()
{
    if (EditorApplication.isPaused)
    {
        // do stuff when the editor is paused.
    }
    else
    {
        // do stuff when the editor is unpaused
    }
}

```

But How to get the "jump frame" button ? Thanks !

# Answer
> 2 votes
Because you can determine when the pause button is pressed you can use this to then deduce when a "jump frame" would have occured.

Essentially, when its in pause, one "frame" would call the update funtion, `Update()` or `FixedUpdate()` once. * *Fixed Update only will work to the framerate of the physics system (Default of 50fps)*

```
bool isPaused = false;

//Code you have provided
private void OnEnable()
{
    EditorApplication.playmodeStateChanged += HandleOnPlayModeChanged;
}

private void OnDisable()
{
    EditorApplication.playmodeStateChanged -= HandleOnPlayModeChanged;
}

private void HandleOnPlayModeChanged()
{
    isPaused = EditorApplication.isPaused;
}

//Update function to check every frame
void Update()
{
    //If a frame has passed in pause then it can be assumed a frame skip has occured
    if (isPaused)
    {
        //Do something when frame skip has occured
        print("skipped a frame");
    }

}

```

---
Tags: unity, editors
---