title: stop object while falling

text:
# Question
Title: stop object while falling
The object have `forwardForce`.

```
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce=800f;
    void Start()
    {

    }

    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }
    }
}

```

Now, the issue is I want to stop that object while falling down(not on that ground anymore).The camera will keep running but, I just want to stop that object. Which means if the is not on ground anymore than `velocity=0`

# Answer
> 0 votes
```
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce=1000f;

    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }
        if(Physics.Raycast(transform.position,Vector3.down,0.5f)==false){
            rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, 0);
        }else{

        }
    }
}

```

I tried by detecting the player is `onGrounded` or not. Then, I set velocity = 0 if player isn't grounded

Thanks Zibelas

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


# Question
Title: How do I stop clicks on a button from also triggering my gameplay scripts?
My character jumps when I press the right side of screen. The pause button is alsp in the top right corner. So when I press that button, the right side script always triggers and I don't want that to happen.

Here the script :

<pre><code> if (Input.GetMouseButtonDown(0))
            {
                float xPosition = Input.mousePosition.x;

                if (xPosition > Screen.width / 2 && isGrounded && !isJump)
                {
                    // mouse is on the right part of the screen, shoot right

                    rb2d.velocity = new Vector3(0, jumpForce, 0);

                    isJump = true;

                    JumpSoundSfx();
                }
            }

            if (Input.GetMouseButton(0))
            {
                float xPosition = Input.mousePosition.x;

                if (xPosition < Screen.width / 2 && !isJump)
                {
                    // mouse is on the left part of the screen, so shoot to the left

                    crouch.SetActive(true);

                    stand.SetActive(false);
                }
            }
```
</code></pre>

# Answer
> 1 votes
Unity has a way to “consume” input events, so that they don’t trickle down to other places that listen to them. This is a somewhat complicated topic, but generally, the ones rendered “on top” will get the events first. So if you make them eat up the event, it won’t reach the lower layers “underneath”.

Check out https://docs.unity3d.com/ScriptReference/Event.Use.html

Good place to start.

# Answer
> 2 votes
Yeah, actually I've fixed the issue using this `EventSystems.current.IsPointerOverGameObject()`, here the full doc

https://docs.unity3d.com/2018.2/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html

```
 if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
            {
                float xPosition = Input.mousePosition.x;

                if (xPosition > Screen.width / 2 && isGrounded && !isJump)
                {
                    // mouse is on the right part of the screen, shoot right

                    rb2d.velocity = new Vector3(0, jumpForce, 0);

                    isJump = true;

                    JumpSoundSfx();
                }
            }

            if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
            {
                float xPosition = Input.mousePosition.x;

                if (xPosition < Screen.width / 2 && !isJump)
                {
                    // mouse is on the left part of the screen, so shoot to the left

                    crouch.SetActive(true);

                    stand.SetActive(false);
                }
            }

```

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


title: How to detect direction of rotation?

text:
# Question
Title: How to detect direction of rotation?
I have a character with a camera behind him. The head of the character rotates with the `LookAt` function on the character's head rig.

The `LookAt` is done towards targets that may be to the right or left of the entire body of the transform character.

So I want to detect when the head rotates clockwise with respect to the controller body and when it rotates counterclockwise. How can I do this?

# Answer
> 2 votes
Assuming you have the `Transform` for your `target` object, and the `Transform` of the `body` the head is attached to, you can compute whether it's on the left or right side of the body by looking at the sign of the dot product:

```
Vector3 toTarget = target.position - body.position;
float dot = Vector3.Dot(toTarget, body.right);

if (Mathf.Approximately(dot, 0f)) {
    // Target is straight ahead.
} else if (dot > 0f) {
    // Target is to the right (head rotates clockwise when viewed from above).
} else if (dot < 0f) {
    // Target is to the left (lead rotates counter-clockwise when viewed from above).
}

```

You can also compare against the head's `.right` vector if you want to know whether it's to the left or right of your current look direction, before you update to look at the target. That would let you detect when you're looking to the right but rotating incrementally forward (counter-clockwise) to follow a target that's moving to get in front of you.

---
Tags: unity, c#, rotation, linear-algebra
---


# Question
Title: How to stop a jump midair and remove y velocity in the process
What I want to do is to cut a jump midair by turning off the y velocity when the player releases the jump button (like in Hollow Knight). I managed to do that with:

```
rb.velocity = new Vector2(rb.velocity.x, 0f);

```

My problem is when I cut the jump and I am midair, if I repeat the release jump button process, the whole thing happens again, the character staggers as long as I am releasing the jump button continously.

I would like to be able to do that only once when I am off the ground. I am a noob when it comes to coding so I don't really know what to do.

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

 public class PlayerController : MonoBehaviour {

     public Animator animator;

     private Rigidbody2D rb;
     public float speed;
     private float moveInput;
     public float jumpForce;

     private bool isGrounded;
     public Transform feetPos;
     public float checkRadius;
     public LayerMask whatIsGround;

     private float jumpTimeCounter;
     public float jumpTime;
     private bool isJumping;
     private bool facingRight = true;
     public float jumpDownForceY = 0;

     void Start()
     {
         rb = GetComponent<Rigidbody2D>();

     }

     void Update()
     {

         isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);

         if (Input.GetButtonDown("Jump") && rb.velocity.y == 0)
             rb.AddForce(Vector2.up * 700f);

         if (Mathf.Abs(moveInput) > 0 && rb.velocity.y == 0)
             animator.SetBool("Running", true);
         else
             animator.SetBool("Running", false);

         if (rb.velocity.y == 0)
         {
             animator.SetBool("Jumping", false);
             animator.SetBool("Falling", false);
         }

         if (rb.velocity.y > 0.2)
         {
             animator.SetBool("Jumping", true);
         }

         if (rb.velocity.y < 0)
         {
             animator.SetBool("Jumping", false);
             animator.SetBool("Falling", true);
         }

         if (isGrounded == true && Input.GetButtonDown("Jump"))
         {
             isJumping = true;

             jumpTimeCounter = jumpTime;
             rb.velocity = Vector2.up * jumpForce;
         }

         if (Input.GetButton("Jump") && isJumping == true)
         {

             if (jumpTimeCounter > 0){
                 rb.velocity = Vector2.up * jumpForce;
                 jumpTimeCounter -= Time.deltaTime;
             } else {
                 isJumping = false;
             }

         }

         if (Input.GetButtonUp("Jump"))
         {
             isJumping = false;
             rb.velocity = new Vector2(rb.velocity.x, 0f);

         }

     }

     void FixedUpdate()
     {
         moveInput = Input.GetAxisRaw("Horizontal");
         rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
         Flip(moveInput);

     }

     private void Flip(float moveInput)
     {
         if (moveInput > 0 && !facingRight || moveInput < 0 && facingRight)
         {
             facingRight = !facingRight;
             Vector3 theScale = transform.localScale;
             theScale.x *= -1;
             transform.localScale = theScale;
         }

     }
 }

```

# Answer
> 1 votes
Solved it by checking if the button is up AND the y velocity is more than zero. Basically the velocity code will not be executed when the character is falling. Here is the code snippet:

```
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0)
    {
        isJumping = false;
        rb.velocity = new Vector2(rb.velocity.x, 0f);

    }

```

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


# Question
Title: How does glm::lookAt produce a View Matrix?
Say we do this:

```
glm::mat4 View = glm::lookAt(glm::vec3(4,3,-3), glm::vec3(0,0,0),glm::vec3(0,1,0));

```

And after printing to the console with glm tostring (column major order):

```
View = -0.600000 -0.411597  0.685994  0.000000
        0.000000  0.857493  0.514496  0.000000
       -0.800000  0.308697 -0.514496  0.000000
       -0.000000 -0.000000 -5.830953  1.000000

```

This matrix works as intended. I multiplied it by a perspective projection matrix and passed the resulting matrix in to my vertex shader to be multiplied by the vertices of a cube with side length = 1. So the full expression for each projected vertex is:

```
VERTEX                   VIEW                              PERSPECTIVE PROJECTION
 p.x    -0.600000 -0.411597  0.685994  0.000000     0.629325 0.000000  0.000000  0.000000
 p.y  *  0.000000  0.857493  0.514496  0.000000  *  0.000000 0.839100  0.000000  0.000000
 p.z    -0.800000  0.308697 -0.514496  0.000000     0.000000 0.000000 -1.002002 -1.000000
 1.0    -0.000000 -0.000000 -5.830953  1.000000     0.000000 0.000000 -0.200200  0.000000

```

Which produces this:

However, I was under the impression that to account for the translation of the camera, the camera's coordinates should be inverted and placed in the fourth column of the **View Matrix**. So I tried this:

```
  VERTEX                   VIEW                               PERSPECTIVE PROJECTION
   p.x    -0.600000 -0.411597  0.685994 -4.000000     0.629325 0.000000  0.000000  0.000000
   p.y  *  0.000000  0.857493  0.514496 -3.000000  *  0.000000 0.839100  0.000000  0.000000
   p.z    -0.800000  0.308697 -0.514496  3.000000     0.000000 0.000000 -1.002002 -1.000000
   1.0    -0.000000 -0.000000 -0.000000  1.000000     0.000000 0.000000 -0.200200  0.000000

```

Which produces this:

Why does the first **View Matrix** work but not the second one?

# Answer
> 4 votes
Alright so upon looking into it further, here's how glm::lookAt produces a View Matrix:

1. Make a row-major ordered **4x4 Translation Matrix** by negating the **camera position**, **c**:

