# Question
Title: How can I create character graphics similar to Valkyrie Profile?
I want to create a game with the character graphics similar to Valkyrie Profile.

I don't know whether I should make my game character sprites pre-rendered or hand drawn, or which technique would let me create a similar look.

Are these created pixel by pixel, what sets me off is the ditter found in a lot of the images, kind of looks like the characters from treasure hunter G or harvest moon friends of mineral town.

@edit Added the screenshots from Treasure Hunter G and Harvest Moon. I know these are pre rendered sprites that are later incorporated into the game, just for comparison against the valkyrie profile ones. Also, the treasure hunter G is a SNES game, and the Valkyrie Profile is PSX one, so I expect an upgrade in graphics.

# Answer
These animations look like traditional pixel art to me. They can be created by artists in any raster-oriented image editor by placing each pixel individually. This art style does not require complex software. There is specialized software available like Asesprite, but the basic techniques can just as well be learned and applied in any general purpose image editor, even in a very simple one like MS Paint.

There are some filters available which can turn 3d renderings into convincing looking pixel art. One of my favorite applications of this is from the game *Saints Row IV* where they suddenly turn a high-budget 3d game into a retro pixel art beat-em-up. You can tell it's not hand-pixeled, because it applies the extensive character customization options to the player-character. Doing every single outfit again in pixel art would have been far too much work just for this short sequence.

But I don't believe that such a filter was applied in the example animations from this question. The art looks far too traditional to me when it comes to "pixel economics" (using exactly as many pixels as needed for every detail). It also does some very neat cloth and hair animations which would be very tedious to do that way in 3d but are actually not that hard (still not trivial, though) to do for an experienced pixel artists.

Pixel art is an artistic medium which is easy to learn, but hard to master. In order to be able to create animations in that level of quality usually requires several years of study and practice. Although a lot of basic principles in art are of course transferable between different techniques. Color theory, the 12 basic principles of animation, human proportions and body language or perspective are universally applicable. So if you already studied those subjects in the context of other visual mediums, then your journey to becoming a decent pixel artist can be a lot shorter.

Why is dithering used in pixel art?

One reason is nostalgia. Old gaming systems only had a very limited color palette available. But dithering allowed them to create blends between two colors, artificially expanding the available color palette. This actually worked a bit better than today because the carthode-ray tube monitors and TVs of that time produced less sharp pixels than today's LCD displays. Today this would be unnecessary, because pretty much any gaming device supports 32bit colors. But nevertheless dithering is still used as an aesthetic choice to emulate the classic look of 90s video games.

Another reason is that dithering is a good way to simulate texture. Here is an example from a well-known pixel art tutorial which compares cell shading to dithering:

Note how random dithered shading makes the objects appear a lot more rough and interesting.

The examples in the question actually show a more regular, checkboard-style dithering (very visible on the skirt of the character in the first animation). I personally don't like that style very much, because it looks artificial and unnatural to me. I much more prefer placing pixels more randomly (like in the harpy on the 3rd image) or if I want the material to look smooth, use bands of color like on the skirt in the 2nd image. But that might just be a personal preference.
> 1 votes

# Answer
It seems like game is using mix of 3D environment and 2D character sheets. For me it looks like sprites are being drawn manually (animations weren't prerendered/animated using limbs in 3D editor). Portraits could be drawn digitally though, it's hard to see pixel art there.

@edit

Dithering is a commonly used technique in pixel art to avoid banding (creating fake contours). A lot of graphics software is supporting dithering. I use Aseprite which for example has built in dithering settable brush.
> 1 votes

---
Tags: rendering, art, pixel-art
---


# Question
Title: How to use WorldToScreenPoint function in a texture context?
I am rendering a scene into a RenderTexture and I have a set of 3D points. I want to convert these points from 3D to texture coordinate frame. It worked, when I rendered into screen and used `camera.WorldToScreen()` function. Now I have to render into texture. Is there any way to do the same as `WorldToScreen()` function does for the render/2D texture?

# Answer
> 0 votes
Now I found that this function WorldToScreenPoint works good as well for RenderTexture. The question was asked because didn't found answer by googling and saw always the same problem while getting screenshots

---
Tags: rendering, coordinates, screen, rendertexture
---


# Question
Title: Why is my OpenGL triangle not drawing on the screen?
I am currently following this tutorial to create a simple game engine, but I am doing it using SDL and C++. I am stumped, however, because I can't get a triangle to draw on the screen, and I'm getting no errors from OpenGL. I have read tens of questions regarding the same problem, but I have already implemented the solutions to those problems (missing `VAO`, missing shaders, wrong size given to `glBufferData`). I'm only seeing a one-coloured window.

My shaders are defined like this:

```
#version 330 core

layout(location = 0) in vec3 position;

void main()
{
    gl_Position = vec4(position, 1.0);
}

```

and

```
#version 330 core

precision highp float;

out vec4 frag_color;

void main()
{
    frag_color = vec4(0.0, 1.0, 1.0, 1.0);
}

```

and I load/use them like this:

```
void Shader::add_program(const std::string& shader_code, GLenum shader_type)
{
    const GLuint shader = glCreateShader(shader_type);
    if (shader == 0) {
        throw std::runtime_error{"Could not create shader"};
    }

    if (shader == GL_INVALID_ENUM) {
        throw std::runtime_error{"Invalid shader type: " + std::to_string(shader_type)};
    }

    const GLchar* programs[1]{shader_code.c_str()};
    const GLint lengths[1]{static_cast<GLint>(shader_code.length())};

    glShaderSource(shader, 1, programs, lengths);
    glCompileShader(shader);

    // Error check using glGetShaderiv

    glAttachShader(shader_program, shader);
}

void Shader::compile_shader()
{
    glLinkProgram(shader_program);
    // Error checks using glGetProgramiv
}

void Shader::bind()
{
    glUseProgram(shader_program);
}

```

Finally, I have the vertices of the triangle stored like this (`Math::Vector3` is just a POD struct with three floats):

```
std::vector<Math::Vector3> vertices{
    {-1.0, -1.0, 0.0},
        {0.0, 1.0, 0.0},
        {1.0, -1.0, 0.0}
};

```

and the init/draw code is:

```
Mesh::Mesh(const std::vector<Math::Vector3>& vertices)
{
    size = vertices.size();

    glGenVertexArrays(1, &vao_id);
    glBindVertexArray(vao_id);

    glGenBuffers(1, &vbo_id);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id);

    glBufferData(
            GL_ARRAY_BUFFER,
            size * sizeof(Math::Vector3),
            vertices.data(),
            GL_STATIC_DRAW
            );
}

void Mesh::draw() const
{
    glBindVertexArray(vao_id);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);
}

```

On every frame I first clear the window, then call the shader's `bind` method and then the `draw` method of the mesh.

Any help is highly appreciated, as I have been trying to tackle this for a long time now!

# Answer
> 2 votes
I was able to debug this using RenderDoc (Thanks Tyyppi\_77 for the suggestion). I was calling `SDL_GL_SwapWindow` every time I cleared the screen, but did not do so after drawing the triangle to the screen. This caused only the background clear to be shown.

The proper fix was to remove the `SDL_GL_SwapWindow` call from the screen clearing method and only call it once after all the drawing.

---
Tags: opengl, c++, glew
---


# Question
Title: Using server timestamp to synchronize actions across clients
# tl;dr

The question is rather simple: **how unsynchronized can internal clocks be between different machines**?

---

# Context

We have a "hybrid" approach where the Clients are authoritative on certain things, and the Server on some others. That is to make our life easier because the gameplay doesn't need to be too tight about certain things.

In this case, the Server will pre-determine a sequence of Enemy Types to be spawned at different locations with pre-determined delay between the spawns. We would then let the Clients handle the rest during the gameplay.

However, if we want the Clients to be mostly synched on the display of the enemies, they would need to initiate this sequence at the very same time, and thus we cannot rely on the network to have transmitted the data at the very same time for all Clients.

The idea we had was to send a timestamp of the format returned by `System.currentTimeMillis()` which would indicate when to begin the sequence.

But then one question remains in the way: how unsynchronized can internal clocks be between different machines?

# Answer
> 2 votes
Checking the Wikipedia article on Network Time Protocol, we find this Windows documentation as one example:

> Under the right operating conditions, systems running Windows 10 or Windows Server 2016 and newer releases can deliver 1 second, 50ms (milliseconds), or 1ms accuracy.

To achieve the tighter 50 ms bound, the documentation says:

> The target computer must have better than 5ms of network latency between its time source.

I'd say its fair to assume this condition will *not* be met for many consumer devices that have not been specifically configured for time accuracy. For most consumer uses, having their system clock accurate within 1 second is sufficient, so I'd expect other consumer operating systems are not dramatically more accurate than this by default.

Software that requires tighter synchronization often implements its own clock adjustment.

So, you should expect that system times will vary between players by multiple frames' worth, and not count on millisecond timestamps to give you accurate synchronization between machines.

Instead of trying to synchronize to a specific moment in wall clock time, you may find it beneficial to try to synchronize to a specific update tick. You can think of your game as though it were turn-based, one turn per server update - it's just the turns auto-advance on their own very very quickly.

This coarser measure of time is more robust against machine variation and network latency. Every client can count up monotonically from their first update tick at game start (or game join, if they joined in-progress, in which case the server needs to stamp the initial game state info-dump with the turn number it represents). Now all clients can agree to spawn the enemy on "turn 153", using the regular rhythm of update messages / fixed timestep beats to ensure they don't get a turn ahead or behind.

---
Tags: java
---


# Question
Title: How to declare per-instance properties for instances rendering on a shader graph?
Unity Version: 2019.4.1f1

Render Pipeline: URP

I created a shader using Unity's Shader Graph, and I want to apply GPU Instancing on this shader, but there is no way to declare per-instance properties inside the shader graph.

Is there a way to make GPU Instancing work on shader graphs' materials?

# Answer
You can set the GPU Instancing in the inspector directly on the material you created:
> 1 votes

---
Tags: unity, instancing, unity-shader-graph
---


# Question
Title: How to make a cell shader like BOTW in Unity?
It seems most cell shader tutorials focus on individual shaders for materials, but the effect used in BOTW seems to be more like a filter, that is applied to everything.

I've researched multiple examples that have been done in UE4 like here and here but nothing in Unity.

How would I apply something like this in Unity?

# Answer
> -1 votes
You can write your own screen-space post-processing effects. One solution for doing this would be to create a custom effect for the official Post-Processing Stack v2 from the Unity Package Manager. See this page for information on getting started.

---
Tags: unity, shaders, cel-shading
---


# Question
Title: How can I get the basic Unity player controller to move based on a gameobjects rotation?
I am making a basic movement script based off of the built in playercontroller in Unity. I am trying to get the Player gameobject to move forward based on its own rotation (i.e. if it is rotated to 90 degrees, it will go forward in the direction it is facing and not based off of its position values), but I can't figure out how to change it.

How can I do this?

EDIT: I figured it out. I just had to multiply the playercontroller's movement by player rotation.

# Answer
I think what you need is the value transform.forward This is a normalized vector that will always point in the same direction as the object's blue arrow in the scene view. Feeding this into the character controller's Move method will move the object forward, regardless of rotation.

Do note that the character controller is only designed to function with an objective 'down' aligned to the y-axis. This means that if you rotate on any axis but the y-axis, it can lead to some strange results.
> 1 votes

---
Tags: unity, rotation, movement, control
---


# Question
Title: Having multiple different friction values on a single piece of track?
I am trying to figure out a good/performant way to give a piece of track multiple values of dynamic friction. A track piece is 10x10 units in Unity and the idea is to puzzle them together to a big track like the tracks in Trackmania. The game itself features no acceleration, except from gravity. To make things more interesting I want to give each track piece at the start of the scene multiple random friction values within a given range.

Currently I achieve this by making each piece of track consisting of 100 little tiles which are 1x1 units and they get a random friction values assigned. This approach works somewhat fine as long as there are less than 30 to 40 track pieces(3000-4000 tiles) but with more than that the fps are dropping really low. As it is a racing type of game I had to set the "Fixed Timestep" in the project settings to 0.001 to get accurate time measurments and this is hurting the performance as well. With a lower timestep the collision detection with all the little tiles is really bad too.

Is there a more elegant and/or performant way to achieve this in within the unity physics system?

# Answer
> 1 votes
It sounds like you should use trigger colliders and a little bit of manual physics to achieve what you want. With this approach, you can place trigger volumes over portions of the track rather than having to break the track into tiny pieces.

For example, add a new GameObject with a box collider to the scene. In the box collider's Inspector, check the "Is Trigger" box. Align the box collider with a portion of the track. Create a new script and assign it to the box collider:

```
[RequireComponent(typeof(Collider))]
public class FrictionArea : MonoBehaviour {
    [SerializeField] private float friction = .02f;

    public float Friction => friction;
}

```

Then create a new component and assign it to your vehicles:

```
[RequireComponent(typeof(Rigidbody))]
public class FrictionApplier : MonoBehaviour {
    private Rigidbody body;
    private float friction = 0;

    void Awake() {
        body = GetComponent<Rigidbody>();
    }

    void OnTriggerEnter(Collider trigger) {
        FrictionArea fa = trigger.GetComponent<FrictionArea>();
        if (fa != null) this.friction = fa.Friction;
    }

    void FixedUpdate() {
        //you might want something more sophisticated than this
        body.velocity *= (1 - friction);
    }
}

```

You can put as many FrictionAreas as you want in the scene and align them with different portions of the track.

---
Tags: unity, physics
---


# Question
Title: UE4 - custom template can only start with blueprints
I tried making a custom template for UE4 to help save some time during gamejams.

I follow this tutorial:

https://docs.unrealengine.com/en-US/Engine/Basics/Projects/CreatingTemplates/index.html

It works alright, even though some minor things don't work, like saving custom folder colors. But what really bothers me is this:

Normally, the options are Blueprint and CPP. I tried making a new template with a different config file, but nothing changes. Is there a way to fix it?

# Answer
If you create a template that's BP only, it will only be available for BP. To create a C++ template, you need to start with a BP/C++ starter set.
> 1 votes

---
Tags: unreal-4
---


# Question
Title: I need to improve my ring shop. help with array, loop & query PHP
I have an array setup which consists of 25 rings, names, stats, prices. Right now in its current form, I have a form setup with 25 radio buttons with a value of 1-25 on them, and I'm using If statements in my function to buy a ring. It works but I feel it's very inefficient because I have this code running 25 times based on $\_POST\['ring'\] which sends the value 1-25.

```
    if ($rings[1][7] > $_SESSION['cash']) {
        echo "You do not have enough cash for this ring!<BR><tr>
        <td class=\"fa-border\" align=\"center\"><a href=\"ringshop.php\">GO Back!</td>
    </tr>";
        return;
    }
    if ($_POST['ring'] == 1) {
        $ringcost = $_SESSION['cash'] - $rings[1][7];
        $stmt = $pdo->prepare('UPDATE cu_cash SET cash=:cash WHERE id=:id');
        $stmt->bindParam(":cash", $ringcost);
        $stmt->bindParam(":id", $_SESSION['id']);
        $stmt->execute();

        $stmt = $pdo->prepare('UPDATE cu_users SET ring_id=:ring_id WHERE id=:id');
        $stmt->bindParam(":ring_id", $_POST['ring']);
        $stmt->bindParam(":id", $_SESSION['id']);
        $stmt->execute();
        echo "You have Successfully Purchased " . $rings[1][0] . "<BR><tr>
        <td class=\"fa-border\" align=\"center\"><a href=\"ringshop.php\">GO Back!</td>
    </tr>";
    }

```

Now I am wondering if there's a loop I could use to take the value from $\_POST\['ring'\] and pull the price assign it to a variable so I can do my cash - price then update the DB with ring id & update my cash? been thinking about this for a while & I am having a hard time wrapping my head around it. Loops have always confused me, but I know they are useful!

# Answer
Well turns out I did not need a loop, I modified my code as follows and it does exactly as I intended.

```
if ($rings[$_POST['ring']][7] > $_SESSION['cash']) {
        echo "You do not have enough cash for this ring!<BR><tr>
        <td class=\"fa-border\" align=\"center\"><a href=\"ringshop.php\">GO Back!</td>
    </tr>";
        return;
    } else {
        $ringcost = $_SESSION['cash'] - $rings[$_POST['ring']][7];
        $stmt = $pdo->prepare('UPDATE cu_cash SET cash=:cash WHERE id=:id');
        $stmt->bindParam(":cash", $ringcost);
        $stmt->bindParam(":id", $_SESSION['id']);
        $stmt->execute();

        $stmt = $pdo->prepare('UPDATE cu_users SET ring_id=:ring_id WHERE id=:id');
        $stmt->bindParam(":ring_id", $_POST['ring']);
        $stmt->bindParam(":id", $_SESSION['id']);
        $stmt->execute();
        echo "You have Successfully Purchased " . $rings[$_POST['ring']][0] . "<BR><tr>
        <td class=\"fa-border\" align=\"center\"><a href=\"ringshop.php\">GO Back!</td>
    </tr>";
    }
    $_SESSION['ring_id'] = $_POST['ring'];
    $_SESSION['cash'] = $ringcost;
}

```

I also do not need 25 of these as I did before.
> 0 votes

---
Tags: php, mysql
---


# Question
Title: How can I access the normal map value in Unity?
I'm simulating laser scanners in Unity with Raycasts, and I've got some "bumpy" items I'd like to scan.

I had tried generating the actual geometry for these objects, but there are tons of these objects and the polygon count exploded.

What I would like to do is something like described here to get the color from a raycast intersection:

```
Renderer renderer = raycastHit.collider.GetComponent<MeshRenderer>();
Texture2D texture2D = renderer.material.mainTexture as Texture2D;
Vector2 pCoord = raycastHit.textureCoord;
pCoord.x *= texture2D.width;
pCoord.y *= texture2D.height;

Vector2 tiling = renderer.material.mainTextureScale;
Color color = texture2D.GetPixel(Mathf.FloorToInt(pCoord.x * tiling.x) , Mathf.FloorToInt(pCoord.y * tiling.y));

```

But, instead of getting the **color**, I'd like to access the **normal**. I used grayscale bump maps to simulate height differences, but the raycasting doesn't take the normal map into account and I can't figure out how to access normal map values. Ideally there'd be some `texture2D.GetNormal()` I could use in place of the `texture2D.GetPixel()` given in the snippet above, but I can't seem to find anything anywhere on getting at the material normals.

I'm using Unity 2019.4, with the Universal Render Pipeline at the moment.

# Answer
Following @DMGregory's excellent feedback, I wrote the following class to test:

```
public class MaterialTextureTest : MonoBehaviour
{
    public Material material = null;
    public List<string> textureNames = new List<string>();
    public List<Texture2D> textures = new List<Texture2D>();
    // Start is called before the first frame update
    void Start()
    {
        if(material!=null)
        {
            string[] names = material.GetTexturePropertyNames();
            foreach(string name in names)
            {
                textureNames.Add(name);
                textures.Add((Texture2D)material.GetTexture(name));
            }
        }
    }
}

```

This showed the material has the following texture property names:

```
_MainTex
_AlphaTex
_BumpMap
_NormalMap
_DetailNormalMap
_BaseMap
_MetallicGlossMap
_ParallaxMap
_OcclusionMap
_EmissionMap
_DetailMask
_DetailAlbedoMap
_SpecGlossMap
_MaskTex

```

I'm using the Universal Render Pipeline and my test material is using the "Simple Lit" shader. I've got a texture put into the "Normal Map" section of the "Surface Inputs" portion of the material, but I actually drew a grayscale image to use for the normal map, with the intention of using it as a true bump map.

I believe this is handled on the texture, because there's a checkbox on the **texture** properties that says "Create from Grayscale" that I ticked.

I used the grayscale/bump map texture as the input to the "Normal Map" setting for my material, so the elements in my `textures` List from the test class above are:

```
Element 0    <My image texture>
Element 1    None (Texture 2D)
Element 2    <My bump map texture!>
Element 3    None (Texture 2D)
Element 4    None (Texture 2D)
Element 5    <My image texture>
Element 6    None (Texture 2D)
Element 7    None (Texture 2D)
Element 8    None (Texture 2D)
Element 9    None (Texture 2D)
Element 10   None (Texture 2D)
Element 11   None (Texture 2D)
Element 12   None (Texture 2D)
Element 13   None (Texture 2D)

```

So now I can see that I can access my bump map by calling:

```
Texture2D bumpMap = (Texture2D)material.GetTexture("_BumpMap");

```

Then finally I just use this line instead of the:

```
Texture2D texture2D = renderer.material.mainTexture as Texture2D;

```

line in the snippet from my question to access the bump map, just like DMGregory said. Now the "color" (grayscale) I get back from the `.GetPixel()` line returns the grayscale value I wrote.

I think a super noteworthy point here is that most "bump" maps are actually *normal* maps, which are the blue/purple looking maps like CrazyBump or similar would generate. I'm trying to encode a height offset on the objects to use for modifying the Raycast results, so there's this double benefit for me in that the grayscale bump maps seem to actually correlate better to a *height* than the surface normals, but also that the actual grayscale bump maps are rarely used, so it's like this hidden channel included in all materials.

For my test material, with a grayscale bump map, the `_NormalMap` entry in the material is null! I am expecting the opposite to be true for most standard materials - the `_BumpMap` entry will probably be null because most modern materials will be using an actual normal map.

All that is to say I can try to get the `_BumpMap` texture and check if it's null. If it's null it's probably not a material I've made, which means I skip the raycast modification and use the actual results. If it's not null, then I can get the color as described above and use that to modify the results.

:EDIT:

I had tried this implementation and found it was still too slow for what I need, so I used a dictionary! This is my first time really needing one, but I found that the `.GetComponent<Renderer>()` was the bottleneck in the snippet from my question.

This part isn't really related to the question per se, but it's related to what I'm *doing*, so I figured I'd post my solution here for all the future visitors. I can skip finding the renderer, then finding the material, then finding the texture every time and just associate a texture directly with the gameObject by caching them in a Dictionary. Dictionaries are built for quick lookups and I found the following to be very, very fast (virtually no change in framerate versus without any of the texture lookup code now):

```
// In the class definition:
private Dictionary<GameObject, Texture2D> textureDictionary = new Dictionary<GameObject, Texture2D>();
Renderer renderer;
Material material;
Texture2D texture;
Vector2 textureCoord;
Color color;
int textureId = Shader.PropertyToID("_BumpMap");

// After running the raycasts:
// If the texture isn't in the dictionary, add it!
if (textureDictionary.TryGetValue(results[i].collider.gameObject, out texture) == false)
{
    bool textureFound = false;
    renderer = results[i].collider.gameObject.GetComponent<Renderer>();
    if (renderer != null) // Terrain has no renderer, so need to check
    {
        material = renderer.sharedMaterial;
        texture = (Texture2D)material.GetTexture(textureId);
        if (texture != null) // We're looking for the bump map texture here, which could be null
        {
            textureDictionary.Add(results[i].collider.gameObject, texture);
            textureFound = true;
        }
    }
    if(textureFound == false) // If the texture doesn't exist that's fine, but put a null entry in the dictionary so you don't continue to look for it every iteration
    {
        texture = null;
        textureDictionary.Add(results[i].collider.gameObject, texture);
    }
}
if(texture!=null)
{
    textureCoord = results[i].textureCoord;
    color = texture.GetPixelBilinear(textureCoord.x, textureCoord.y);
    // Do your stuff with the bump map color now
}

```

}
> 1 votes