```
  1     0     0     0
  0     1     0     0
  0     0     1     0
 -c.x  -c.y  -c.z   1

```
2. Multiply it by a column-major ordered **4x4 Rotation Matrix** that you make using the formula here: https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluLookAt.xml

```
             TRANSLATION             ROTATION
         1     0     0     0     x.x  y.x  z.x  0
VIEW  =  0     1     0     0  •  x.y  y.y  z.y  0
         0     0     1     0     x.z  y.z  z.z  0
        -c.x  -c.y  -c.z   1     0.0  0.0  0.0  1

```

So what I think is going on is you're effectively inverting the **camera-to-world** matrix to get the **world-to-camera** matrix. The above equation produces a column-major ordered **View Matrix**.

And for people like me who like row-major ordered matrices (contiguous memory gang), you can do this with a **row-major ordered rotation matrix** to produce a row-major ordered **View Matrix**. Notice the multiplication order must be swapped:

```
             ROTATION            TRANSLATION
         x.x  x.y  x.z  0       1  0  0  -c.x
VIEW  =  y.x  y.y  y.z  0   •   0  1  0  -c.y
         z.x  z.y  z.z  0       0  0  1  -c.z
         0.0  0.0  0.0  1       0  0  0     1

```

---
Tags: opengl, mathematics, matrix, projection-matrix
---


# Question
Title: How to interpolate colors around the spectrum of hues?
I wanted to generate a 7 segment display whose color brightness varies with time, this can be done by just using linear relationship.

```
Color activeColour2 = new Color(1, DateTime.Now.Millisecond*0.001f, DateTime.Now.Millisecond*0.001f);

```

So in 1 complete second, it produce color in the range of (1,0,0) to (1,1,1) as in the code below:

```
using System;
using UnityEngine;

public class ClockDigit2 : MonoBehaviour
{
    static readonly bool[,] SEGMENT_IS_ACTIVE = new bool[,] {

        {true,  true,  true,  true,  true,  true,  false}, // 0
        {false, true,  true,  false, false, false, false}, // 1
        {true,  true,  false, true,  true,  false, true }, // 2
        {true,  true,  true,  true,  false, false, true }, // 3
        {false, true,  true,  false, false, true,  true }, // 4
        {true,  false, true,  true,  false, true,  true }, // 5
        {true,  false, true,  true,  true,  true,  true }, // 6
        {true,  true,  true,  false, false, false, false}, // 7
        {true,  true,  true,  true,  true,  true,  true }, // 8
        {true,  true,  true,  true,  false, true,  true }  // 9
    };

    public Color32 inactiveColour = Color.black;

    public SpriteRenderer[] segments = new SpriteRenderer[7];

    public void Display(int number)
    {
        Color activeColour2 = new Color(1, DateTime.Now.Millisecond*0.001f, DateTime.Now.Millisecond*0.001f);
        var digit = number % 10;
        if (digit < 0) digit *= -1;

        for (int i = 0; i < 7; i++)
        {
            if (SEGMENT_IS_ACTIVE[digit, i])
            {
                segments[i].color = activeColour2;
            }
            else
            {
                segments[i].color = inactiveColour;
            }
        }

    }

    void Update()
    {
        Display(DateTime.Now.Second);
    }
}

```

However, now I want to interpolate through all the colors in the circle above over 1 second.

I don't know how to express this as a formula for R, G, and B. The RGB value is not linear relationship: as you spin the selected color in the chart, you can notice the RGBA components vary together in a nonlinear form.

I considered using Lagrangian interpolation. However, this will not be accurate or might fail greatly because if you take a reference point at the circle and assume in 1sec, it made a complete revolution, you will notice there is a certain period of time where the RGB value is constant along the path: either 0 and 1.

So is there any method to get a formula that perfectly fits the color chart with respect to time?

# Answer
I'm not aware of the Color.HSVToRGB method in Unity. using Color activeColour2 = Color.HSVToRGB(DateTime.Now.Millisecond\*0.001f,1,1) give the desired result since the conversion is a linear relationship with respect to time.
> 0 votes

---
Tags: unity, c#, mathematics, color, interpolation
---


# Question
Title: OnTriggerEnter2D or OnCollisionEnter2D not getting called
I checked the other answers for this but mine didn't get fixed Here's the code

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

public class DestroyCollectibles : MonoBehaviour
{
    private void Start()
    {
        Debug.Log("Hallo");
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log("Trigger");
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Collsion");
        // if (collision.gameObject.CompareTag("Collectible"))
        // {
        //     Debug.Log("Apple");
        //     Destroy(collision.gameObject);
        // }
    }
}

```

And screenshots:

# Answer
OnTriggerEnter() is called if your `BoxCollider2D` (the one which something should enter) is marked as `trigger`. And as Zibelas said, you are missing a `RigidBody2D` on one object (the one that is entering).

A quote from the Unity documentation on MonoBehaviour.OnTriggerEnter2D():

> **Note:** Trigger events are only sent if one of the Colliders also has a Rigidbody2D attached. Trigger events are sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.
> 1 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: UNITY: How to LOAD save file from main menu
So I've created a simple main menu with a new game, load game, and quit game buttons. In the new scene where I've created pause menu save/load buttons work, I've created a new object and attached a script to it. So I've used the same logic for the LOAD game button in the main menu, I've created new object and attached script to it and then added that to load button. I then played the game and saved it. I then run the game again and load button didn't work. It didn't output any error or anything.

**The script I've used for both load buttons:**

```
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class LoadGame : SingletonMonobehaviour<LoadGame>
{
    public GameSave gameSave;

    public List<ISaveable> iSaveableObjectList;

    protected override void Awake()
    {
        base.Awake();

        iSaveableObjectList = new List<ISaveable>(); //create new list for the ISaveableObject list field
    }

    public void LoadDataFromFile()
    {
        BinaryFormatter bf = new BinaryFormatter();
        gameSave = new GameSave();
        FileStream file = File.Open(Application.persistentDataPath + "/SaveData.dat", FileMode.Open);
        gameSave = (GameSave)bf.Deserialize(file);

        //loop through all ISaveable objects and apply save data
        for (int i = iSaveableObjectList.Count - 1; i > -1; i--)
        {
            if (gameSave.gameObjectData.ContainsKey(iSaveableObjectList[i].ISaveableUniqueID))
            {
                iSaveableObjectList[i].ISaveableLoad(gameSave);
            }
            else
            {
                Component component = (Component)iSaveableObjectList[i];
                Destroy(component.gameObject);
            }
        }

        file.Close();
    }

    public void SaveDataToFile()
    {
        gameSave = new GameSave();

        //loop through all ISaveable objects and generate save data
        foreach (ISaveable iSaveableObject in iSaveableObjectList)
        {
            gameSave.gameObjectData.Add(iSaveableObject.ISaveableUniqueID, iSaveableObject.ISaveableSave());
        }

        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/SaveData.dat", FileMode.OpenOrCreate);
        bf.Serialize(file, gameSave);
        file.Close();
    }

    public void StoreCurrentSceneData()
    {
        //loop through all ISaveable objects and trigger store scene data for each
        foreach (ISaveable iSaveableObject in iSaveableObjectList)
        {
            iSaveableObject.ISaveableStoreScene(SceneManager.GetActiveScene().name); //it passes current scene name
        }
    }

    public void RestoreCurrentSceneData()
    {
        //loop through all ISaveable objects and trigger restore scene data for each
        foreach (ISaveable iSaveableObject in iSaveableObjectList)
        {
            iSaveableObject.ISaveableRestoreScene(SceneManager.GetActiveScene().name);  //it passes current scene name
        }
    }
}

```

So this is the first scene in the game: On Main Menu object there is a script to start new game and to quit the game. I created new object LoadGame that contains the script above.

This is PauseMenu UI in the game. Basically, players in the game can save/load games and that works normally and as same as I have in the main menu here I too have SaveLoadManager with the script exactly the same (only class name different). I forgot to mention that I created first PersistentScene then I created the MainMenu scene. Maybe the file I save in the game (pause menu) doesn't exist when I press the load button from the main menu. Because If I save the game in the pause menu and load it from there that works.

I have also script GameSave with the following script:

```
using System.Collections.Generic;

[System.Serializable]

public class GameSave
{
    //string key = GUID gameobject ID
    public Dictionary<string, GameObjectSave> gameObjectData;

    public GameSave()
    {
        gameObjectData = new Dictionary<string, GameObjectSave>();
    }
}

```

And ISaveable with the following script:

public interface ISaveable
{
   string ISaveableUniqueID { get; set; }

   GameObjectSave GameObjectSave { get; set; }

    void ISaveableRegister();

    void ISaveableDeregister();

    GameObjectSave ISaveableSave();

    void ISaveableLoad(GameSave gameSave);

    void ISaveableStoreScene(string sceneName);

    void ISaveableRestoreScene(string sceneName);
}
```
</code></pre>

# Answer
> 0 votes
When your code doesn't work, the first thing you should try is usually adding some logging:

```
    public void LoadDataFromFile()
    {
        Debug.Log("Loading data from file...");
        BinaryFormatter bf = new BinaryFormatter();
        gameSave = new GameSave();
        string path = Application.persistentDataPath + "/SaveData.dat";
        Debug.Log("Opening file " + path);
        FileStream file = File.Open(path, FileMode.Open);
        gameSave = (GameSave)bf.Deserialize(file);

        Assert.IsNotNull(gameSave);
        Debug.Log("iSaveableObjectList.Count: " + iSaveableObjectList.Count);

        //loop through all ISaveable objects and apply save data
        for (int i = iSaveableObjectList.Count - 1; i > -1; i--)
        {
            var id = iSaveableObjectList[i].ISaveableUniqueID;
            if (gameSave.gameObjectData.ContainsKey(id))
            {
                Debug.Log("Loading value for Saveable " + i + " with ID" + id);
                iSaveableObjectList[i].ISaveableLoad(gameSave);
            }
            else
            {
                Debug.Log("No saved data found for Saveable " + i + " with ID " + id);
                Component component = (Component)iSaveableObjectList[i];
                Destroy(component.gameObject);
            }
        }

        file.Close();
    }

```

I don't see any place that you add values to `iSaveableObjectList`. Did you forget to populate that list? Does it show up in the Inspector?

---
Tags: unity, 2d, menu, unity-ui
---


title: Curved 3D health bar

text:
# Question
Title: Curved 3D health bar
Hello I would like to make a curved healthbar (like if it is drawn on a cylinder). See the spatial UI element left to the shoulder of the character on this photo for what I mean.

There is a main outline in white and inside the green healthbar When health decrease only the green bar get shorter.

I can use blender 3d but this is not so immediate...

Any idea?

# Answer
I found a pretty neat solution using the LineRenderer component with a script which places its positions on a procedural arc.

First we need a character. I am using Unity Chan from the Asset Store for this demonstration.

Right-click on your character in the Hierarchy and select *Effect \> Line*. Move that new child-Object to where you want the center of the curve to be. Then go to the Inspector of the Line Renderer component and set:

* "Alignment" to "TransformZ"
* "Texture Mode" to "Tile"
* "Cast Shadows" to "Off"

Then add the following script to it:

```
using UnityEngine;

[RequireComponent(typeof(LineRenderer))] // without a LineRenderer, this script is pointless
[ExecuteAlways] // makes it work in the editor
public class CurvedProgressBar : MonoBehaviour {
    [SerializeField]
    private int numSegments = 32; // quality setting - the higher the better it looks in close-ups
    [SerializeField]
    [Range(0f, 1f)]
    private float fillState = 1.0f; // how full the bar is

    public float FillState {
        get => fillState;
        set {
            fillState = value;
            RecalculatePoints();
        }
    }

    private void OnValidate() => RecalculatePoints();

    // Called when you change something in the inspector
    // or change the FillState via another script
    private void RecalculatePoints() {
        // calculate the positions of the points
        float angleIncrement = Mathf.PI * fillState / numSegments;
        float angle = 0.0f;
        Vector3[] positions = new Vector3[numSegments + 1];
        for (var i = 0; i <= numSegments; i++) {
            positions[i] = new Vector3(
                Mathf.Cos(angle),
                0.0f,
                Mathf.Sin(angle)
            );
            angle += angleIncrement;
        }
        // apply the new points to the LineRenderer
        LineRenderer myLineRenderer = GetComponent<LineRenderer>();
        myLineRenderer.positionCount = numSegments + 1;
        myLineRenderer.SetPositions(positions);
    }
}

```

This script controls the positions of the LineRenderer. It arranges them in a half circle.

It should now look like this:

Now you can adjust to taste:

* The current fill state by changing the `FillState` of the CurvedProgressBar component between 0.0 and 1.0 (both in the editor or via script while the game is running).
* Quality vs. performance by changing the NumSegments variable of the curved progress bar up or down. (The default of 32 seems good enough even for close-ups, but you might get away with a smaller number for further away objects)
* The direction where the bar appears by changing the Rotation Y
* The radius of the bar by changing the Scale X and Z. You can also set them to different values to control the amount of curvature.
* The direction from which the bar fills by setting Scale X to a negative value
* Color and width of the bar in the LineRenderer component

OK, but this is still a solid color bar. You wanted some fancy looking border around it. In order to do that we are going to create not one but two of these lines. One for the border (which always stays at fill state 1.0f) and one for the filling. Then we create separate materials for them. Here are the textures I am using. Note that both are the same size. The 2nd one has a transparent padding. Enable "Alpha Is Transparency" in the import settings of both textures.

Don't laugh at me! I am a programmer, not a ui artist!

Then create a material for it. I am using the "Particles/Standard Unlit" Shader here with the following settings:

* Rendering Mode: Fade
* Color Mode: Opaque
* Two-Sided: enabled
* Albedo: \[the textures above\]
* Color: Some shades of green and grey
* Tile X: 0.3183099 (the value of \\$1/π\\$ \- important so the texture matches the arc)

but you can of course use a different shader. What matters is that you pick a shader which supports transparency and two-sided rendering.

This is my end result:

To further improve the results:

* Pick HDR colors and add the Bloom post-processing effect
* Experiment with fancier shaders
* Find a better UI artist than me :)
> 2 votes

# Answer
You can create the mesh in Blender (or another 3D modeling program).

After that, you can create a single channel texture (red for example), where at the start of the health bar it's `0` and it slowly fades to `1` until you get to the end of the mesh, like this:

*Note: The choice of using only one channel for the texture is just because you don't need the rest, you could use regular RGB/RGBA texture if you'd like.*

Then create a shader in your engine of choice, and you could use the health of the player and the texture above, to cut out the health bar as you like.

Here is an example in Unity: https://answers.unity.com/questions/14770/creating-a-circular-progressbar-timer.html
> 0 votes

---
Tags: unity, 3d, gui, graphic-effects, ui-design
---


# Question
Title: Set object rotation according to the outer vertex in unity
I am able to get the outer vertices of a mesh using this and able to generate cubes on outer edges of the mesh. Here is my code:

```
  mesh = GetComponent<MeshFilter>().mesh;
        Stopwatch sp = new Stopwatch();
        sp.Start();
        Vector3[] vertices = mesh.vertices;
        List<EdgeHelpers.Edge> edges =  EdgeHelpers.GetEdges(mesh.triangles).FindBoundary();

        for (int i = 0; i < edges.Count; i++)
        {

            Vector3 v3 = vertices[edges[i].v1];
            GameObject go1 = GameObject.CreatePrimitive(PrimitiveType.Cube);
            go1.transform.localScale = new Vector3(0.25f, 0.25f, 0.25f);
            go1.transform.localPosition = transform.TransformPoint(v3);
            //go1.transform.localEulerAngles = transform.TransformDirection(v3);
            //go1.transform.rotation = this.transform.rotation;
           // go1.AddComponent<CubeMakerOnEmptySpaces>();
        }
        sp.Stop();
        UnityEngine.Debug.Log(sp.ElapsedMilliseconds / 1000);

```

Now I want to change the rotation of each cube that each cube z should be pointing against the mesh direction (should be outside of the mesh). Maybe picture representation helpful here

Need to be like this:

# Answer
Are you sorting your edge list as suggested in the linked question?

If so, get the location of point `n+1`, subtract point `n-1` and you have a vector for your edge at point `n` (You'll need to handle either side of the wraparound).

Now all you need to do is decide which orientation is "in".

To reach a good conclusion, we need to know what assumptions we can make about your mesh topology and whether you need a 2D/3D direction for "out".

If the mesh is largely level, meaning the cube doesn't need to tilt in/out to account for hills just inside the edge (aka the cube's `+z` has no `y` component)...

The `+z` vector of the cube is either going to be the cross product of world `+y` and your edge, or the the exact inverse.

It should be fairly easy to distinguish between the two cases. Compare one option to the point `n` and whether the result is +/- 90 degrees will tell you which configuration you want.

Thinking of it another way... Start at point `n-1`, Look at `n+1` with "up" being `+y`. From there, it's all 90 degree rotations.

This provides undefined behaviour on truly vertical edges, and doesn't behave well when the edge of the mesh is a cliff or for a sheet of paper tipped slightly backwards (the sides would work perfectly but the cubes at the top and bottom would be have an `up` vector of `+y`)

If you need to solve in "real" 3D, we need some way to work out which verts to include in our calculation of the "in" vector.

How often do you need to do this? On level load? Every frame?

There's a brute force approach where we simply scan all verts for those in proximity to the point in question, then filter by some criteria and get an average.

It all depends on exactly what you need and what assumptions we can make about the mesh.
> 0 votes

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


# Question
Title: Why the transform.localPosition never equal to the begin position of the transform?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveScrollView : MonoBehaviour
{
    float seconds;
    Vector3 begin;
    Vector3 end;
    Vector3 difference;

    public static bool go = false;
    public static bool goBack = false;
    public static bool atOriginPos = false;

    void Start()
    {
        seconds = 0.5f;

        begin = transform.localPosition;
        end = new Vector3(0, -1, 0);
        difference = end - begin;
    }

    void Update()
    {
        if (go)
        {
            if (transform.localPosition.x < end.x)
            {
                var mx = transform.localPosition.x;
                transform.localPosition = new Vector3(mx += seconds * Time.unscaledTime, -1, 0);
                difference = end + transform.localPosition;
            }
        }

        if(goBack)
        {
            if (transform.localPosition.x > begin.x)
            {
                var mx = transform.localPosition.x;
                transform.localPosition = new Vector3(mx -= seconds * Time.unscaledTime, -1, 0);
                difference = end - transform.localPosition;
            }
        }

        if(transform.localPosition == begin && goBack)
        {
            atOriginPos = true;
        }
    }
}

```

At the Start the begin position is (-540.0, -1.0, 0.0) also the transform.localPosition is at the same position.

Then at this line 39 :

```
if (transform.localPosition.x > begin.x)