---
Tags: unity, raycasting, normal-mapping, bump-map
---


# Question
Title: Copy component features to Instantiate object?
I'm trying to add component to Instantiate object. This new component is audioSource. Now I added the audio to the Instantiate but I want to copy all features from "\_sound" to the new component.

```
 public AudioSource _sound;
 public float targetCompass;
 public GameObject ebullet;

  Void Start() {
      _sound = GetComponent<AudioSource>();

   }

 Void Update() {
 if (targetCompass <= 5 )
     {
      GameObject bullets = Instantiate(ebullet) as GameObject;
      bullets.AddComponent<AudioSource>();
      bullets.GetComponent<AudioSource>() = _sound;
     }

```

}

# Answer
> 2 votes
Run this from an Editor script to copy your AudioSource to the prefab:

```
 UnityEditorInternal.ComponentUtility.CopyComponent(source.GetComponent<AudioSource>());
 UnityEditorInternal.ComponentUtility.PasteComponentAsNew(source.ebullet);

```

This does not work at runtime, but you can update your prefabs in the Editor and then they'll be good to go at runtime. If you need to do this for many objects, use a loop.

---
Tags: unity
---


# Question
Title: How can I reset the mouse axes when respawning a player?
I am making a simple parkour game in which the camera will follow the mouse based on the mouse input axis * the sensitivity. This works great, but when I want to reset my character to the start I cant figure out how to reset the mouse axis to zero, thus preventing me from resetting the camera rotation. I have tried `Input.ResetInputAxes();`, but that seems to only reset the buttons.

```
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{

    public CharacterController characterController;
    public Transform Player, camera;
    public Camera cam;
    public float XSensitivity, YSensitivity;
    public bool grounded, jumping;
    public float forwardSpeed, horizontalSpeed, jumpPower, gravity, sprintModifier;

    [HideInInspector] public float sideSpeed, lastPlayerPosX, lastPlayerPosZ, jumpSpeed, verticalRotation, horizontalRotation;

    private float isSprinting = 1;

    void Update()
    {
        //This is where I get the axes
        float mouseX = Input.GetAxis("Mouse X"), mouseY = Input.GetAxis("Mouse Y");

        //This is how I rotate the player and camera
        verticalRotation += -mouseY * YSensitivity;
        Player.transform.localRotation = Quaternion.Euler(0, horizontalRotation, 0);
        horizontalRotation += mouseX * XSensitivity;
        cam.transform.localRotation = Quaternion.Euler(verticalRotation, horizontalRotation, 0);

        if (Input.GetMouseButtonDown(0))
        {
            Cursor.lockState = CursorLockMode.Locked;
        }

        float horizontal = Input.GetAxis("Horizontal"), forward = Input.GetAxis("Vertical");

        grounded = characterController.isGrounded;

        if (grounded)
        {
            if (Input.GetKey("left shift"))
            {
                isSprinting = sprintModifier;
            }
            if (Input.GetKey("left shift") == false)
            {
                isSprinting = 1f;
            }
            jumping = false;
            jumpSpeed = 0;
            sideSpeed = .75f;
        }
        else
            jumpSpeed -= (gravity * 25) * Time.deltaTime;

        if (Input.GetKey("space"))
        {
            sideSpeed = .25f;
        }
        if (Input.GetAxisRaw("Jump") != 0 && !jumping)
        {
            jumping = true;
            jumpSpeed = jumpPower;
        }

        lastPlayerPosX = Player.transform.position.x;

        lastPlayerPosZ = Player.transform.position.z;

        Vector3 motion = new Vector3(horizontal * horizontalSpeed * sideSpeed, jumpSpeed, forward * forwardSpeed * isSprinting);
        characterController.Move((Player.transform.rotation * motion) * Time.deltaTime);
    }

    void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.name == "deathbarrier")
        {
            //Resets player to starting position
            Player.transform.position = new Vector3(20.5f, -2, -22.5f);
            //Is supposed to reset all inputs (including mouse)
            Input.ResetInputAxes();
            //Sets camera rotation to 0, but only for one frame before the stored mouse axes change it
            camera.transform.rotation = Quaternion.Euler(0, 0, 0);
        }
    }
}

```

Thanks for any tips!

# Answer
> 1 votes
You don't need to reset the mouse axes.

The mouse axes (e.g. `Input.GetAxis("Mouse X")`) reflect mouse movement over the last frame. If you do not move the mouse, the value returned from this axis will be 0.

You need to reset your fields `horizontalRotation` and `verticalRotation` in your `OnTriggerEnter()`.

---
Tags: unity, c#, camera, input, character-controller
---


title: I want my shapes to stay at screen

text:
# Question
Title: I want my shapes to stay at screen
I am working on a paint project and it's almost complete but I want it to behave like the ms paint , in which whenever we draw an object (rectangle ,line) it shows it on the screen while we are moving our mouse . I implemented it for only one object i.e the window shows which object I am drawing but when I start drawing another object it wipes the previously drawn one

```
import pygame
pygame.init()
run = True
screen =   pygame.display.set_mode((400,400))
clock = pygame.time.Clock()
screen.fill((255,255,255))
down = None
while run == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           run = False

        elif event.type == pygame.MOUSEMOTION:
            motion = event.pos
            screen.fill((255,255,255))
            if down:
                pygame.draw.line(screen,(0,0,0),(down[0],down[1]),\
                    (motion[0],motion[1]))

        elif event.type == pygame.MOUSEBUTTONDOWN:
            down = event.pos

        elif event.type == pygame.MOUSEBUTTONUP:
            up = event.pos
            pygame.draw.line(screen,(0,0,0),(down[0],down[1]),(up[0],up[1]))
            down = None

    pygame.display.update()
    clock.tick(60)

```

I tried saving the data of the all previously draw objects in an array and then calling a function make(self,arr) to draw it again on the screen but it's very slow. How can I draw the objects like i showed in my program and still have other objects stay on the screen ?

# Answer
```
import pygame
pygame.init()
screen = pygame.display.set_mode((400,400))
run = True
white = (255,255,255)
black = (0,0,0)
screen.fill(white)
down = None
cpy = None
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.MOUSEMOTION:
            motion = event.pos
            screen.fill(white)
            if cpy:
                screen.blit(cpy,(0,0))
            if down:
                pygame.draw.line(screen,black,(down[0],down[1]),\
                    (motion[0],motion[1]))

        elif event.type == pygame.MOUSEBUTTONDOWN:
            down = event.pos
        elif event.type == pygame.MOUSEBUTTONUP:
            up = event.pos
            down = None
            cpy = screen.copy()
    pygame.display.update()

```
> 0 votes

---
Tags: pygame
---


# Question
Title: Serializing nested ScriptableObjects with runtime changes
I'm making an effort to use ScriptableObjects more in my game architecture, after watching a fantastic Unity Unite talk on the subject. The central idea is to use ScriptableObjects, during runtime, as a kind of pluggable, mutable global data container. It's intended to replace things like the singleton pattern in a more testable, less tightly-coupled way.

I'm not going to go into detail on the arguments in favor of this, but I do definitely recommend watching the talk.

When using this pattern, you'll probably run into data-container-style ScriptableObjects that you want to persist between play sessions. The problem I'm running into is that, when Unity's serializer is run on a ScriptableObject that references other ScriptableObjects, and those referenced ScriptableObjects have changed during runtime, the serializer ignores the changes on those sub-SOs.

Is there a good way to serialize nested SOs containing data that changes during runtime?

---

For some examples/more in-depth background:

In the game I'm working on, I'm emulating a file system that multiple otherwise-independent game objects are interested in. It looks somewhat like this:

```
public abstract class FilesystemObject : ScriptableObject
{
    public string FileName;
}

[CreateAssetMenu(fileName = "NewDirectory.asset", menuName = "Directory")]
public class FilesystemDirectory : FilesystemObject
{
    public List<FilesystemObject> Contents;
}

[CreateAssetMenu(fileName = "NewTextFile.asset", menuName = "Directory")]
public class FilesystemTextFile : FilesystemObject
{
    public string Contents;
}

```

In my project directory, I have a `FilesystemDirectory` asset file named `FSRoot.asset` that represents the root directory of the filesystem. It's populated with all the files that need to exist when the player first launches the game.

If a MonoBehaviour wants to read or write to this filesystem (say, an in-game text editor), all I have to do is expose a `FilesystemDirectory` field to Unity's serializer, and then hook `FSRoot` up to that field using the inspector. Then, during runtime, if the player creates, edits, or deletes any filesystem data, those manipulations are done directly on the `FSRoot` object. Any other MonoBehaviour with the same reference to `FSRoot` sees the same mutated data, since those changes persist in memory.

However, unless you're in the editor, those changes do *not* persist between sessions. You have to serialize and deserialize the data manually for that. However, when I serialize `FSRoot` using Unity's JsonUtility, it only captures changes that have happened to `FSRoot` directly, and not any changes in subdirectories/files inside `FSRoot`. Any files that were authored in edit time are completely unchanged.

# Answer
> 2 votes
IIRC Unity won't serialize a List where the data type is abstract.

Your `FilesystemDirectory` class has one field:

```
public List<FilesystemObject> Contents;

```

`FilesystemObject` is an abstract class, which Unity can't serialize as-is. Unfortunately Unity's built-in serialization does not work well with abstraction.

You could try adding the `[SerializeReference]` attribute in front of the field:

```
[SerializeReference] public List<FilesystemObject> Contents;

```

That can get Unity to serialize interfaces, but I'm not sure if it supports abstract base classes. If it doesn't work, you may have to either stop using an abstract base, or write a little custom code to copy the data into a structure that can be serialized. Or I believe you can serialize and deserialize using .NET instead of Unity, e.g.

```
public bool SaveFile(object obj, string path) {
    FileStream stream = null;
    try {
        stream = new FileStream(path, FileMode.Create);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, obj);
    } catch (Exception ex) {
        Debug.LogException(ex);
    } finally {
        if (stream != null) stream .Close();
    }
}

```

---
Tags: unity, savegame, serialization, scriptable-object
---


title: DirectX 11, support for Font drawing

text:
# Question
Title: DirectX 11, support for Font drawing
I have recently started to work with DirectX 11 and 12, I am using Microsoft Visual Studio Community Edition. I am under a 64-bit machine. I am currently rendering a frame with background and a window using Windows C++ API and DirectX 11.1.