```

The value of the x of the transform.localPosition is 3.039021 and the x of the begin is -540 So it's getting inside and move the transform.

Then when the transform has finished moving I see on this line :

```
if (transform.localPosition.x > begin.x)

```

The transform.localPosition x value is -540.7267 and the x value of the begin is still -540 So now it will not get inside and will not move the transform anymore.

But two wrong things happened :

1. The transform stopped moving but it didn't move to it's original position only close to it.
2. Because it didn't move to it's exact original position then the localPosition x and the begin x are never equal so the this will never be true :

if(transform.localPosition == begin && goBack)

And the flag atOriginPos is never true.

I want the transform to move back to it's original position and then when it's reached the original position set the flag atOriginPos to true.

# Answer
You are moving your transforms at a speed that depends on the framerate:

```
transform.localPosition = new Vector3(mx += seconds * Time.unscaledTime, -1, 0);

```

That's good because it ensures that the movement speed is steady even if the framerate is inconsistent. However, it means that your transforms are not moving a fixed distance each frame.

Let's say that your movement speed is 60 units/second and the game is trying to render 60 fps per second. Ideally, you render one frame every 1/60th of a second (16ms) and the GameObject moves exactly `1` unit each frame. However, in reality the framerate is going to fluctuate at least a little bit. Maybe one frame takes 21ms to render, and the GameObject moves `1.3125` units that frame. Or the frame only takes 15ms to render and the GameObject moves `.9375` units that frame.

Since the movement we add to our position each frame is a floating point value, it's extremely unlikely that the GameObject is ever going to precisely end up at a specific position. For example, say we started at `x = 0` and want to end up at `x = 5`. We might see movement like this:

1. Move .9375 (total .9375)
2. Move 1.125 (total 2.0625)
3. Move 1 (total 3.0625)
4. Move 1.0625 (total 4.125)
5. Move .9375 (total 5.0625)

In 5 frames, we moved 5.0625 units and did not land exactly on `x = 5`. Worse, even if the framerate is 100% consistent, if our movement distance is not a whole number, we might still not exactly end up at a particular position due to floating-point precision error.

There are two solutions easy to this problem:

### 1. Use `Vector3.MoveTowards()`.

The MoveTowards() function moves towards a destination by a specific amount, and will never pass the destination.

```
float distanceToMove = speed * Time.unscaledTime;
//We will never move past the end point
transform.localPosition = Vector3.MoveTowards(transform.localPosition, end, distanceToMove);

```

### 2. Don't use an equality comparison for positions

Instead of writing `if (transform.localPosition == begin)`, you can do this:

```
float threshold = .1f; //adjust as needed for more precision
if (Vector3.Distance(transform.localPosition, end) < threshold) {
    atOriginPos = true;
}

```

Here, instead of checking if our position is *exactly* equal to some position, we check if it's *closer than a certain threshold*. This is much safer, but it is not perfect. If our object moved by more than `threshold` distance in one frame, it might go from one side of the target position to the other without ever being within `threshold` units.
> 1 votes

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


# Question
Title: How should I check if object is null or not?
```
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public float gap;

    private Transform slots;
    private string[] imagesToLoad;

    // Start is called before the first frame update
    void Start()
    {
        string imagesFolder = Path.Combine(Application.dataPath + "/Saved Screenshots");
        if (!Directory.Exists(imagesFolder))
        {
            Directory.CreateDirectory(imagesFolder);
        }

        imagesToLoad = Directory.GetFiles(imagesFolder, "*.png");

        slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        if (imagesToLoad.Length > 0 && slots != null)
        {
            for (int i = 0; i < imagesToLoad.Length; i++)
            {
                var go = Instantiate(saveSlotPrefab);
                go.transform.SetParent(slots);

                Texture2D thisTexture = new Texture2D(100, 100);
                string fileName = imagesToLoad[i];
                go.GetComponent<RawImageInfo>().FolderAndFileName = fileName;
                byte[] bytes = File.ReadAllBytes(fileName);
                thisTexture.LoadImage(bytes);
                thisTexture.name = fileName;
                go.GetComponent<RawImage>().texture = thisTexture;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
}

```

I'm checking in this line if slots is not null :

```
if (imagesToLoad.Length > 0 && slots != null)

```

The problem is that I'm getting exception null already on the line before :

```
slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

```

The reason is that the object with the tag "Slots Content" is disabled when the game start and I want it to be disabled when the game start but I also don't want to get this null exception. Then how should I make the null checking ?

I tried also :

```
if (GameObject.FindGameObjectWithTag("Slots Content").transform != null)
            slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        if (imagesToLoad.Length > 0 && slots != null)

```

But still getting the exception null on the check :

```
if (GameObject.FindGameObjectWithTag("Slots Content").transform != null)

```

# Answer
> 6 votes
```
slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

```

`FindGameObjectWithTag` can return `null` if it doesn't find such an object, then the `transform` reference will fail.

Just split this into two lines:

```
Transform theTransform;
slots = GameObject.FindGameObjectWithTag("Slots Content");
if(slots != null)
{
    theTransform = slots.transform;
}

```

There are other ramifications in your code now that `theTransform` might not have what you're looking for.

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


# Question
Title: How to make AI detect a target behind a wall, who is only partially exposed?
I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger.

So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed.

I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target?

# Answer
This isn't common in all shooter games, but some do go to this level of detail. In Splinter Cell games, for instance, AI can detect Sam's individual body parts.

When an AI is performing a detection check, we fire rays to 8 selected bone positions in Sam's animated skeleton (one per frame to cap the processing cost), and tally up how much of him is visible. (We also evaluate lighting per bone, so they only detect you if they can see enough of you in the light)

You don't need a collider on each bone to do this; you just need to do a raycast with a fixed length, or a point-to-point linecast. If you get no hits, that means no other object intercepts the line of sight, and the destination point is visible.

Doing it this way lets you control the sensitivity, by choosing which bones to test, and setting a threshold for how many exposed bones are needed to count as visible/shootable (which can vary with player stance, illumination, AI alertness level...). Maybe having your whole hand exposed up to the wrist, or whole arm out to the elbow should be a liability, but having just a finger exposed doesn't count. (This also lets you manage the cost of doing these checks)

Keep in mind that players' controls might be precise enough to keep their arms and legs tucked in if they're careful, but they probably don't have the fidelity to control placement of their toes and fingers, which are driven by animation. Nor does the typical gameplay view help them notice when those little bits might be sticking out. So penalizing the player for too small a misalignment might not make your game feel more realistic, but instead make it feel like the game is cheating and letting AI shoot through walls.

In some games, AI will even ignore the player's whole head when they're crouching behind cover - raycasting to the chest instead - so players can peek over the top without sudden detection. See more details in this Game Maker's Toolkit video
> 68 votes

# Answer
If you really want to detect *any* exposed part of the player, the extreme approach is to simply render the scene from the gun's perspective using replacement shaders, such as the player rendering as plain white while everything else renders black - any pixels which are white in the result show a potential target. You can even use multiple colour channels to make the AI aware of seeing the player behind glass (e.g. glass renders as red with a multiply shader, so white means visible and exposed, red means visible but not exposed, and black means not visible).

To introduce some amount of forgiveness you could only have the AI take a shot if a large enough area is detected (maybe a few tens of pixels depending on the render resolution). This can be accomplished with segmentation techniques back on the CPU, or with a blur+threshold if you have GPU cycles to spare.

This is pretty similar to the technique used to cast shadows from light sources, which is analogous to what you are trying to achieve. Note that (as with light source shadows) this doesn't scale well to hundreds of enemies, though you could have enemies take it in turns to "see", with a few being rendered each frame. Also if there is only one target (the player), you can use some smarts to restrict the area which is actually rendered to only cover the computed limits of the player's bounding box.

---

As pointed out already, this seems pretty cruel to the player, so make sure it's actually a fun mechanic in your game before committing to it!
> 23 votes

# Answer
I assume your current way of detecting visibility is checking a clear line to the centre of the bounding box?

If so, then one viable approach would be to keep doing this, but additionally choose a few random points belonging to the player model to check. This might even add a bit of realism to the experience: the AI will instantly detect the fully exposed player, but it may take from a second to notice the hand sticking out up to a minute to see the finger. After first hit, you'd probably want to remember the previously-random point, so that the AI keeps seeing the poor player.
> 3 votes

# Answer
Building on previous answers, the most common solutions are to **raycast multiple times**, although I believe your approach of querying for enemies that are near walls can get buggy over time (if you add cover that is not "a wall", i.e. a character standing near a car that simply occludes LoS but is not a proper cover)

---

Most games do a gradual checking **from cheapest to most expensive** (assuming your detection works with a view cone for simplicity):

* Spacial partition, AABB or sphere collider (filter which characters are in range)
* Visibility culling (filter which characters are within the view cone, removes characters in range but behind or on the sides)
* Raycasting to bones (filter which characters are visible)

---

Choosing the bones depends on the kind of game you're working on, what feel you want the players to have when playing and how the AI behaviour can help to enforce a certain playstyle.

* **Last of Us** casts a **single raycast to the hip when the character is standing** and switches to **raycast to the head when the character is crouching**. This works well with a carefully designed level where there are no gaps at waist height for the enemies to see your hip when you don't see them Check Figure 34.4
* **Splinter Cell** casts on 8 different bones and has a **minimum requirement of visible bones for detection** (eg. 3 out of 8). This brings out the ability to change the visibility threshold for certain areas (eg. if it's dark enemies need 5/8) or for enemy types (eg. snipers only need 1/8) Check Figure 28.1
* Like pointed out by @Dave, if you really want to detect/shoot on ANY visible little bit, **rendering it to a texture** is probably the best way to go although you'll have very unhappy players that get shot from "nowhere". It might work when if it supports the character's backstory and there is an "excuse" for it to be so accurate, if it's a super killing machine or a ruthless legendary sniper.
> 2 votes

---
Tags: unity, ai, line-of-sight
---


title: Help understanding movement script

text:
# Question
Title: Help understanding movement script
Can someone clearly explain how this script works and how I would be able to improve it? (It's a movement script)

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

public class move : MonoBehaviour
{
    public Rigidbody2D rg2d;
    public float movespeed;
    // Start is called before the first frame update
    void Start()
    {
        rg2d = GetComponent<Rigidbody2D>();
        movespeed = 10f;
    }

    // Update is called once per frame
    void Update()
    {
        float X = Input.GetAxisRaw("Horizontal");

        if (X != 0)
        {
            rg2d.velocity = new Vector2(movespeed * X, rg2d.velocity.y);

        }
    }
}

```

# Answer
I commented on every line explaining what it does. As for improving it all depends on what you want to do with this movement code and is a much broader questions.

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

public class move : MonoBehaviour
{
    public Rigidbody2D rg2d; // This creates a reference to a RigidBody2d type
    public float movespeed; // this is a variable that stores the movement speed
    // Start is called before the first frame update
    void Start()
    {
        rg2d = GetComponent<Rigidbody2D>();// this tries to get the RigidBody2D component that is on the same game object as the scipt
                                           // if no rigidbody is found it will return null
        movespeed = 10f;// this sets the movement speed variable to 10.
                        // NOTE that this will override any value you set in the inspector when you start your game
    }

    // Update is called once per frame
    void Update()
    {
        float X = Input.GetAxisRaw("Horizontal"); // this will store the RAW, meaning unsmoothed value, of the axis defined as Horizontal into the variable X
                                                  // if you do not plan on doing smooting yourself I suggest using Input.GetAxis

        if (X != 0) // checks if the value of X is different than 0 and if it is we proceed into the if body
        {
            rg2d.velocity = new Vector2(movespeed * X, rg2d.velocity.y); // this line creates a new Vector 2 where the X component is the value our input times the movement speed
                                                                         //and the Y component is the current Y velocity of the rigid body
                                                                         //it also sets this new Vector2 as the current velocity of the rigidbody

        }

    }
}

```
> 1 votes

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


title: ScollRect Jumps while Filling

text:
# Question
Title: ScollRect Jumps while Filling
I have a UI panel with a scollrect inside, which I fill dynamically. It can only be moved vertically.

When filling this scollrect, the content jumps up and down for one frame, creating a weird look. When I check for the `VerticalNormalizedPosition` of the scrollrect after each added GameObject, it always tells me, the position is 1. When I check for the position in an Update method, it sometimes gives me a small rounding error. Instead of 1 it's somewhere between 0.9999995 and 0.9999998. The height of the content holder is less trhan 2000 units, whereas the jumps seems to be more than 2000\*0.9999998.

I tried to set the VerticalNormalizedPosition of the scrollrect to 1 every frame which didn't help. It also didn't help setting it after every newly added GameObject. Locking vertical scrolling also didn' help.

Is this soley a rounding error and I can't do anything about it, or is there a way to stop this jump from happening?

Here you can see the jump happening in 0.05 speed

# Answer
> 0 votes
If I'm understanding your issue correctly, you might want to try changing the `scrollSensitivity` in the inspector to a smaller number, because according to the Unity Documentation found on ScrollRects here:

> \[This controls\] the **sensitivity** to scroll wheel and track pad events.

This should mean that if you change this to a smaller number, the ScrollRect's jumps should not be as large, due to decreased sensitivity.

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


# Question
Title: How to draw grass sprites without using gameobjects?
I am making a rimworld-like procedurally generated 2D game using Unity's tilemap system.

Just like tiles, I also have to procedurally generate grass and trees. Each grass instance should have logic inside that keeps track of it's growth progress and update the grass size appropriately.

The downside is, I have to have maps as big as 400x400. That could be THOUSANDS of grass instances and each of them having their own GameObject seems ridiculous and like the game would lag.

How can instantiate those grass sprites without creating new gameobjects for each one while still being able to control the growth and similar things?

(Come to think of it, the DOTS / ECS system in Unity would be perfect for this, however it is nowhere near ready and many things I want to do are just not supported.)

# Answer
Create a TileMap with 400x400 tiles for your grass tiles. Tiles on a TileMap aren't full-fledged gameObjects. They are very lightweight. A 400x400 tilemap is absolutely no problem.

Then create *one* gameObject. Let's call it `GrassManager` and put a script with the same name on it. That script internally has a `tile[400][400]` array and a reference to that TileMap. Those array entries contain `struct`s with all the data related to the grass growth of each tile. Like whether or not it has grass at all, its current growth progress, any tile properties which influence grass growth (moisture? temperature? fertility?) and when it was last updated.

Then Implement its Update method to go through all those tiles and update their growth status. When that Update-function notices that a grass tile has reached its next growth stage, then you update that tile of the tilemap. Note that you likely do not need to process all the grass tiles on every single update. It is likely completely sufficient for your use-case to do staggered updates where you only process a small chunk of all tiles in each Update-call.
> 4 votes

---
Tags: unity, c#, rendering, procedural-generation, terrain-rendering
---


# Question
Title: How do I make a part of my map off limit?
I'm looking for a common way to make zones in my 3D map "off limit"? The kind of thing you see in eg Hitman games where NPCs will get suspicious if you step into certain areas. Will need several areas like this, corridors, rooms etc.

Is it just to create invisible collider objects that set an `offLimits` bool to true, or is there a preferable way?

# Answer
> 1 votes
> Is it just to create invisible collider objects that set an offLimits bool to true?

It's even easier than that. You can just enable or disable the invisible wall colliders with `gameObject.SetActive(false);`. A Collider component on an inactive gameObject doesn't block anything.

But keep in mind that putting invisible walls in your game really breaks immersion. And when there is no way for the player to tell that an invisible wall was removed, they can really confuse the player about where they can and can't go. That makes them a last resort solution when you can not come up with a more plausible methods of restricting the player's freedom.

It's always better to find some diegetic obstacles which make sense in the context of your game world. Like a door being open or closed, a force-field being active or inactive, a drawbridge being down or up, an immovable and immortal NPC standing in the way or moving aside, and so on. But what method exactly is appropriate depends on the theme of your game.

Another alternative to hard invisible walls are "kill zones". When the player walks too far away from the playable area, you just kill them. An invincible enemy shows up and kills them in one hit, an invisible sniper shoots them, the police shows up and arrest them for no reason, the god of the game world smites them for abandoning their holy quest... whatever makes at least a bit of sense in the context of your game world.

---
Tags: unity, 3d
---


# Question
Title: How can I jump down from a platform in Unity?
How can I jump down from a platform in Unity?

I use two 2D colliders: one is my character, another one is platform. These colliders allow my character to stand on platform. Now whenever a characters ducks I show a button, when it is clicked I want my character to go through platform down. How can I achieve this?

I researched a few options and none of them worked for me. Let me explain them.

**1** I can make the character collider `isTrigger = true;`. There is a serious problem with that option, because character would for a moment ignore all collissions. So, if for example, previously he would loose health due to bullet being hit into him, now the bullet will just go through him. Of course I can duplicate the code from the `OnColliderEnter2D` to the `OnTriggerEnter2D`. But it is a mess, so I feel that it would produce a technical debt. Hence, I want to avoid it.

**2** I can make the platform collider `isTrigger = true;`. The problem with this approach is that now anyone standing on the platform would fall from it. Not only the character who clicked the button to jump through the platform down.

**3** I can disable the collision of the colliders layers. Here the issue is that I feel it is a wrong way to treat layers. They are not intended to be used like that. My feelings can be easily proven by an example. Let us suppose we have two enemies with the same layer standing on the same platform. One of the enemies wants to go down, so I disable the layer collision. And as a result two of the enemies go down. Yeah, I actually want a generic solution for the down jump. Such a solution which would be applicable not only as if it is the last feature I add into my game. I want to be able to empower enemies later on to do the same things as a character does.

So, I basically need something which would take the character collider and allow it to go down through the platform collider once.

# Answer
The @DMGregory's comment is what I was looking for.

I just take the character colliders and run for each one of them the call:

```
foreach(var characterPartCollider in characterPartsColliders)
{
    Physics2D.IgnoreCollision(groundCollider, characterPartCollider);
}

```

This makes the character fall down through a platform. Then when I detect a collision with another platform I run the following piece of code to enable the collision with the previous platform back:

```
foreach(var characterPartCollider in characterPartsColliders)
{
    Physics2D.IgnoreCollision(groundCollider, characterPartCollider, false);
}

```

Previously I confused the solution with the layer collision disabling. This solution is better, because it is more fine frained - with the code above we affect only what we intend to affect - that is the relationship between the character collider and a platform collider and absolutely nothing else.
> 0 votes

---
Tags: unity, 2d, collision-detection, collider, jumping
---


# Question
Title: How do I fix this "Accessed None trying to read property Save Game" error?
I have create this blueprint, with a Check for an existing Save-Game and load it in case of true. Else, create a new save game object. While Z is pressed, create a new Save Game, getting the Player Position.

The problem is that when I try to start the game, I have two errors:

How can I solve those problems? This is my blueprint:

Thanks.

# Answer
> 0 votes
It seems like your problem is very simple - in the beginning, you haven't connected return value of "does save game exist" node to the branch. Fix that and see if it works :)

---
Tags: unreal-4, blueprints
---


title: Where can/should I learn C# or Unity

text:
# Question
Title: Where can/should I learn C# or Unity
I’ve recently got interested in getting into game development due to having too much time (I’m in high school). I’ve been thinking of getting into Unity specifically but I’m not sure where to start. Should I just mess around with Unity and Visual studio while slowly learning or should I learn C# first?

# Answer
> -1 votes
I don't think this question fits the community but I'm going to answer my two cents anyways.

If you have no previous programming experience you should learn to code first. Learn the basics of OOP( object oriented programing) and the syntax specifics of C#. As of where you can do that: There is no best place to learn, it highly depends on how you learn stuff etc. There are tons of recourse on the net. You say you are in high school. As far as I know most schools have programming classes. Maybe ask a teacher or try to join a club?

Game development might seem easy at first but it can get very complex very quickly. After getting the basics of programing first I suggest that you start with very simple games and build up from there. Generally starting building your dream game as your first game will end in disaster. My proffered progression that I always recommend is Pong -\> Tetris -\> Pacman.

---
Tags: c#
---


# Question
Title: How can I create a DLC for Steam using Unity?
I have uploaded a game on Steam. I know steam deals the DLC as separate depots; I have also watched and read the documentation on steam documentation page.

The problem is how will I deal the DLC in my game (the coding part)? Is depot a full game and there is download option in the game? Please guide me about it as I am new in steam game development. What would be the global architecture of both my game and the DLC?

# Answer
### Short answer: Use AssetBundle plus authoring tools like Asset Bundle Browser (which simplify creating asset bundles)

Here is the longer answer: One could use **AssetBundle** or the new **Addressable** system. But here is the catch: the newer Addressable doesn't mean it's better. Let's see the use case.

### Steam DLC

As OP has noted, steam DLC works by either just adding a new depot into user download, or no additional file download at all but use it the DLC for a **license check**.

* **License check (without file download)**: With a simple IF check with Steam API `SteamApps.BIsDlcInstalled( XX )` to see if current logged in user has purchased DLC XX? This could be used in scenario such as:

+ Use Case 1: An exclusive skin for a tank multiplayer game. You would have to include this skin data with the game for all players, most likely with base game download, so it renders the DLC owned by other people correctly. The DLC just enables the owner to wear it.
    + Use Case 2: Or maybe an offline game, that unlock certain item, functionality, maps, which already exist in game data/code. (**A bit side topic**: some player might consider this a bad practice since they know that content already there in their HDD yet they must pay an extra to unlock it, well, depends on your choice, no one stop you as a developer from doing it though)
    + You can find sample code easily by searching the term `SteamApps.BIsDlcInstalled`, like this one I found: http://www.mwmdragon.com/2019/03/31/prep-for-a-steam-release/
* **With file download**: This is suitable for maps, extra mission pack, etc. And this answer will cover more on this specific type of DLC. **More on down below!**

+ Practically, even the game sees the extra file downloaded from DLC depots, you should still check for `SteamApps.BIsDlcInstalled( XX )` anyway, else player could just copy files from elsewhere and paste in the game folder to enable the DLC. which is probably weird.
    + Again, this wont safe guard against real hack or pirate, but we just make sure that we do thing in proper way :)

### Let's look at Addressable first

This is more suitable for a mobile game which updates/distributes content regularly. It works by maintaining/downloading a **catalog file**, which serves as an index file to other asset bundles. Update and download them smartly by comparing local version and dependencies.

But this is not suitable to our **Steam DLC** case at all. Let's say you want to sell a **new voice pack**. For the addressable approach you would need a way to update the **catalog file** (changing/updating the main app, or host it on our custom server) which **defeats all purpose for traditional DLC**. Also Steam already handles the download for us. This simplifies things a lot, because the game only has to check for local files.

### Making a DLC asset bundle

I used **Asset Bundle Browser** for this. Despite its name, it also helps with creating asset bundles by simple drag and drop. I wont get into details, because the tool is very easy to use. It is far easier than dealing with Addressable.

The final result will be an asset bundle file sitting in `ProjectFolder/AssetBundles` beside `ProjectFolder/Assets`. Which is good, because we are making DLC. We dont want to include them with build from start, nor in StreamingAssets.

The file **has no extension** by default. Asset bundles do not require extensions, but you could append them if you like. The `.manifest` file is for editor side reporting. Ignore it when copying to production.

### Enumerating extra files

This example just uses file IO to iterate files in a specific location, and then uses the `AssetBundle` API to load and peek them. It is now up to you how to use or manage the life cycle of these asset bundles. (unload them to release memory)

```
using System.IO;
using UnityEngine;

public class DlcTest : MonoBehaviour
{
    void Start( )
    {
        // Application.dataPath resolved to
        // - Editor: "ProjectPath/Assets"
        // - Build: "GameBuild/Game_Data" (note that GameBuild/Game.exe would be game executable)
        // I would like to position my DLC in
        // - Editor: "ProjectPath/AssetBundles/PlatformName/"
        // - Build: "GameBuild/AssetBundles/PlatformName/"
        // Of course you could change "AssetBundles" path to something suitable
        string extraPath = Path.Combine( Application.dataPath, "../", "AssetBundles", _ConvertPlatformToBuildTargetName( Application.platform ) );
        string voicePackPath = Path.Combine( extraPath, "voice" );

        // For example this would be
        // - Editor: "ProjectPath/AssetBundles/StandaloneWindows64/voice"
        voicePackPath = Path.GetFullPath( voicePackPath );
        Debug.Log( $"Get voice pack at {voicePackPath}" );

        // In my workflow, I build asset bundle without file extension, so I search all file
        foreach( string file in Directory.EnumerateFiles( voicePackPath ) )
        {
            if( Path.HasExtension( file ) ) continue; // Ignore something else, could be ".manifest" files.

            // For example this would be
            // - Editor: "ProjectPath/AssetBundles/StandaloneWindows64/voice/pack1" (file without extension)
            AssetBundle ab = AssetBundle.LoadFromFile( file );

            // Find ".yaml" info file for this voice pack
            // This would be my own stuff, you replace this with your own stuff
            TextAsset[] allText = ab.LoadAllAssets<TextAsset>( );
            foreach( TextAsset t in allText )
                Debug.Log( $"Found text asset, {t.name}" );

            WaveBankData[] allWb = ab.LoadAllAssets<WaveBankData>( ); // This is my ScriptableObject
            foreach( WaveBankData wb in allWb )
                Debug.Log( $"Found wavebank, {wb.name}" );

            // Normally you would let AssetBundle live throughout its usage,
            // Probably managed via some manager.
            // I will call this just for example to release memory.
            ab.Unload( true );
        }
    }

    string _ConvertPlatformToBuildTargetName( RuntimePlatform p )
    {
        // Depends on how you name your output platform for asset bundles
        switch( p )
        {
            case RuntimePlatform.WindowsEditor:
            case RuntimePlatform.WindowsPlayer:
                return "StandaloneWindows64";
        }

        return "Unknown";
    }

}

```
> 6 votes

---
Tags: unity, steam, steamworks
---


# Question
Title: Do you need to pay just to put your game as a closed beta on steam?
I'm currently working on my game, and we are planning on releasing a closed beta pretty soon. I would like to use Steam to make it, as it has a key generator to give people access, but I can't figure out or find out anywhere if you need to pay for the Steamworks partner, just to make a closed beta.

# Answer
Yes. It is a non-refundable\* $100 cost per application for distributing via steam.

\*When your product reaches $1000.00 revenue they pay it back to you.

Further details: https://partner.steamgames.com/doc/gettingstarted/appfee
> 2 votes

# Answer
### Making Steamworks account

First, you will need Steamworks partner account, which created from normal steam ID.

* A regular steam ID, the one that you buy/play games as normal user is fine.
* Document for tax review for setting up Steamworks partner account.
    + Registering as individual, they will ask for **personal identification**. A scan of official document or national ID card will do (non-US). Note that here you need to enter real name, you will be able to put another developer name or branding to your game, like **Yiddyyadda Games Interactive** later when setting up store page.
    + If registering as a company, they will ask for more company related documents.

After above process is done and after tax review is done (takes few days), if I remembered correctly, they will immediately ask for first app submission fee (100$) upfront, which will be credited to your account.

You will be able to create 1 app ID from the this initial credit. (More on this fee is already answered by Casey's)

### After you have working Steamworks account and App ID

There are options you can continue from this point

* For closed beta test, you will need to setup depot and upload your first build. (see Steamworks documents) This process totally happen on developer side and does not require any review/approval from Steam personnel.
    + To share to other, **if that person is also a developer in the team**, you could **add him to your team as developer in your Steamworks account**. That person will auto grant right to that app ID (and appear in his library) immediately.
    + To share to **outsider** beta tester, generate **"beta" keys** from app dashboard. Send this key to your friend and let him add it as if it is a retail key. (You can revoke this key later if you want that person to be able to buy your game when it is released) Issuing the key, although monitored by Steam personnel, if key is small enough, it will be usually fast, less in an hour.
* Setup a store front for app to really appear in public Steam market as **"Coming soon"** for public presence and marketing (and game will be able to start accepting wishlist). This one requires review/approval from Steam personnel.

The point above is I want to show that **2 process are totally separated**.

* You **don't need** a game build to open a "Coming soon" store page.
* You **don't need** a store page to do closed beta testing.

Valve also has their own tutorial in YouTube channel.
> 1 votes

---
Tags: steam, steamworks
---


# Question
Title: SteamWorks.Net for unity and inviting a friend to a multiplayer game
I'm trying to send an invitation to a steam friend and have it that when he accepts I create a PUN 2 room for both players and they can start their match. So far I've done this :

```
 protected Steamworks.Callback<GameRichPresenceJoinRequested_t> m_GameRichPresenceJoinRequested;

private void OnEnable()
{
    m_GameRichPresenceJoinRequested = Callback<GameRichPresenceJoinRequested_t>.Create(OnGameRichPresenceJoinRequested);
}

public void InviteFriend()
{

    SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "");
}

private void OnGameRichPresenceJoinRequested(GameRichPresenceJoinRequested_t pCallback)
{
     Debug.Log(pCallback.m_rgchConnect);
    Debug.Log("<color=green>Friend accepted the invite</color> ");
}

```

The invite is being sent to the correct friend and when he accepts it launches the game but I get no callback from that and thus have no way to place them in a room. What am I doing wrong ?

# Answer
### There are 2 ways receiver can receive invite

One is from **OnGameRichPresenceJoinRequested** as you have posted.

Take a note that `OnGameRichPresenceJoinRequested` will only called on receiver side if **he is already playing the game**. That is, app is already running, and someone happen to send him an invite and he accept it while exe is running

Two is from **SteamApps.GetLaunchCommandLine**

On the other hand **if he is not playing that game** at the moment and request came through friend chat. If he accepts invite from there, parameter will instead sent via **Steam's launch command**. (Similar to exe launch arguments, but this one is from Steam, for security reason)

For Steamworks.NET, uses `SteamApps.GetLaunchCommandLine`. Usually it comes by this format `+connect_lobby LOBBY_ID`. So parse it accordingly and handle it the same way as you get with `OnGameRichPresenceJoinRequested`.

See https://partner.steamgames.com/doc/api/ISteamMatchmaking and search for keyword `connect_lobby`

For example, I call this at my title screen.

```
    private void _AcquireLaunchCommandLine( )
    {
        string launchCmd;
        if( SteamApps.GetLaunchCommandLine( out launchCmd, 260 ) > 0 )
            _ParseCommandLine( launchCmd );
        Debug.Log( $"Got Steam _AcquireLaunchCommandLine '{launchCmd}'" );
    }

```
> 2 votes

# Answer
Under the official steam docs for the GameRichPresenceJoinRequested\_t function

> NOTE: This callback is made when joining a game. If the user is attempting to join a lobby, then the callback GameLobbyJoinRequested\_t will be made.

So perhaps the user is attempting to join a lobby instead, and the wrong callback was provided?

Alternatively:

Also, in your code you do:

```
public void InviteFriend()
{

    SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "");
}