I was thinking about drawing text, but I thought about using custom Fonts, so I will have original Font file, not some graphic file e.g. ***bmp** or some other format. I have read about: `SpriteBatch`\[1\] and `SpriteFont`\[2\], which can be used via **DirectX Tool Kit** (https://github.com/microsoft/DirectXTK).

I tried:

```
std::unique_ptr< SpriteFont> font(new SpriteFont(device, L"text.spritefont"));
std::unique_ptr<SpriteBatch> spriteBatch(new SpriteBatch(context));
spriteBatch->Begin();
font->DrawString(spriteBatch.get(), L"Hello, ", XMFLOAT2(200,200));
spriteBatch->End();

```

But, I am running into some issues with the `Begin()` function, that seems to have mandatory parameters. I did try: `Begin(SpriteSortMode:: SpriteSortMode_Deferred, nullptr, nullptr, nullptr);` But, I keep experiencing the same errors in Visual Studio regarding overloading and params.

I know that **DirectX 9** had `D3DXFont`, https://drunkenhyena.com/cgi-bin/view\_cpp\_article.pl?chapter=3;article=17 , I also found this: http://download.nvidia.com/developer/GPU\_Gems/CD\_Image/Natural\_Effects/Water\_Simulation/d3dfont.cpp

I also found the **DXUT for Direct3D 11**, https://github.com/walbourn/directx-sdk-samples/tree/master/DXUT -- but seems this is no longer active.

**\[1\]** https://github.com/microsoft/DirectXTK/wiki/SpriteBatch

**\[2\]** https://github.com/microsoft/DirectXTK/wiki/SpriteFont

**EDIT #1:** With DirectX 9, I can do the following:

```
 HRESULT hr=D3DXCreateFont(
                     device,           //D3D Device
                     22,               //Font height
                     0,                //Font width
                     FW_NORMAL,        //Font Weight
                     1,                //MipLevels
                     false,            //Italic
                     DEFAULT_CHARSET,  //CharSet
                     OUT_DEFAULT_PRECIS, //OutputPrecision
                     ANTIALIASED_QUALITY, //Quality
                     DEFAULT_PITCH|FF_DONTCARE,//PitchAndFamily
                     "Arial",          //pFacename,
                     &font);           //ppFont

```

**But, unfortunately this does not exist in DirectX 10, 11, or 12.**

---

**Questions:**

1. Is using these new recommendations (SpriteBatch, SpriteFont & DirectXDTK) by Microsoft, in any way, linking the stuff I build with XNA?
2. Is it possible to use Font file, custom one? Or, do I have to create graphic font? (What is more recommended generally speaking)?

A book recommended writing your own Font drawer class, it uses:

* ID3D11VertexShader
* ID3D11PixelShader
* ID3D11InputLayout
* ID3D11Buffer
* ID3D11ShaderResourceView
* ID3DX11CreateShaderResourceViewFromFile
* ID3D11SamplerState
* D311\_MAPPED\_SUBRESOURCE
* D311\_MAP\_WRITE\_DISCARD

EDIT #2: WHY DO I HAVE TO CAST, Microsoft::WRL::ComPtr

# Answer
For *DirectX Tool Kit*, you should walk through the first few lessons of the tutorials which covers the basic of `SpriteBatch` and `SpriteFont`.

*DirectX Tool Kit* is a C++ language library. The class designs are *inspired* by the XNA Game Studio class design, but they are very different things. The intent is if you are familiar with `SpriteBatch` from XNA Game Studio in C#, it should be easier to get started with the C++ `SpriteBatch` in *DirectX Tool Kit*.

`D3DXCreateFont` was a D3DX utility library function. While there was in fact a Direct3D 10 version of in D3DX10, the D3DX11 library was very much trimmed down to just the texture loading. In any case, D3DX9, D3DX10, and D3DX11 are deprecated and only available in the end-of-life legacy DirectX SDK. See Microsoft Docs

> The DXUT for Direct3D 11 framework includes a very basic sprite-based bitmap font system because D3DX11 didn't have one, but it's not a great implementation. It was done in a rush to fill a need for samples, but `SpriteBatch` / `SpriteFont` is a better choice.

You can also make use of Direct2D/DirectWrite through device interop with Direct3D 11, and this is the recommended solution if you need support for large fonts or complex font layouts. For basic "Hello, World" use you should start with `SpriteFont`.
> 1 votes

---
Tags: c++, directx, directx11, directx9, fonts
---


# Question
Title: New Input System Differs Between Editor and Runtime?
I'm sure the problem is me.

Here is a simple look script (from a tutorial, actually).

I'm getting inconsistent results between editor and runtime. I'm guessing its a framerate thing.

Code:

```
using UnityEngine;
using Mirror;
using Cinemachine;

public class PlayerCameraController : NetworkBehaviour
{
    [Header("Camera")]
    [SerializeField] private Vector2 maxFollowOffset = new Vector2(-1f, 6f);
    [SerializeField] private Vector2 cameraVelocity = new Vector2(4f, 0.25f);

    [SerializeField] private Transform playerTransform = null;
    [SerializeField] private CinemachineVirtualCamera virtualCamera = null;

    private Controls controls;
    private Controls Controls {
        get {
            if (controls != null) { return controls; }
            return controls = new Controls();
        }
    }
    private CinemachineTransposer transposer;

    public override void OnStartAuthority()
    {
        transposer = virtualCamera.GetCinemachineComponent<CinemachineTransposer>();
        virtualCamera.gameObject.SetActive(true);

        Controls.Player.Look.performed += ctx => Look(ctx.ReadValue<Vector2>());

        enabled = true;
    }

    [ClientCallback]
    private void OnEnable() => Controls.Enable();

    [ClientCallback]
    private void OnDisable() => Controls.Disable();

    private void Look(Vector2 lookAxis) {
        float deltaTime = Time.deltaTime;

        float followOffset = Mathf.Clamp(
            transposer.m_FollowOffset.y - (lookAxis.y * cameraVelocity.y * deltaTime),
            maxFollowOffset.x,
            maxFollowOffset.y);

        transposer.m_FollowOffset.y = followOffset;
        playerTransform.Rotate(0f, lookAxis.x * cameraVelocity.x * deltaTime, 0f);
    }
}

```

The code seems right. Watching the values of `Vector2 lookAxis` reveals that the numbers are slightly different coming into the function based on environment.

Is there something wrong with this code that would give different results between editor and runtime?

# Answer
> 1 votes
The problem was (in my case) that I didn't realize Time.deltaTime can get in the way in some cases. Explained by @DMGregory and @Kevin in the comments.

> Sounds like you're double-dipping by multiplying by Time.deltaTime then. A mouse delta will already be larger on a long frame or smaller on a short frame, given a constant speed of mouse movement, just given that there's more or less time to accumulate travel. By multiplying by deltaTime, you're effectively squaring your frame time adjustment, making it more sluggish at high framerates.

---
Tags: unity, input, editors
---


# Question
Title: How can I set up a 2D circular boundary in Unity?
I wanted to create a virtual analogue stick on Unity.

I figured a very simple, 2 part method setting up a tether to the middle of a doughnut-container and a boundary would work. While the tether was quickly solved just by using `Vector2.MoveTowards`, the boundaries would be much harder to solve.

I initially tried to create a 2D circle collider around the doughnut-container but I didn't know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut-container). Thus was done with multiple if statements:

```
 if (currentPoint.y >= 2.7f){currentPoint.y = 2.7f;}
 if (currentPoint.x >= 2.5f){currentPoint.x = 2.5f;}
 if (currentPoint.y <= -2.7f){currentPoint.y = -2.7f;}
 if (currentPoint.x <= -2.5f){currentPoint.x = -2.5f;}

```

However, when testing the code out, the cursor still exceeded the boundaries given:

Minimum reproducible code for the cursor:

```
public class menuScript : MonoBehaviour
{
    public float speed;
    public Vector2 originPoint;
    private Vector2 currentPoint;
    // Start is called before the first frame update
    void Start()
    {
        Vector2 originPoint = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        currentPoint = transform.position;
        float step = 50 * Time.deltaTime;
        float vertical = Input.GetAxis("Vertical") * Time.deltaTime * speed;
        float horizontal = Input.GetAxis("Horizontal") * Time.deltaTime * speed;

        if (horizontal != 0 || vertical != 0)
        {
            transform.Translate(horizontal, vertical, 0);
            if (currentPoint.y >= 2.7f){currentPoint.y = 2.7f;}
            if (currentPoint.x >= 2.5f){currentPoint.x = 2.5f;}
            if (currentPoint.y <= -2.7f){currentPoint.y = -2.7f;}
            if (currentPoint.x <= -2.5f){currentPoint.x = -2.5f;}
        }
        else
        {
            transform.position = Vector2.MoveTowards(transform.position, originPoint, step);
        }
    }
}

```

# Answer
Your if-else block for constraining the position of the stick looks like this:

```
if (currentPoint.y >= 2.7f){currentPoint.y = 2.7f;}
if (currentPoint.x >= 2.5f){currentPoint.x = 2.5f;}
if (currentPoint.y <= -2.7f){currentPoint.y = -2.7f;}
if (currentPoint.x <= -2.5f){currentPoint.x = -2.5f;}

```

This is going to lock the stick in a square region, not a circular region as you probably intend. There are several ways to enforce a region that is actually circular. Here's a simple one:

```
float radius = 2.5f;
float distance = Vector3.Distance(transform.position, originPoint);
float excess = distance - radius;
if (excess > 0) transform.position = Vector2.MoveTowards(transform.position, originPoint, excess);

```

This checks if the distance to the center is further than the maximum radius, and if so moves back towards the center the exact distance that is needed to put it on the edge of the circle. For example, if the radius is 2.5 but the measured distance is 3.7, it will move the stick 1.2 units back towards the center.

It's also worth noting there are numerous virtual joystick packages on the Unity Asset Store, and there is one included in Unity Standard Assets.

EDIT: As noted by DMGregory, you can also do this:

```
float radius = 2.5f;
Vector2 offset = transform.position - originPoint;
offset = Vector2.ClampMagnitude(offset, radius);
transform.position = originPoint + offset;

```

or, if stick is centered when its local position is (0, 0)

```
float radius = 2.5f;
transform.localPosition = Vector2.ClampMagnitude(transform.localPosition, radius);

```
> 1 votes

---
Tags: unity, 2d
---


# Question
Title: Godot: How to get mouse button input for a Tilemap for Cellular Automata
**Conway's Game of Life**

I have been working with a tilemap for the implementation of a cellular automata game. My current method for getting mouse button input is using an Area2D as a child of the Tilemap and detecting mouse button input like that.

I have done this and have since been wondering if there is something built in that I can use for this. I have looked into it and cannot find anything better.

Is there something built-in to Node2Ds or Canvas Items that I can use.

# Answer
The recommended way would be to override `Node._unhandled_input()` and use `TileMap.world_to_map()` and `TileMap.map_to_world()` methods.

Example:

```
# tile_map.gd
extends TileMap

func _unhandled_input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT and event.pressed:
            var clicked_cell = world_to_map(event.position)

```

Do note that `world_to_map()` takes a local position. Node2D supplies the `to_global()` and `to_local()` methods to ease the conversion.

I recommended using `_unhandled_input()` rather than `_input()` so gui input events are not passed through to the tile map. If the the tile map is undesirably receiving mouse events when you interact with a control, make sure that the control's `mouse_filter` property is not set to "Ignore".
> 2 votes

---
Tags: tilemap, input, mouse, godot
---


# Question
Title: Assigning values on multiple clients in UE4
I am currently working on a multiplayer game and I am having difficulties on assigning values on variables for each clients. Originally I looped through available clients character from HUD then assigned the calculated the value but I decided to do it inside character blueprint's instead.

I don't know why only first clients gets the calculated values but the other client still having the default value.

This is the initial value that I assigned from inside Character C++

```
MaxHealth = 500;
Health = MaxHealth;

```

This is how I assigned the value from the Blueprint.

Set Initial Attributes is where I calculated the Health value based on player's Strength value etc and the reason I'm doing this is because I am planning to retrieve the stats from the datatable in the future. But I don't know why it becomes like this instead.

This is the correct final value that supposedly assigned on both clients.

But only first client gets the correct value, not second client.

I don't want to use loop to search the player characters' inside player character's blueprint and assigned the value because I don't think it's a wise move so I am looking for a better alternative if any. Thanks!

# Answer
So I ended up calculate all the values inside the C++ instead and I'm not sure why I can't do it in the blueprints. From the log I gathered the values are updating correctly even when I'm still declaring it from blueprint. It's probably because Client 2 is basically not owned by ThirdPersonCharacter\_C\_0 but ThirdPersonCharacter\_C\_1 so that's probably why I can't see it from the dedicated server. I probably wrong though.
> 0 votes

---
Tags: c++, multiplayer, unreal-4, blueprints
---


title: Understanding Physics Materials

text:
# Question
Title: Understanding Physics Materials
I have been reading the documentation about Physics materials, and it really seems very incomplete to me. When I try to work with it, I get so many questions... Maybe can someone help me wrap my head around how it works?

* Why is there a `physics material` field for the `Rigidbody2D`, but also another in the `BoxCollider2D`?
* Do they work differently, depending on which you put it?
* What happens if you put different materials, one on the RB and one in the collider with different settings?
* If a player is standing in a platform, and you want it to *bounce*, or *slide*... do you set that on the player? Or in the platform?

**Update**

As suggested in the comments, I did some experimenting and this is what I saw:

* When I put contradicting materials in the `RigidBody2D` and the `Collider2D`, the one in the collider seems to take precedence. Not sure what is the purpose of the one in the Rigidbody.
* If both are the same, well, they just behave like one of them alone. The value isn't added

# Answer
> 1 votes
After following @DMGregory 's suggestions in the comments I have reached the following conclusions.

If you set a physics material to a Rigidbody2D, that material will apply. But if you also set another Physics Material to a collider in the same GameObject, this will override the Material in the Rigidbody2D.

Apparently this is meaningless when you only have 1 object with one collider, but if you were to have an GameObject with multiple colliders, and you wanted the GO to react differently, depending on which Collider2D it lands, you can apply a Physics Material to each collider, to achieve more complex behaviours.

**Summary**

Use the "Physics Material" slot in the collider only to override the one in the Rigidbody2D. If you only have one collider, it is pretty meaningless and you can ignore it.

---
Tags: unity, physics
---


title: Getting Rendered Sprite Size

text:
# Question
Title: Getting Rendered Sprite Size
I need the rendered dimensions of a sprite, I'm calling Draw in the class below:

```
public class Ship
{
    public Ship(Texture2D texture)
    {
        Width = texture.Width;
        Height = texture.Height;

        Texture = texture;
    }

    public int Width { get; set; }

    public int Height { get; set; }

    public float Scale { get; set; }

    public Vector2 Position { get; set; }

    public Texture2D Texture { get; }

    public Rectangle Rectangle => new Rectangle((int)Position.X, (int) Position.Y, Width, Height);

    public void Draw(SpriteBatch batch)
    {
        var origin = new Vector2(Texture.Width / 2, Texture.Height / 2);
        var scale = new Vector2(Scale, Scale);
        var rotation = GetRotationInRadians();

        batch.Draw(Texture, Position, null, Color.White,
            rotation,
            origin,
            scale,
            SpriteEffects.None, 0f);
    }
}

```

The problem is Width and Height are based off the source (see the constructor) Texture size, so *after* drawing they are not actual dimensions. Is there away to determine the scaled sprite size?

Side note: I'm using these dimension to detect if an sprite was clicked on by the mouse. Maybe there is a better way to detect clicks?

# Answer
> 1 votes
I'm now using Monogame.Extended, Camera and Sprite classes to detect mouse collision:

```
public RectangleF GetBoundingRectangle()
{
    return Sprite.GetBoundingRectangle(_transform);
}

```

---
Tags: xna, monogame
---


# Question
Title: Run n' Gun game: Fixating the gun's angle
I am trying to have the gun stick to facing the left or right when the player isn't pressing any of the arrow keys. For instance, if the player is aiming diagonally up-left, then when the player lets go of the arrow keys the gun should aim to the left. Here is the code, it is when it starts using the facing variable. Right now it stays stuck aiming in any direction.

```
//Keyboard Aim
key_left = keyboard_check(vk_left);
key_right = keyboard_check(vk_right);
key_up = keyboard_check(vk_up);
key_down = keyboard_check(vk_down);

if (oPlayer.controller == 0)
{
    var dir = point_direction(0, 0, key_right-key_left, key_down-key_up);
    if (key_left!=0 || key_right!=0 || key_up!=0 || key_down!=0)
    {
        image_angle = round(dir / 45) * 45;
    }
    //Make it so the gun aims only left or right when not pressing arrow keys
    if (key_right || key_left)
    {
        facing = key_right - key_left;
    }
    else
    {
        dir = point_direction(0, 0, facing, 0);
    }
}

```

# Answer
> 0 votes
In the code you've written here, `dir` is a local variable that gets thrown out at the end of the function. It doesn't store any information for the next frame or directly affect game state.

In order to have a visible outcome, you need to update your `image_angle` variable.

But you only do that in one place:

```
if (key_left!=0 || key_right!=0 || key_up!=0 || key_down!=0) {
    image_angle = round(dir / 45) * 45;
}

```

And this code is skipped entirely when no keys are pressed.

Later on, you update `dir` to your desired direction for the case where no keys are pressed, but now it's too late.

```
else {
    dir = point_direction(0, 0, facing, 0);
}

```

The only thing `dir` does after this point in your function is wink out of existence. Because you don't assign it to your `image_angle`, this code has no visible outcome.

It looks like you want your function to look more like this:

```
// Cache our left-right facing direction
// whenever it's non-zero.
var newFacing = key_right - key_left;
if (newFacing != 0) {
    facing = newFacing;
}

// Compute our aim angle, using the
// cached left-right facing, and the
// latest up-down input, if any.
var dir = point_direction(0, 0, facing, key_down-key_up);

// Apply the result so we can see it.
image_angle = round(dir / 45) * 45;

```

Now `image_angle` is always updated at the end of the function, whether we're pressing any keys or not.

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


# Question
Title: Godot: How do I create a temporary invincible state or invincibility frames?
**My issue**

I have been racking my head around how to achieve invincibility frames. Working in the Godot Engine I have considered a few methods for this:

* Setting a Timer Node when damaged to trigger the invincibility
* setting a knockback variable, converting it into an int which is then multiplied by the movement vector.

> move\_dir * int(self.knockback)

Each of these runs into the problem of how do I return the state back at a set interval to prevent some sort of ping-pong effect when many enemies are present.

there likely is something better that I haven't yet considered for this, but I just want to know what else is out there for this. Any algorithms or techniques will be welcome. I just want to help get the end of this.

# Answer
> 1 votes
For the invincibility frame I’m not quite sure what you mean, but I would recommend watching this video: https://youtu.be/Cx\_i4Uei\_ME As it helped me with something sort of similar

As for the knockback variable do you mean the player takes knock back from enemy damage? Or do you meant the player gives knock back to an enemy? Also is it 2d or 3D because the answer will definitely vary based on that alone.

---
Tags: collision-detection, algorithm, collision-resolution, godot
---


# Question
Title: How to make a countdown timer based on local time
I have a problem. In my GetTime.cs script, I am getting local time from an Android/iOS device, and simply assigning it to a Text component.

```
private void Update()
{
    time = System.DateTime.Now.ToLocalTime().ToString("HH:mm:ss");
    timeText.text = time;
}

```

I am making a travel system, that takes X amount of seconds to get from point A to point B. While in travel, you cannot do any actions.

How can I make this into a countdown timer based on local time? For example, I want to do travel from point A to point B like this:

* I am in point A
* I choose an option to travel to point B
* I wait 30 seconds
* I am at point B

But it has to be based on local time, and it has to work in the background, even when the app is not running.

# Answer
It looks like you want to do something like this, using PlayerPrefs to store the state between runs of the game. (This is insecure, but so is using the local system time - if a player wants to cheat, they can just change their local clock anyway, so we might as well keep things simple)

```
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using DateTime = System.DateTime;
using TimeSpan = System.TimeSpan;

public class CountdownAction : MonoBehaviour
{
    // Assign a unique name here so two different countdowns
    // don't fight for the same save location.
    public string actionKey = "travelStart";
    public int durationSeconds = 60;
    public Text display;

    public UnityEvent OnComplete;

    DateTime? _startTime;

    // On load, try to resume our countdown from where we left off.
    void Start() {
        // If we don't have a saved start time, then there's no action in progress.
        // So we'll abort, and wait patiently for the player to start the action.
        if (!PlayerPrefs.HasKey(actionKey))
            return;

        // Otherwise, load our saved start time.
        // PlayerPrefs doesn't support DateTime natively, so we'll decode it from a string.
        var savedString = PlayerPrefs.GetString(actionKey);
        if (long.TryParse(savedString, out long ticks)) {
            _startTime = new DateTime(ticks);
        } else {
            Debug.LogWarningFormat("Indecipherable countdown start time for {0}, restarting countdown.", actionKey);
            _startTime = DateTime.Now;
        }

        // Wait for the action to complete, updating our countdown timer in the meantime.
        StartCoroutine(WaitForCompletion());
    }

    // Start a new countdown.
    public void StartCountdown() {
        if (_startTime.HasValue) {
            // Abort the countdown in progress and warn the developer - this might be a sign of a bug.
            Debug.LogWarningFormat("Restarted the countdown for {0} when one was already running!", actionKey);
            StopAllCoroutines();
        }

        // This moment is when we will measure the duration from.
        _startTime = DateTime.Now;

        // Save this in our player prefs, so we can recover it even if the app is closed & restarted.
        PlayerPrefs.SetString(actionKey, _startTime.Value.Ticks.ToString());
        // To be safe, let's save this data to disc right away, just in case our app crashes or we lose power.
        PlayerPrefs.Save();

        // Wait for the action to complete, updating our countdown timer in the meantime.
        StartCoroutine(WaitForCompletion());
    }

    // This can be a win compared to Update, since it runs only when we have a countdown in progress.
    IEnumerator WaitForCompletion() {
        int remainingSeconds;

        do {
            // Compute how much time has passed since the countdown started.
            var elapsed = DateTime.Now - _startTime.Value;

            // Subtract the time we've waited from the total duration of the action.
            remainingSeconds = Mathf.Max(durationSeconds - (int)elapsed.TotalSeconds, 0);

            // Display the difference in our text field.
            display.text = (new TimeSpan(0, 0, remainingSeconds)).ToString(@"hh\:mm\:ss");

            // Wait a frame.
            yield return null;
        // Loop until the countdown is over.
        } while (remainingSeconds > 0);

        // We're done!
        Debug.LogFormat("Action {0} has completed!", actionKey);

        // Clear the countdown, since there's no longer any action in progress.
        _startTime = null;
        PlayerPrefs.DeleteKey(actionKey);

        // Fire off any actions that were wired-up to happen once this timer completes.
        // We'll assume if this countdown has any persistent effects, these handlers
        // will call PlayerPrefs.Save so we don't have to double-up on it here.
        if (OnComplete != null)
            OnComplete.Invoke();
    }
}

```
> 1 votes

---
Tags: unity, c#, mobile, timer
---


# Question
Title: DirectX 11 C2661 & C2664 errors constructing SpriteBatch / SpriteFont
**I keep having these two errors:**

> * Error C2664 'DirectX::SpriteBatch::SpriteBatch(const DirectX::SpriteBatch &)': cannot convert argument 1 from 'ID3D11DeviceContext \*' to 'DirectX::SpriteBatch &&' C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\include\memory 2068
> * Error C2661 'DirectX::SpriteFont::SpriteFont': no overloaded function takes 2 arguments C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\include\memory 2068

I used this source, https://github.com/microsoft/DirectXTK/wiki/SpriteFont

```
std::unique_ptr<SpriteBatch> spriteBatch;
std::unique_ptr<SpriteFont> spriteFont;

spriteBatch = std::make_unique<SpriteBatch>(deviceContext);
spriteFont = std::make_unique<SpriteFont>(device, L"myfile.spritefont");

spriteBatch->Begin();
spriteFont->DrawString(spriteBatch.get(), L"Hello, world!", XMFLOAT2(x, y));
spriteBatch->End();

```

I tried wrapping my: `ID3D11Device` & `ID3D11DeviceContext` with `Microsoft::WRL::ComPtr<>`, but still throws error. Seems there's some issue with the `<memory>`.

**I tried:**

```
ComPtr<ID3D11Device> device = nullptr;
ComPtr<ID3D11DeviceContext> deviceContext = nullptr;

```

**Messages:**

```
Reason: cannot convert from 'ID3D11DeviceContext *' to 'DirectX::SpriteBatch'
No constructor could take the source type, or constructor overload resolution was ambiguous.

```

**EDIT, Complete Build Output:**

```
1>------ Build started: Project: Game, Configuration: Debug x64 ------
1>main.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\include\memory(2068,35): error C2664: 'DirectX::SpriteBatch::SpriteBatch(const DirectX::SpriteBatch &)': cannot convert argument 1 from 'ID3D11DeviceContext *' to 'DirectX::SpriteBatch &&'
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\include\memory(2067,59): message : Reason: cannot convert from 'ID3D11DeviceContext *' to 'DirectX::SpriteBatch'
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\include\memory(2067,59): message : No constructor could take the source type, or constructor overload resolution was ambiguous
1>C:\Users\root\Documents\Visual Studio 2019\Game\Game\include\SpriteBatch.h(90,9): message : see declaration of 'DirectX::SpriteBatch::SpriteBatch'
1>C:\Users\root\Documents\Visual Studio 2019\Game\Game\main.cpp(199): message : see reference to function template instantiation 'std::unique_ptr<DirectX::SpriteBatch,std::default_delete<DirectX::SpriteBatch>> std::make_unique<DirectX::SpriteBatch,ID3D11DeviceContext*&,0>(ID3D11DeviceContext *&)' being compiled
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\include\memory(2068,35): error C2661: 'DirectX::SpriteFont::SpriteFont': no overloaded function takes 2 arguments
1>C:\Users\root\Documents\Visual Studio 2019\Game\Game\main.cpp(200): message : see reference to function template instantiation 'std::unique_ptr<DirectX::SpriteFont,std::default_delete<DirectX::SpriteFont>> std::make_unique<DirectX::SpriteFont,ID3D11Device*&,const wchar_t(&)[32],0>(ID3D11Device *&,const wchar_t (&)[32])' being compiled
1>Done building project "Game.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

```

# Answer
The only way I was able to reproduce issue was to try to use the *DirectX Tool Kit for DirectX 12* library but using the *DirectX Tool Kit for DirectX 11* instructions with a Direct3D 11 device/deviceContext.

IOW: You have the DirectX 12 version of the library added to your DirectX 11 project.

If you want Direct3D 11, be sure to use the instructions from here for obtaining the correct version of the library.

Also make sure to follow the tutorials.
> 1 votes

---
Tags: c++, directx11
---


title: How to use particle editor for libgdx?

text:
# Question
Title: How to use particle editor for libgdx?
In the libgdx wiki, this particle editor is recommended. And this blog was helpful. But the problem is that I am not sure yet how to use it for my game. Let's say I want to have a fire-effect in my game. How can I get help for this particle editor?

# Answer
> 6 votes
Found the answer in here. You can directly use the output of the editor in the API. It's really cool.

# Answer
> 0 votes
If you mean 3D particle effects, there is also a "new" Wiki page for using the particles: https://github.com/libgdx/libgdx/wiki/3D-Particle-Effects

---
Tags: tools, assets, particles, libgdx
---


# Question
Title: How should I manage my data that needs to be associated with rank (Unity)
So I am making a game with a similar content progression to Clash Royale. Essentially u have ranking points (Identified as Trophies), and the number of trophies you have will determine what content you will have access to in the game. So for example every 100 ranking points, you will be able to find new types of cards in chests, new chests in general or new maps. In my game, I want it to be somewhat similar, but I also have some other data that changes based on rank points that is more specific to my game, such as army supply. I'm trying to figure out how I can implement this in a manageable way.

Maybe this is overkill, but this is my design so far:

Basically I have my RankContentItemBase class which has a ranking points int and an IsUnlocked method that returns whether or not the passed in rank is \> than the rank passed in. Then I extend this with classes with classes that add the data type I wanna work with (Int, Troop, Map, w/e).

I then have a Generic base container class that has a method for getting all unlocked item in the list of T contents that is extended to contain the concrete RankUnlockItembase types.

I've basically structured things this way so it's easy for me to add new types of items that I want unlocked by rank without having to do much work. Also it prevents things from being coupled together.

Just curious what ppl think of this setup, and what kinda setup you would go with? One concern I have with this design was that if I wanted to see whether a troop was unlocked or not, I can't just say troop.IsUnlocked(). Instead I have to create a new means of determining whether or not a troop is unlocked yet, like for example maybe a method on the RankUnlockedTroopContainer that determines this. Maybe this is ok? I feel like I'm sacrificing simplicity for the sake of maintainability/flexibility.

Thanks

# Answer
> 2 votes
When you have a data-structure which fits your design workflow but is bad for runtime, then you always have the option to convert it into a more runtime-appropriate data structure at game startup.

Your current architecture seems to allow you to quickly see which rank unlocks what content. But you might also require the reverse: On which rank is a specific piece of content unlocked?

You can easily enumerate that information at startup by going through all the ranks and determining the unlock-rank for each item. That information could be stored in `RankUnlockedItemBase`, or it could be stored in a lookup-table (`Dictionary<RankUnlockedItemBase, int>`).

You could also use this as an opportunity for a sanity-check. Currently it looks to me as if nothing stops you from adding the same item as an unlock to multiple ranks. This could easily happen if you move a lot of items around between ranks over the course of your development. This could lead to confused players at best and weird bugs at worst. So this would be a good opportunity to log a warning if a piece of content gets a rank assignment even though it already has one. And after finding the unlock rank of each item, you can check if there are any items which are unobtainable because they don't have an unlock-rank and also log that as a warning.

---
Tags: unity
---


title: Draw calls in Unity 3d

text:
# Question
Title: Draw calls in Unity 3d
I have only 20 materials in my game (19 are made with textures atlas). But the Setpass call is 72. I don't understand why. I want to know how to decrease the number of SetPass call.
This is a brief summary about the game:
Houses vertex attributes : from 43 to 270. They are low poly houses. Props too.
No normal maps. Only diffuse and ambient occlusion maps. Only the Playable character has his own texture. There 45 houses models. I have 19 textures atlas.
In the game, some houses are assembled to formed another house (modular houses). And I assembled 10 to 18 houses to form a BLOC (a piece of town).
For all the gameObects, SHADER is Universal Render Pipeline. I didn't edit anything, I use the default properties.
In the game, Bloc of houses are put together 3 by 3 and randomly to form town like (SUBWAY SURFER)
In Unity playmode :
Tris : 54.9k
Verts: 80k
Batches : 466
Saved by batching : 0
Shadow caster: 0
Visible Skinned meshes: 1

# Answer
> 0 votes
This is something that is easy to diagnose yourself. Just turn off objects in your scene (uncheck the box next to their name in the inspector to deactivate their GameObject) one at a time and watch how the stats change. If the SetPass calls drop off a lot after disabling a particular object, you've found your culprit. Then you just need to investigate the configuration of that object.

---
Tags: unity, textures, performance, materials, texture-atlas
---


# Question
Title: prefab editor not working for NGUI in unity2018
i just updated my project from unity5 to unity 2018. my project uses ngui as UI solution. eveything works fine in updated version but when i want to edit prefabs in prefab mode i get this message:

is there any idea about cause of this problem and how to solve it?

i looked for updating ngui for unity 2018 but because of many changes ngui has, it causes lots of problem in project that takes lots of time to solve the mall

# Answer
some special prefabs or gameobjects need a certain parent object. for example any Unity UI object needs to be parented directly or indirectly with canvas object. NGUI is the same and any ui object needs to be parented with object with UIRoot Component with same layer.

in new version of ngui its handled but in older versions Unity doesnt know what is the parent gameobject and in start of prefab editor you see the error and you have to return.

you can make an empty scene and drop a UIRoot in it and save it and in

Edit\>Project Settings\>Editor\> Prefab Editing Environment

set that scene to **Regular Environment** and **UI Environment**
> 1 votes

# Answer
In 2018.4 you can edit prefab edit environment in ProjectSettings/Editor
> 1 votes

---
Tags: unity, ngui
---


# Question
Title: Is it bad form to use singletons in unity
I've heard **a lot** of people say singletons are bad practice and an 'anti-pattern', like here, this answer this article and here. However, a lot of the reasons I've read about seem to be to do with dangers in their creation, them not being thread safe, difficult to destroy safely etc. But in unity where there are functions such as `awake()` and `start()` which are (as far as I'm aware) guaranteed to only be called once, are they unsafe to use?

# Answer
> 2 votes
You have stumbled onto a controversial topic in the programming world. Most people dislike singletons, but we game developers tend to be a bit more friendly towards them. There are pros and cons to singletons.

My answer is specific to Unity, and covers maybe 1% of the topic.

In Unity, Singletons are very useful. Let's say you have a manager class that you want to be globally accessible. You could make a static class instead - but then you lose access to Unity messages, Awake, Start, Update, etc., which are the heart of MonoBehaviours.

You mentioned thread safety - Unity is single threaded. So you will not run into these problems (unless you explicitly break off the main thread).

So why are they so bad? There are much better articles, like the ones you linked, which explain it much better than I can.

But if you stay disciplined, Singletons can make game development much easier. However, since you don't have any of the safeguards that you gain with other design patterns, it is easy to fall into the traps that Singletons present.

# Answer
> 2 votes
Awake() and Start() are called only once per object for reasons unrelated to Singletons. The single instance part of the singleton is fine, and its possible to make it thread safe and control how many things its keeping in memory because it never dies. It's the global accessibility that a lot of design pattern people dislike. Having a singleton in your code won't break it, but using them for everything can cause problems. Take it from someone who built a prototype held together by a half dozen singletons. I would slap that version of me if I could.

In large projects, it is important to 'decouple' your code. Overuse of Singletons promotes coupling code together. An example is a having an AudioSingleton that plays sounds. It looks like an awesome idea because then you can simple call *AudioSingleton.Instance.PlaySound(GUNSHOT1);* in your weapon code, and you're done. That's actually a huge problem. Now your weapons depend on the existence and functionality of the AudioSingleton.

It gets worse as the project grows, and the team grows. Every button press is a series of calls to different singletons, or one call to a massive singleton that sits at the center of your project, immovable and instable. Singletons lash together disparate objects and make it easier to cause problems and make finding problems more difficult.

There is a time and place for Singletons, but you need to be careful that you aren't solving a problem that just needs some carefully laid out wires and some solder with a global communications network. If you can avoid using a singleton by using something like the Observer pattern, you almost always should.

Also, even when you are working alone, your "team" grows over time, because you forget what you were thinking when you wrote your old code. In the years of solo development I've learned one thing: if you don't want to hate yourself write code like you're in a team.

I'd suggest reading this book: https://gameprogrammingpatterns.com/contents.html It put labels on all the patterns I blindly trying to use and explained their pros and cons with good examples.

---
Tags: unity, c#, design-patterns
---


# Question
Title: How can I get the speed of finger drag using unity TouchPhase.Moved?
I'm making a mobile game where you control a 3d ball by touch. So far I can get it to roll based on finger down and drag (via TouchPhase.Moved) but I want to be able to detect a fast flick or finger swipe so that I can addforce based on finger speed and let go. Bit like how I would if I was only using TouchPhase.Began and TouchPhase.Ended with calculating start/end position and time duration, but now I think I need to do something in .Moved to keep track of finger speed and get the start and end position of the beginning and end of that fast finger movement. Here's my code so far:

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

          if (touch.phase == TouchPhase.Began)
          {
              touchdown = true;
          }

          if (touch.phase == TouchPhase.Moved)
          {
              if (touchdown == true)
              {
                  startPos = new Vector2(0, 0);
              }
              else {
                  startPos = Input.GetTouch(0).position;
              }

              touchTimeStart = Time.time;

              direction = startPos - endPos;
              timeInterval = touchTimeFinish - touchTimeStart;

              endPos = Input.GetTouch(0).position;
              touchTimeFinish = Time.time;

              rb.AddForce(direction.x * force, 0, direction.y * force/ moveSpeed);

              touchdown1 = false;

          } if (touch.phase == TouchPhase.Ended)
      {
          startPos = new Vector2(0, 0);
          endPos = new Vector2(0, 0); } }

```

# Answer
I was overthinking it. Just used start and end time and position for TouchPhase.Began and .End. Also reset touch start values on TouchPhase.Stationary.
> 0 votes

---
Tags: unity, c#, movement, touch, control
---


title: UE4 - Cloth collision

text:
# Question
Title: UE4 - Cloth collision
How is collision working in UE4 Free Asset Paragon-Kallari? It seems like the body of the character and the cape is somehow colliding but I wasnt able to find any physics asset or any setting. Could someone help me with this?

# Answer
> 1 votes
I never worked with specifically Kallari asset, but I worked with Shinbi asset, which is from the same asset pack.

The thing is, Paragon assets were made before Clothing Tool built in into the engine, which means they were handled using collision from the APEX clothing data. This APEX clothing method is pretty much outdated by the time 4.16 came out.

Speaking of cloth simulation, you should use the newer Clothing Tool method for per vertex cloth simulation. Or if you want for more controlled cloth physics, you can use physics-driven bones on the cloth simulated with Anim Dynamics or KawaiiPhysics.

---
Tags: unreal-4, cloth
---


# Question
Title: Why isnt setting the global_position working?
Previously my items were relative to the player by node hierarchy. But for items like bombs this is not ideal so i tried to add the items to the world scene, but when i try to adjust the position of the item to the players position it doesnt work and i see the sword in the top left corner of the screen the worlds origin.

Entity Script

```
func use_item(item):
    var newitem = item.instance()
    newitem.own = self
    newitem.global_position = global_position

    #not setting the position of the item correctly

    newitem.add_to_group(str(newitem.get_name(), self))
    get_node("..").add_child(newitem)

    if get_tree().get_nodes_in_group(str(newitem.get_name(),self)).size() > newitem.maxamount:
        newitem.queue_free()

```

Sword Script

```
func _ready():
    type = own.type
    $anim.connect("animation_finished",self,"destroy")
    $anim.play(str("swing",own.spritedir))
    if own.has_method("state_swing"):
        own.state = "swing"

func destroy(animation):
    if own.has_method("state_swing"):
        own.state = "default"
    queue_free()

```

It seems like it should work but with an engine like godot there could be several reasons why a certain thing is not working.

https://github.com/MonkeyToiletLadder/wendingo

could it be that in my animation player i set the sword positions as key frames and thats why its not working?

# Answer
I had a very similar question, it is not quite the same scenario, however I believe it could be applied in the same way. Basically, you should create a new var and set it to the player's position, then create a function that takes into the position. Like this.. 1st) If you dont already have one(Add an animation node) if you do then in your ready function I would connect your animation node

```
$AnimationPlayer.add_animation(#animationname, #variable)

```

2nd) Inside your use\_item function: Create a variable that is set to your players position, then run a created function using the directions below 3rd) Create a function that takes in that new variable, runs through the position logic and then play the animation(if you need help with this ill post another comment) 4) Implement this function where you need it in your code Hope this helps!
> 1 votes

---
Tags: godot, gdscript
---


title: How to build a game for linux in unity

text:
# Question
Title: How to build a game for linux in unity
I made a game and uploaded it to a game site. I exported the build as windows mac OS and Linux. My thinking was that it supported all of those platforms but i guess not. Someone commented saying that the game didn't support linux. I have no idea why since it said it built for mac and windows and linux. Do i have to change settings? If so were? if its target platform i cant because the only option is windows.

# Answer
Sounds like you haven't installed build support for Linux binaries in Unity. The way to do this in Unity can be found here:

1. Open the Hub.
2. Select Installs.
3. Find the Editor you want to add the components to.
4. Click the three dots to the right of the version label, then select Add Modules. (NOTE: If you didn’t install the Editor via the Hub, you will not see this option. To enable this option, install the Editor via the Hub.)
5. In the Add Modules dialog, locate the module to add and tick its checkbox.
6. When you have selected all the modules to add, select Done.

Note that while Unity can export binaries to other platforms, you probably still want to test the output binary on a system with the target platform, perhaps in a VM for an example.
> 4 votes

---
Tags: unity, build-process
---


# Question
Title: Find the current player instance from multiple scripts
I have the following code used by multiple classes (e.g. Enemy, Scenary, EnemyProjectile etc.) in my game, which seems intrinsically wrong. What are some ways I could write this code once and use it from multiple places?

```
        GameObject go = GameObject.Find("Player");
        if (go == null)
        {
            Debug.Log("Failed to find Player go");
        }
        else
        {
            _player = go.GetComponent<Player>();

            if (_player == null)
            {
                Debug.Log("Failed to find player component");
            }
        }

```

I usually have this code in an Awake function but sometimes I do it in a collision event, e.g. for EnemyProjectile grabbing a player handle would often not be required and thus a wasted lookup. Player is a private variable in the class definition of each class.

# Answer
> 1 votes
This type of thing is often implemented using some form of the Singleton pattern. Here's one version, fairly similar to what you're doing now, just without the redundant double-search for the object, then the component, when all you really wanted was the component:

```
public class Player: MonoBehaviour {

     static Player _instance;
     public static Player instance {
         get {
             if(_instance == null) {
                 _instance = FindObjectOfType<Player>();
                 UnityEngine.Assertions.Assert.IsNotNull(_instance, "Failed to find player component.");
             }

             return _instance;
         }
     }
}

```

Now other scripts can just ask for the current instance like this:

```
_player = Player.instance;

```

...and the singleton will look it up for them. It returns a cached copy quickly if it's been asked before, and only does the slow search the first time it's asked, or after the player's been destroyed and re-created.

You can also skip the search entirely and have your player "report" itself on load:

```
void Awake() { _instance = this; }

```

...but this can cause timing issues if you have other scripts that need to reference the player in their own `Awake` methods that happen to run before the player got a chance to do so. If you can safely defer all references to the player until `Start` or `Update` though, this is an option.

(As an aside, some folks find they use this pattern so much that they implement it in a `Singleton<T> : MonoBehaviour where T: Singleton<T>`, using the curiously recurring template pattern, so they can quickly add it to any class by declaring it as `Player : Singleton<Player>`. This can help if you're worried about the amount of boilerplate this adds to every type you want to look up this way.)

You'll find folks are often critical of the singleton pattern for good reasons, though the risk of making the data global doesn't really apply here - as your code shows, access to the player object was already available globally.

So in this case, the main risk this method introduces is that it limits you to a single player at a time. If you ever want to have multiplayer with multiple instances of the `Player` class active in the scene at a time, this method only lets you find the first one, and so you have some heavy refactoring to do if you've got dozens of scripts that all find "the" player this way.

That's no worse than your current code, and it's acceptable for many Unity games. And it's still solvable. You can replace your `instance` property with a `public static GetPlayer(int playerID)` function, or a `GetClosestPlayer()`, etc. Then systematically replace each occurrence of `Player.instance` with the appropriate alternative. It's work, but not an insurmountable obstacle.

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


# Question
Title: How do I create a laser pointer dot in Unity URP?
I want to replicate the laser pointer dot as in RE4:

Here is a video that shows the laser in action.

I have tried to replicate it using a spotlight. The problem with the spotlight is that its size can only be controlled by its distance to the object. I'm struggeling really hard with keeping it at just the right distance.

Since this is such a big problem, I would first of all like to ask if a spotlight is the preferred way to create such a laser dot.

Thank you.

# Answer
> 0 votes
I'm now using a Screen Space Decal Shader that works with URP, specificially this one:

https://github.com/ColinLeung-NiloCat/UnityURPUnlitScreenSpaceDecalShader

I will update my answer with the details as soon as I have it completed. I'm still working on the details of an implementation.

---
Tags: unity
---


# Question
Title: Unity AI issue with recalculating NavMesh at runtime
I am using Unity NavMesh to control my units.

I am running into an Issue when updating Navmesh at runtime, It seems agents re-calculate their path whenever it is modified, which makes sense, but it causes this line (check if unit is on last corner) to return an `IndexOutOfBounds` error:

```
agent.steeringTarget == agent.path.corners[agent.path.corners.Length - 1]

```

I guess something is happening while re-calculating path that might mess with this for 1 frame. I solved this by putting a try/catch around it, but is there some better way I can manage this so I don't get the error at all?

# Answer
> 0 votes
The most likely explanation is that the path length is 0, so `agent.path.corners.Length - 1` would give an index of `-1`, which is of course invalid.

Try this:

```
if (agent.path.corners.Length > 0) {
    agent.steeringTarget = agent.path.corners[agent.path.corners.Length - 1]
}

```

---
Tags: unity
---