```

without assigning it to a variable to see what's happening, but according to the docs for InviteUserToGame (scroll about halfway down the page):

> Returns: bool Triggers a GameRichPresenceJoinRequested\_t callback. true if the invite was successfully sent. false under the following conditions:
>
> ```
> The Steam ID provided to steamIDFriend was invalid.
> The Steam ID provided to steamIDFriend is not a friend or does not share the same Steam Group as the current user.
> The value provided to pchConnectString was too long.
>
> ```

So first of all, if you store it to a bool variable, like so:

```
public void InviteFriend()
{

    bool wasItSent = SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "");

    Debug.Log("Was it sent? " + wasItSent);
}

```

you will probably find that that bool returns false, and if so then probably you have to look into those 3 conditions that happen when it is false. It seems now you are assuming that it is sent, from your last function which debugs "sent successfully", but never actually checking if the send failed
> 0 votes

---
Tags: unity, steamworks
---


# Question
Title: What makes a computer opponent feel alive?
Are there any recommended blogs or whitepapers that talk about making the AI in an RPG game feel more real? (Specifically in turn based combat.)

I know something must be out there, but I am only finding papers that talk about algorithms behind the AI. I am looking more along the lines of "this is what makes a computer opponent feel alive". Taking risks, going easy, retreating, etc....

---

So many awesome answers, and I wish I could accept several of them. Thanks everyone!

# Answer
Mistakes. Nothing is worse than an AI opponent who can headshot you from fifteen miles away, or always picks the perfect winning strategy. It breaks the immersion and makes it apparent that you're playing a routine. Mistakes can make the AI seem more human.

Many FPS games force the AI to miss with its first few shots, warning the player that the AI is there, before going for the kill.

Strategy games could sometimes select a suboptimial strategy, or when evaluating threats may purposefully ignore some proportion of them.

A racing game I worked on calculated when the player was nearby, and then rolled a dice to make the AI cars in front of him understeer through the corner or blow a tyre. It was praised for its realistic AI.

However creating imperfect AI is still something of a challenge. You have to make convincing mistakes, at a convincing rate, rather than perform perfect action after perfect action until making a ridiculous blunder. That can be even worse than playing just a perfect AI. For instance, the programmer working on the racing AI above spent a lot of time on modelling how a car understeers, and what inputs the AI needs to make to cause a convincing understeer. As always, playtesting is vital.

Here's a good article on what goes into producing these kind of mistakes: http://www.gamasutra.com/view/feature/3947/intelligent\_mistakes\_how\_to\_.php
> 114 votes

# Answer
Others have talked about AI, logic, planning, and the importance of making mistakes. And all of these are good and useful in the development of AI.

But the question was about what makes a computer opponent feel alive, and that isn't achievable through AI. It just isn't. Players don't judge a character in a game based upon their strategic level choices; they judge it based on much smaller things.

To make a computer opponent feel alive, what you need is a comprehensive set of high-quality animations and sounds (vocals, especially) for the opponent. The player can't see the AI. He can't hear it, he can't experience it, he can't know what the opponent is thinking. The appearance of "this character is a living entity" is presented to the player entirely through the animations playing on the character, and the sounds being produced by the character (which again, will mostly be vocals).

It's important for the character to react to stimuli around him; to look at things nearby, to touch objects nearby (when appropriate to do so), to appear startled when surprised, and to show other emotions when appropriate.

When talking about these things, it's important to minimise repeats. If the character uses the same "attack" animation every time he attacks, he's never going to feel alive. If he plays a single looping "idle" animation when he's not doing anything else, he's not going to feel alive. If he says the same voice quip twice (especially consecutively), that breaks the illusion that the character is alive.

And that's pretty much it. If the opponent that you're trying to make seem alive is physically present in your game, then your success at making them seem alive will mostly be determined by the graphics and sound shown to the player.

If the opponent that you're trying to make seem "alive" isn't actually present in the game, as is the case in Chess and StarCraft, then feel free to disregard this reply; your best bet is to follow the AI-focused replies.
> 46 votes

# Answer
Here's a list of some simple concepts that can make your opponent more vivid:

1. Intent
Give the player some way of divining the 'intent' of the AI. This could be as simple as having them yell out "Quantity over Quality" before attempting an accurate headshot attack, "Flank him" while attempting to get behind you, or "Take the leader, nothing else matters" before attacking the protagonist. You could also get more complex, for example, have them give some sign language to their teammates, then change the behaviour of those teammates.
2. Desperation
As the opponent gets closer to death, you can give them a sense of desperation. Change their tactics at certain health milestones. Make their later stages more panicky, with greater risk taking on their part (going for the hail mary, rather than slow chipping). Visually communicate this as well (more exaggerated animations, pulsing veins, etc).
3. Go out with a Bang.
Give them a death that makes the fight with them something worth repeating. Grunts keel over animatedly. Bosses soliloquize. If it's a proud character, make them refuse to give you the kill, and deal the last of their damage to themselves. You get the drift.
> 33 votes

# Answer
I do recommend this google IO talk it is about google doodle pacman. At cca 18:00 they start to speak about personality of ghosts in pacman. It is really stuning how simply you can put personalities into the simple path finding.

Google I/O 2011: The Secrets of Google Pac-Man: A Game Show

Whole video is worth watching. I really recommend it.
> 23 votes

# Answer
I don't know about any such blogs, but since a tactical turn-based RPGs is my second favorite genre right after roguelikes, I'll write you a blog post. From my experience, it was not a difficulty of tactical AI in a RPG or RTS which often put me off, but its opposite: AI's complete short-sightedness and absence of team decisions. Human will never play like this.

Back then, when I still viewed JRPGs as a pinnacle of game design, I once tried to make a "typical japanese TRPG" with heavy focus on tactical turn-based combat like Final Fantasy Tactics. As always, it became just a tech demo for pathfinding and AI, so I'll share my thoughts on the subject.

Most of these TRPGs don't bother with AI much. Player's fun out there comes not from a complex tactical or strategical challenge, but from general farming and abusing AI in a funny way. So it doesn't matter much that their AIs do things no human would ever do. Usually it's sufficient to have a stupid AI and balance it out with game design in way that it never needs to see more than one move in advance and only use best short-term moves. Of course it never feels real, but who cares? This just feels wrong, I want to believe it is possible to create fun based on a battling complex AI actions instead of farming and steamrolling. Unnecessary maybe, and time-consuming as well, but possible.

Remembering original Final Fantasy Tactics and its hardcore mod FFT 1.3, I set the following goals for human-like and fun to play AI:

* AI must create a challenge, but a fun challenge and not a "human full search" challenge. This fun challenge should be often expected by player via overall context of a current mission. Usually thats where scripts come into play creating a one trick pony AI.
* AI should be clever, but not deep Minimax clever. Different types of AI should have different flaws, just like different human personalities would. It's a rare thing to encounter in games, Advance Wars had scripted personalities for generals, for example, but units can have them too.
* AI must avoid looking dumb when it is not intended. Obscene stupidity completely ruins any illusion of intelligence, always winning strategies do so as well. And loopholes created by careless scripting, those are the worst.

I thought that I will tackle #1 with emergent behaviours, #2 with different personalities and human-like "semi-random" strategy choice, #3 with keeping hard-coding to a minimum and a careful testing.

So what are these behaviours I'm what talking about, is it a scripted sequence of abilities to use? A top ability from a weighted list? Nope, what I had in mind was a combination of a *desired intelligence*, *personality type* and a *role* derived from currently available abilities and weapons. You can describe this combination as a "stupid berserking damage dealer" or "smart defensive healer". So AI specializations, like classes or professions, e.g. an Archer AI which uses bow to shoot arrows with some set of predefined generic archer ability combos like Take Aim or Arrow Shower, become logically emergent instead of hard-coded.

Basically, it is important to detect and operate on these roles: damage dealer, damage soaker, disabler, skirmisher, healer, buffer/debuffer, area of effect'er; usually, one character will perform at least two of these roles.

To make a tactical fun out of this we want for behaviours to handle several cases solidly:

*Simplest case.* A lot of weak goblins ambush our heroes. Perceived threat is obvious, goblins will try to overwhelm player with each goblin having a stupid berserk personality with some primitive melee abilities, perceived weakness is also obvious, like baiting goblins to a single armored and fire-resistant character, then casting a series of fire-based AoE spells in that general direction. Find a damage soaker, find an AoE'er, specialize the damage soaker for AoE'er damage type, send the damage soaker to the goblin mass, cast a damaging AoE spell when goblins group around.

*Usual case to test out simple team interactions.* Player encounters a knight, an archer, a mage and a cleric. Perceived threat is now more complex, various interactions become available. YOu can already see possible roles and its combinations. Cleric will buff and heal, mage will dish out complex but high-damaging magic things, knight will either charge someone or defend a mage, archer will help knight by sniping those who try to run away from him or making his defence strategy more comple, this will depend on knight's choice. Personalities for enemies may be decided randomly turning the same encounter into unique experience. Player will have to decide what is the best strategy with units he currently has, and if AI would try to do the same on the other side of the screen, it would be interesting.

*Complex case to test out team interactions and strategic planning.* There is a battle where you confront a gang of four assasins (clever careful damage dealer+skirmisher). Few in numbers, with menacing appearance, their perceived threat lies in skillful and deadly attack, and perceived weakness is that it's easy to reduce overall strength with just a single assasin killed. So naturally they're clever, they use abilities that work well with each other and can focus fire player's most dangerous characters; seriously injured ones retreat, heal and buff themselves to rejoin the battle. Obviously, player will try to nuke one of them first, and assasins will have to soft-counter this easy strategy, so it will be a less dominant.

*Hard case for lots of strategy.* There are several squads of enemies with each squad leader deciding best local tactical moves, and then a best global strategic decision is selected to benefit all squads.

*Impossible case.* Add a general to decide a strategy, and have squad leaders implement it to the best of the squads abilities.

It's a lot of letters already, so long story short, implementation was a mess and I never got past a "hard case", but even then this approach to a fun tactics felt doable. I started with FSMs but had to abandon that approach quickly, it became an entangled mess of states and transitions impossible to debug. After a while I settled with semi-autonomous ability perception based characters as in "sense-think-act" paradigm with behaviour trees for possible individual actions, a global strategy affecting possible team actions based on possible individual actions, also a bastardized version of something like N-Gram statistical prediction was tossed in.

**How has this worked out?** Surprisingly well, AI even read my mind several times, but I grew tired and abandoned it since there were more than enough convincing flaws:

* The biggest flaw was that sometimes the entire AI operation was just weird and chaotic, even though I punished quick change of strategies. Probably either strategy logic or wrong personalities were a culprit, but I never found out. Yep, code architecture was horrible.
* Fine-tuning desired scenario by a careful selection of available abilities and personalities is tedious.
* Ability tagging for roles should be done very careful, or some wacky combos would appear.
* Same for personality tagging, but instead of wacky combos you would see careful casters buffing for frontal assault.
* It was hard to decide on a "cleverness" level for a given ability.
* Some seemingly stupid decions which were required for a level-design like "hold this castle wall no matter what" had to be implemented in a hackish way.
* Planning for units to perform a time-based attack was also a hack.

I guess my approach was mediocre at best, if not outright bad, and AI was buggy and pain in the ass to develop further, but even then I had some really fun time playing against it, almost as if playing with a distracted kid, which is still better than Tactics Ogre :)
> 14 votes

# Answer
Don't always make it respond to your action X with action Y. As you evaluate each potential action add a random fudge factor so the AI doesn't always pick the same option but it chooses something reasonable.

Evaluate if an attack has a reasonable chance of succeeding or at least doing meaningful damage. Too many games simply have scripted attack routes that a human can learn and use to ambush the AI over and over.
> 5 votes

# Answer
One thing I see suggested a lot is to have the AI communicate its "thoughts" to the player in some way. This is often done in first-person shooters by having the enemies (unrealistically) shout out their plans to the player (i.e. "flank him!", "he's over there!", etc.).

At the end of the day, players know they're playing against an AI, so anything smart that the AI does without first informing the player can just be dismissed as cheating.
> 3 votes

# Answer
When talking about game NPCs **most people associate liveness with intelligence**, but **emotion would probably be a much better indicator**.

A hostage NPC in a bank robbery might just be sitting on the floor not doing anything "intelligent" but **trembling, crying, holding a picture of family would bring an otherwise dull NPC to life**.

The same thing is true for enemy NPCs. They would get **enraged or fearful** if you keep headshotting his pals. If you're sneaking around you could hear some rookies that are **hesitant in going into combat**. You could overhear their leader doing an **inspiring speech to get the morale up**.

Take a look at the **Heider-Simmel Illusion** where a psychologist shows that **people have a tendency to see human-like behaviour everywhere**, even in super abstract shapes. The video has no realistic animations, audio or models, but it has emotion.
> 2 votes

# Answer
Often, we think of "how do we create A.I.?"

That is skipping the big question, "What IS A.I. ?"

This talk from TED.com that I watched some years ago, shared a very inspiring approach to the definition of Artificial Intelligent.

If you want your players to feel that the enemies are "intelligent" then this will provide a high-level answer, and essentially a whole new way of thinking about A.I., which is the "ability to predict"

http://www.ted.com/talks/jeff\_hawkins\_on\_how\_brain\_science\_will\_change\_computing.html
> 1 votes

# Answer
To me, "feeling alive" means that the character act as you would think it would in real life.

People in real life have needs, motivations, fears, flaws. They talk, they react with each other if it is a group, they flee because they care for their own life.

If they are military or trained, they have tactics.

So maybe you should check in the field of human behavior, so in human sciences, not in computer sciences.
> 1 votes

---
Tags: game-design, ai, game-mechanics
---


# Question
Title: Why aren't the changes to the transform being applied?
I don't understand why this doesn't work. The code only acts when I press *"Horizontal"* buttons.

Here's the code:

```
using UnityEngine;
using Flycer.Helpers;

namespace Flycer.Controllers
{
    public class MovementNew : BaseController
    {
        #region ========== Variables ========

        [SerializeField] [Tooltip("Forward moving speed")] [Range(0, 1f)] float _forSpeed = 0.5f;
        [SerializeField] [Tooltip("Slide speed")] private float speedSlide = 10;
        [SerializeField] [Tooltip("Max slide distance")] private float maxSlide = 4;

        private Vector3 _curPos;
        float slide = 0;
        int i = 1;

        #endregion ========== Variables ========

        #region ========== Unity-time ========

        private void Start()
        {
            base.On();
            _curPos = transform.position;
        }

        private void Update()
        {
            if (!Enabled)
                return;

            if (Input.GetButton(Controls.Horizontal.ToString()))
                Moving();
        }

        private void FixedUpdate()
        {
            _curPos += new Vector3(0, 0, _forSpeed);
        }

        #endregion ========== Unity-time ========

        #region ========== Methods ========

        void Moving()
        {
            slide = Input.GetAxis("Horizontal") * speedSlide;

            _curPos.x += slide * Time.deltaTime;

            _curPos.x = Mathf.Clamp(_curPos.x, -maxSlide, maxSlide);

            transform.position = _curPos;
        }

        #endregion ========== Methods ========
    }
}

```

It doesn't move in any condition whether it has a RigidBody or not.

# Answer
Your fixed update is only adding to the z-axis vector without ever applying it to the transform. Your movement function is taking the same vector and handles the x-axis part. All changes over time to z-axis are applied then as well. But if you never call movement - movement only gets called when you press the horizontal button), it just accumulates on z-axis without movement.

To fix it, just add the z-axis changes right away in your fixed update. This way they are independent from your horizontal movement.

```
private void FixedUpdate() {
    _curPos += new Vector3(0, 0, _forSpeed);
    transform.position = _curPos;
}

```
> 3 votes

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