# Question
Title: Rotating character for 2.5D platformer in Unity
I'm currently making a prototype for a college project in Unity. The game is a 2.5D platformer, though I've incorporated a script for the camera from a 2D platformer so the camera moves ahead of the player. Unfortunately, because my character only faces left and right and doesn't rotate, the camera doesn't move ahead to the left, which will make it difficult for the player to see ahead if they go back to the left. I'm not sure what or how I would tackle the issue in a script. These are the camera and player controller scripts I have at the moment:

**CameraController:**

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

public class CameraController : MonoBehaviour
{
    [SerializeField] GameObject player = null;
    [SerializeField] [Range(0.1f, 3f)] float followAhead = 2f;
    [SerializeField] [Range(0.1f, 3f)] float smoothing = 1f;

    const float m_minY = 2f;
    Vector3 targetPosition;
    Vector3 cameraOffset;

    void Start()
    {
        cameraOffset = transform.position - player.transform.position;
    }

    private void Update()
    {
        targetPosition = (player.transform.position + (player.transform.forward * followAhead)) + cameraOffset;
        targetPosition.y = Mathf.Min(targetPosition.y, m_minY);
        transform.position = Vector3.Lerp(transform.position, targetPosition, smoothing * Time.deltaTime);
    }
}

```

**PlayerController:**

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

public class PlayerController : MonoBehaviour
{
    public Animator anim;
    public float moveSpeed;
    public float jumpForce;
    public bool jumped;
    public float gravityScale;
    public float knockBackForce;
    public float knockBackTime;
    public float invincibilityLength;

    private float jumpDelay;
    private Vector3 moveDirection;
    private float knockBackCounter;
    private float invincibilityCounter;
    private CharacterController controller;

    void Start()
    {
        Cursor.visible = false;
        controller = GetComponent<CharacterController>();
        /*jumped = false;
        if(jumpDelay <= 0)
        {
            jumpDelay = 5;
        }*/
    }

    void Update()
    {
        if (knockBackCounter <= 0)
        {
            float moveHorizontal = Input.GetAxis("Horizontal");
            moveDirection = new Vector3(moveHorizontal * moveSpeed, moveDirection.y);

            if (moveHorizontal > 0)
            {
                transform.eulerAngles = new Vector3(0, 90);
            }
            else if (moveHorizontal < 0)
            {
                transform.eulerAngles = new Vector3(0, -100);
            }

            if (controller.isGrounded)
            {
                moveDirection.y = -1f;
                if (Input.GetKey(KeyCode.KeypadPlus))
                {
                    moveDirection.y = jumpForce;
                    jumped = true;
                    //StartCoroutine(SpamBlockco());
                }
                else if(!Input.GetKey(KeyCode.KeypadPlus))
                {
                    jumped = false;
                }
            }
        }
        else
        {
            knockBackCounter -= Time.deltaTime;
        }

        moveDirection.y = moveDirection.y + (Physics.gravity.y * gravityScale * Time.deltaTime);
        controller.Move(moveDirection * Time.deltaTime);

        anim.SetBool("isGrounded", controller.isGrounded);
        anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));

    }

    public void Knockback(Vector3 direction)
    {
        knockBackCounter = knockBackTime;

        moveDirection = direction * knockBackForce;
        moveDirection.y = knockBackForce;
    }

    /*public IEnumerator SpamBlockco()
    {
        if (moveDirection.y == jumpForce)
        {
            yield return new WaitForSeconds(jumpDelay);
        }
        yield return null;
        jumped = false;
    }*/
}

```

There are two ways I'd like for it to work - either when the player presses left/right, the character instantly rotates in the desired direction and move forwards, or the player presses left/right, the character turns, and then the player has to press left/right for the character to move.

# Answer
> 0 votes
Add something like this to your player script:

```
public Vector3 GetTravelDirection() {
    return moveDirection.normalized;
}

```

Then use that instead of the `player.transform.forward` in your camera script:

```
smoothedForward = Vector3.MoveTowards(
                     smoothedForward,
                     playerController.GetTravelDirection(),
                     2f * Time.deltaTime);

targetPosition = (player.transform.position + (smoothedForward * followAhead)) + cameraOffset;

```

Here I'm assuming you've created appropriate member variables for `smoothedForward` and `playerController`.

---
Tags: unity, c#, platformer, 2.5d
---


title: OnCollisionEnter calls rapidly

text:
# Question
Title: OnCollisionEnter calls rapidly
```
bool tntFall = true;

void Awake()
{
    tntFallTime = Time.deltaTime / 0.05f;
}

void OnCollisionEnter(Collision coll)
{
    if (CurrentScene != "ColorGame" && CurrentScene != "PaintingGame" && coll.gameObject.tag != "Player" && CurrentScene == "TNT Run" && tntFall)
    {
        Debug.Log(coll.gameObject.GetComponent<MeshRenderer>().material.name);
        if (coll.gameObject.GetComponent<MeshRenderer>().material.name == "TNT_0 (Instance)")
        {
            coll.gameObject.GetComponent<MeshRenderer>().material = TNT_Mat1;
            StartCoroutine(coroutine);
        }
        else if (coll.gameObject.GetComponent<MeshRenderer>().material.name == "TNT_1 (Instance)")
        {
            coll.gameObject.GetComponent<MeshRenderer>().material = TNT_Mat2;
            StartCoroutine(coroutine);
        }
        else if (coll.gameObject.GetComponent<MeshRenderer>().material.name == "TNT_2 (Instance)")
        {
            coll.gameObject.transform.position = Vector3.Lerp(coll.gameObject.transform.position, new Vector3(coll.gameObject.transform.position.x,-10,coll.gameObject.transform.position.z), tntFallTime);
            Destroy(coll.gameObject, 3);
        }
    }
}

IEnumerator TNTFallDelay(int WaitTime)
{
    tntFall = false;
    yield return new WaitForSeconds(WaitTime);
    tntFall = true;
}

```

This my code from Player script. If you look at my  as you can see it's actually cubes holding together. All i want is;

1. When player touches one of the cubes **For the first time** it will change material
2. When player touches that cube **Second time** it will change material again
3. When player touches that cube **Third time** cube is going to fall down.

But in these case (with my code) when i touch one of the cubes it does all of the if-else statements in a second and cube falls down.

# Answer
> 0 votes
I'd move the responsibility for this from the player avatar to the tile they're sitting on, and correct some other errors while we're at it.

```
public class ColorChangingTile : MonoBehaviour
{

    public Material[] materialSequence;

    Renderer renderer;
    float playerExitTime = float.NegativeInfinity;
    int state = 0;

    void Start()
    {
        renderer = gameObject.GetComponent<MeshRenderer>();
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            // Add a little tolerance, so rapid vibration at the edge of collision
            // doesn't advance the state. We need to leave for some time then return.
            if (Time.time - playerExitTime > 0.1f)
                AdvanceState();
        }
    }

    void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            playerExitTime = Time.time;
        }
    }

    void AdvanceState()
    {
        // If we're already falling, ignore further state changes.
        if (state == materialSequence.Length)
            return;

        renderer.sharedMaterial = materialSequence[state];
        state++;

        if (state == materialSequence.Length)
            StartCoroutine(FallThenDestroy(10f, 3f));
    }

    // This lets us animate out the fall before the destruction takes place.
    IEnumerator FallThenDestroy(float distance, float duration)
    {
        // 0.5f seconds later object will start to fall down.
        yield return new WaitForSeconds(0.5f);
        for (float t = 0; t < duration; t += Time.deltaTime)
        {
            // Fall some distance.
            transform.Translate(0, -distance * Time.deltaTime / duration, 0, Space.World);
            // Yield control to the engine to run for a frame, then resume here.
            yield return null;
        }

        // Destroy ourselves once the fall is over.
        Destroy(gameObject);
    }
}

```

# Answer
> 0 votes
How about using a simple boolean type to store when the player enters/exits in a cube area. My logic is simple... You have a 'colCounter' that increases each time the player collides with the cube. Then when the value is bigger/equal than '2' the cube falls. I used Physics to make the fall(which might be inefficient...). You can call the IEnumerator function @DMGregory instead.

I agree with @DMGregory on using collision check in a separate cube class. So all the cube should have that script and it would look for the player collision.

```
 public class CubeManager : MonoBehaviour
 {
   public Color[] colors;

   private bool playerEnter; // this helps to prevent continuous collision

   private int colCounter;

   private void OnCollisionEnter(Collision other)
   {
     if (playerEnter == false && other.transform.tag == "Player")
     {
        if (colCounter >= 2)
        {
            // code for falling. I Just used Physics.
            transform.GetComponent<Rigidbody>().isKinematic = false;
            return;
        }
        transform.GetComponent<Renderer>().material.color = colors[colCounter];
        colCounter++;
        playerEnter = true;

    }

  }

  private void OnCollisionExit(Collision other)
  {
    playerEnter = false;
  }
 }

```

# Answer
> 0 votes
```
public Material []materialSequence;
new public Renderer renderer;

float playerExitTime = float.NegativeInfinity;
int state = 0;

bool PlayerStays = false;

void Awake()
{
    renderer = gameObject.GetComponent<MeshRenderer>();
}

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        // Add a little tolerance, so rapid vibration at the edge of collision
        // doesn't advance the state. We need to leave for some time then return.
        if (Time.time - playerExitTime > 0.1f)
            AdvanceState();

    }
}

void OnCollisionStay(Collision collision)
{
    if (PlayerStays)
    {
        StartCoroutine(FallThenDestroy(5f, 9f));
        PlayerStays = false;
    }

    if (state == 1)
    {
        StartCoroutine(PlayerCheckStayStatus(1.5f));
    }
}

void OnCollisionExit(Collision collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        playerExitTime = Time.time;
    }
}

void AdvanceState()
{
    // If we're already falling, ignore further state changes.
    if (state == materialSequence.Length)
        return;

    renderer.sharedMaterial = materialSequence[state];
    state++;

    if (state == materialSequence.Length)
        StartCoroutine(FallThenDestroy(10f, 3f));
}

// This lets us animate out the fall before the destruction takes place.
IEnumerator FallThenDestroy(float distance, float duration)
{
    PlayerStays = false;
    yield return new WaitForSeconds(0.5f);
    for (float t = 0; t < duration; t += Time.deltaTime)
    {
        // Fall some distance.
        transform.Translate(0, -distance * Time.deltaTime / duration, 0, Space.World);
        // Yield control to the engine to run for a frame, then resume here.
        yield return null;
    }

    // Destroy ourselves once the fall is over.
    Destroy(gameObject);
}

IEnumerator PlayerCheckStayStatus(float time)
{
    yield return new WaitForSeconds(time);
    PlayerStays = true;
    Debug.Log(PlayerStays);
}

```

Edited code like this, it works nice but i need to ask when cube falls, my character teleports to nearest cube around instead of falling with it. How can i fix it?

---
Tags: unity, c#, game-mechanics
---


# Question
Title: Unity C# : How to make 3D objects move in the grid?
I want to move and deploy 3D objects in the grid, like bakery 2(Storm8 Studios). How do you make a grid like that? For example, make a 5x5 grid and move it to a touchdrag. I'd like you to give me some advice.

Pictures for reference: https://lh3.googleusercontent.com/Kwp9i9ExRboeQCtM65sztw3tqEL9R76zZzB9U6j5vs98ueF9ksOU3huMdZqv4KPDZ2E=w2590-h1430

# Answer
> 1 votes
Probably the simplest solution in your case would be to set the location of the object using the mouse position as a reference and then adjust it using a mathematical round operation, something like this:

```
public class SnapToGridControl : MonoBehaviour {
    public Transform objectToMove;
    private Vector3 objectLocation;
    private Camera _cam;

    void Start () {
        _cam = Camera.main;
    }

    void Update () {
        if(!objectToMove)
        {
            Debug.LogAssertoin("No object was selected.");
            return;
        }

        //Creating a ray pointing forward based on the Cursor and camera positions
        Ray ray = _cam.ScreenPointToRay(Inupt.mousePosition);
        RaycastHit hit;

        //Checking if the ray is hitting something, maybe the ground
        if(Physics.Raycast(ray, out hit, 100f, Layer.GetMask("Ground")))
        {
            //Adjusting the position and rounding the coordinates to snap to virtual grid
            objectPosition = new Vector3(Mathf.RoundToInt(hit.point.x), Mathf.RoundToInt(hit.point.y), Mathf.RoundToInt(hit.point.z));
        }

        //Setting the object's position
        objectToMove.position = objectPosition;
    }
}

```

For more info about casting rays from the Camera check here: https://docs.unity3d.com/Manual/CameraRays.html

---
Tags: unity
---


# Question
Title: How can I toggle between single shots when clicking the mouse left button and automatic none stop shooting when clicking the mouse right button?
I'm talking in build not in editor !

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

public class Shooting : MonoBehaviour
{
    [SerializeField]
    private Transform[] firePoints;
    [SerializeField]
    private Rigidbody projectilePrefab;
    [SerializeField]
    private float launchForce = 700f;
    [SerializeField]
    private Animator anim;
    [SerializeField]
    private bool automaticFire = false;
    [SerializeField]
    private bool slowDownEffect = false;

    private void Start()
    {
        anim.SetBool("Shooting", true);
    }

    public void Update()
    {
        if (isAnimationStatePlaying(anim, 0, "AIMING") == true)
        {
            if (Input.GetButtonDown("Fire1")/*automaticFire == false*/)
            {
                automaticFire = false;

                if (anim.GetBool("Shooting") == true)
                {
                    anim.Play("SHOOTING");
                    LaunchProjectile();
                }
            }
            else
            {
                if (/*automaticFire == true &&*/Input.GetButtonDown("Fire2"))
                {
                    automaticFire = true;
                }
            }
        }

        if(automaticFire == true)
        {
            anim.Play("SHOOTING");
            LaunchProjectile();
        }
    }

    private void LaunchProjectile()
    {
        foreach (var firePoint in firePoints)
        {
            Rigidbody projectileInstance = Instantiate(
                projectilePrefab,
                firePoint.position,
                firePoint.rotation);

            projectileInstance.AddForce(new Vector3(0, 0, 1) * launchForce);

            projectileInstance.gameObject.AddComponent<BulletDestruction>().Init();
        }
    }

    bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName)
    {
        if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName))
            return true;
        else
            return false;
    }
}

```

I tried to do it in the Update using the automaticFire variable but it's not working fine.

When clicking first the left mouse button it's shooting singles but then when clicking the mouse right button it's shooting automatic but then when clicking the left mouse button again it's not back to single shots again it's staying on automatic.

The idea is right click mouse button automatic fire left button each time clicking the left mouse button the automatic should stop and then single shots with the left mouse button. And this way to toggle between the Fire1 and Fire2.

Fire1 = left mouse button click Fire2 = right mouse button.

# Answer
> 1 votes
So, if I understood correctly when you press the Mouse1 key once, the gun keeps on shooting continuously, instead if you click Mouse0 it stops and will only shoot again when you press the Mouse0 again. I'll base my code on this. Also, since I don't know how you set up the Animator, I'll change a few things that may not correspond to how you used to manage it, but it should make it more clear.

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

public class Shooting : MonoBehaviour
{
    [SerializeField]
    private Transform[] firePoints;
    [SerializeField]
    private Rigidbody projectilePrefab;
    [SerializeField]
    private float launchForce = 700f;
    [SerializeField]
    private Animator anim;
    [SerializeField]
    private bool automaticFire = false;
    [SerializeField]//ADDED NEW VARIABLES FOR FIRE RATE TO PREVENT SHOOTING EVERY SINGLE FRAME
    private float fireRate = 0.25f;
    private float lastFire = 0;
    [SerializeField]
    private bool slowDownEffect = false;

    private void Start()
    {
        anim.SetBool("Aiming", true);//CHANGED NAME, IF WHAT IT DOES IS PLAYING THE AIMING STATE
    }

    private void Update()
    {
        if (isAnimationStatePlaying("AIMING", 0))
        {
            if(Input.GetMouseDown(0))//LEFT CLICKING
            {
                if(automaticFire)
                {
                    automaticFire = false;
                }
                else
                {
                    anim.Play("SHOOTING");
                    LaunchProjectile();
                }
            }

            if(Input.GetMouseDown(1) && !automaticFire)//RIGHT CLICKING
                automaticFire = true;

            if(automaticFire)
            {
                if(Time.time > lastFire + fireRate)
                {
                    anim.Play("SHOOTING");
                    LaunchProjectile();
                    lastFire = Time.time;
                }
            }
        }
    }

    private void LaunchProjectile()
    {
        foreach (var firePoint in firePoints)
        {
            Rigidbody projectileInstance = Instantiate(
                projectilePrefab,
                firePoint.position,
                firePoint.rotation);

            projectileInstance.AddForce(new Vector3(0, 0, 1) * launchForce);

            projectileInstance.gameObject.AddComponent<BulletDestruction>().Init();
        }
    }

    bool isAnimationStatePlaying(string stateName, int animLayer)
    {
        if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName))
            return true;
        else
            return false;
    }

}

```
* As you may have noticed, I have changed the anim.SetBool("Shooting", true); in the Start void since, from what I understand, what it does is simply making the animator play the "AIMING" state.
* Added a fireRate system so that the when you're automatic firing you won't instantiate a new projectile every single frame.
* I modified the isAnimationStatePlaying function since passing the animator is pointless as it is a global variable.
* One more suggestion is to attach the BulletDestruction component to the bulletPrefab so that you won't have to do it by code every time you shoot a new bullet.

If this doesn't answer your question then probably you need to upload an image of how your Animator is set up and better explain how this code is supposed to relate with other scripts in your scene that deal with the animator as well.

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


# Question
Title: How can I divide a grid map into clusters for path finding algorithm?
I am trying to implement HPA algorithm for finding the shortest path between two point. I came across the paper Near Optimal Path Finding Algorithm (by Botea, Müller & Schaeffer) but I am stuck at the clustering part. I have a 2 dimensional array and each index in the array is a node. Could anyone help me clustering my 2 dimensional array into clusters?

# Answer
The easiest implementation is to divide the map into large tiles. For example, this illustration shows a 16 x 16 map clustered into 4x4 tiles:

While somewhat naive, this approach is very easy to implement, gives consistently sized clusters and due to the hierarchical reduction, may very well give good enough performance.
> 1 votes

---
Tags: algorithm, path-finding
---


# Question
Title: Math needed to create a very simple 2D side view car game
I'm trying to create a 2D side view car game (something like *Hill Climb Racing*, but much more simpler), but I'm confused on the math and physics.

Most of the tutorials I found were about making a top-down view game. The rest referred to the Unity3D engine, which does all the math behind the scenes and uses complex objects, whereas I'd like to achieve my goal using simple objects, such as 2D vectors and abstract them on my own (that is, without any game engine).

The project I'm working on assumes that a car is a rectangle with 2 wheels, which are ellipses. It doesn't need to brake, turn back and speed up, it should just go straight ahead (and eventually stop in case it looses all of its velocity).

An example terrain the car would be driving on:

I can't figure out how to move the car on an irregular terrain, as well as how to rotate and move it when it falls from a hillock, etc.

Have you any idea how to move and rotate the car with respect to its current position and velocity?

# Answer
I'm assuming you can understand pseudocode, and know the various terms I use. I also assume screen is defined as origin the top left and max width and max height being the right and bottom respectively where width is x and height is y. I also assume your wheels are always on the ground. I also assume your terrain is a segmented line curve.

Create your car, and assign it's center-on-screen location to a 3D vector, and do the same for your wheels if they're seperate objects. The third demension is the rotation of the object relative to the screen width, i.e. 0 rotation is completely horizontal and max is vertical. Max rotation should be ±90 degrees based on your question. Store the total height and width of the vehicle. Create your terrain, storing an array of 3D vectors, each being a location and a rotation of a line segment on screen. Also store height and width information for each of these objects. Create a gravity constant. Create a velocity variable.

Each frame: Conceptualize a line straight down from the center of the wheels by iterating and cacheing all the points where the screen point X equals the wheel center X and the screen point Y equals wheel center Y plus some small constant. Then, using those points, iterate through your terrain and find the one that intersects that line i.e. terrain.y - (terrain.width/2) \< screen point y \< terrain point y + (terrain width /2) and store it. This also gives you a triangle to determine the correct wheel and car angle based on the hypotenuse and the Pythagorean theorem. If the wheel intersects the terrain (same as above, just different vector now), move the wheels away from it by the difference so you stop clipping. Once you have that you can apply your gravity and velocity physics. Each frame your velocity updates to velocity - gravity if the angle of the terrain is positive or velocity + gravity if your angle is negative. Then subtract any terrain friction you might like. If your velocity is less than or equal to 0 then game over.

Not exactly the best algorithm, the iterations will impact performance at especially high object counts. The math will need tweaking if any of my assumptions are incorrect but something tells me your a smart human and will be able to adapt in that case.
> 0 votes

---
Tags: 2d, physics, mathematics, side-scroller, car
---


# Question
Title: Why is my mesh outside its collision component grid?
I've created a blueprint (well, two of them, as a test since the first one wasn't working right) with an sphere component around a mesh, as in the picture:

As you can see, the mesh is well placed inside the collision component outer grid lines, but when I place this blueprint in the editor the mesh appears displaced from the grid:

I've checked this is not a merely visual bug of the editor; the collision component is really at different coordinates than the mesh, making all kind of strange collisions and side effects. However, I fail to see why is this happening, or what can I do to solve it. The blueprint is based on a custom C++ class, but I'm not making anything related to position in there. I paste the full code of that class:

```
#include "FPSBall.h"

// Sets default values
AFPSBall::AFPSBall(const FObjectInitializer& ObjectInitializer)
{
    // Crear una malla
    MeshComp = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("Mesh"));
    MeshComp->SetMobility(EComponentMobility::Movable);

    // Crear un component esfèric per a les colisions
    CollisionComp = ObjectInitializer.CreateDefaultSubobject<USphereComponent>(this, TEXT("Envolvent esferic"));
    CollisionComp->BodyInstance.SetCollisionProfileName("Pilota");
    RootComponent = CollisionComp;

    // Valors inicials de transformació
    Velocitat = 0.0f;
    Direccio = FVector(1, 2, 3);
    Rotacio = FRotator(3, 2, 1);
}

void AFPSBall::Shoot(float velocitat, FVector a_on, FRotator spin, FVector hit)
{
    Velocitat = velocitat;
    Direccio = a_on;
    Rotacio = spin;
    CollisionComp->AddImpulse(Direccio * Velocitat);
}

```

Can anyone point me towards a solution? I could try to fix things in the class constructor, but I fail to see why this is not working out-of-the-box and I don't want to try fixing things that shouldn't be broken to start with.

# Answer
Make sure your mesh ignores collisions. Or atleast it ignores the collision component by setting channels to ignore eachother.
> 0 votes

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


title: how to detect Unity UNET errors?

text:
# Question
Title: how to detect Unity UNET errors?
I'm working on a simple multiplayer online game. and I use `UNET` and `Networkmanager`.

In my game I have some rooms and players that they can join to this rooms by connecting to specific `server.exe` file that I runned on a dedicated server.

My problem is when I use port 7777 for first server, if I run another server, then this error Appear :

> Cannot open socket on ip{\*},and port{7777}

For now I solved this issue by building servers with specific ports. for example in `server1.exe` I used port 7777 by default. and `server2.exe` , 7778 and same for other servers .

But I want to do this automatically. I mean when the server recognize port 7777 is busy , then increase port number.

I want to know can I use `try catch` for this kind of errors ? because I used `try catch` but it's not work. I don't know how to use it. this is part of my code :

```
try
    {
        StartServer();
    }
    catch(Exception ex)
    {
        networkPort++;
        //then change port number and run server again
    }

```

I just looking for a way that my servers run by choosing right port automatically.

# Answer
I solved my problem with another way that works very well.

For checking the port is free or not we can use `System.Net`.

and before Network Manager `StartServer()`, we have to check the current port is busy or not.

```
    int the_port = 7777;

    IPEndPoint[] list_all_ports = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();

                foreach (IPEndPoint iep in list_all_ports)
                {
                    if (the_port == iep.Port)
                    {
                        the_port++;
                    }
                }

                //set the network port
                networkPort = the_port;
                StartServer();

```

For example if another server use 7777 then new server port will set 7778 automatically.
> 1 votes

---
Tags: unity, networking, unet, exceptions, error-management
---


# Question
Title: How to detect whether a transform has rotated left or right
I have a game object in my scene, and I want to know how can I calculate whether this game object rotating to the right or to the left.

For example :

```
if(check whether the transform rotated to the right)
{
    print("rotate to right");
}
else if(check whether the transform rotated to the left)
{
    print("rotate to left");
}
else
{
    print("no rotation");
}

```

# Answer
> 2 votes
I'd recommend using the properties of the cross product to check this, rather than relying on Euler angles.

Given a vector a & b, the cross product will point along the rotation axis that swings a toward b. Since Unity uses left-handed coordinates, you can take your left hand in a "thumbs-up" gesture and turn it so you fingers curl in the direction of rotation. Your thumb points along the direction of the cross product.

For example, here's how we'd detect rightward (positive) and leftward (negative) "yaw" rotation about the world's Y+ axis:

```
public enum RotationDirection {
    NoRotation,
    Leftward,
    Rightward
}

Vector3 oldForward
RotationDirection rotationDirection;

void Start() {
    oldForward = transform.forward;
}

void Update() {
    Vector3 cross = Vector3.Cross(oldForward, forward);

    if (cross.y > 0f) }
        rotationDirection = RotationDirection.Rightward;
    } else if (cross.y < 0f) {
        rotationDirection = RotationDirection.Leftward;
    } else {
        rotationDirection = RotationDirection.NoRotation;
    }

    oldForward = transform.forward;
}

```

# Answer
> 1 votes
Do you have a rigidbody on it? Then you can check the angularVelocity field. If not, the best you can do is cache the previous orientation, then compare it to the current one. First let's define "right" and "left". To me, that means "clockwise about the z axis" and "counter clockwise about the z axis". What we want then is to do is this:

```
Quaternion oldRotation;
Quaternion currentRotation;
float zRotation = (Quaternion.Inverse(oldRotation) * currentRotation).eulerAngles.z;
if (z > 0) // we turned right
if (z < 0) // we turned left
if (z == 0) // we did not turn

```

Something like that should work. But if you have a rigidbody, do just use that.

---
Tags: unity, c#, rotation, scripting
---


# Question
Title: Add logic if Shift is pressed nothing to do if not speed=100 to my BP
I have followed tutorial on how to make 3rd person game but I cant figure out how to implement logic if Shift is pressed nothing to do and if its not set speed to be some value lets say 100

# Answer
> 1 votes
I’m not sure in the scripting you’re using but shift being pressed or not is a Boolean so 0 or 1, you can set the speed to 100 times by NOT that Boolean, so if shift is pressed it’ll be 0 but if it’s not it’s going to be 100.

Speed = 100 * (not)shift\_pressed\_boolean

If it gives you an error when you times a number by Boolean just parse it as integer

# Answer
> 1 votes
The first thing you're going to want to do is set up an input action that's bound to the Shift key. If the tutorial you followed showed you how to set up a third person game from scratch, some of this will probably look a little bit familiar.

If I'm understanding you correctly, it sounds like what you want is to have the character sprint when you hold down shift, and to run at normal speed when you're not holding down shift? If I'm wrong, this advice should still point you in the right direction.

First you're going to want to set up an input action bound to Shift:

Go to the "Edit" menu in the Editor and select "Project Settings"

The settings for adding new Input Actions are in the Input section, under Engine:

Create a new Action Mapping (call it "Sprint" or something suitably descriptive. The engine doesn't really care what it's called), and select "Left Shift" from the dropdown. You can ignore the "Toggle Sprint" one I added if you're not using a controller, I just added that one for completeness, typically in most games where you can play on controller the clicking in the left thumbstick button will toggle sprint on or off, so I made a separate input action for that case.

The next step is to handle this new input in your Blueprint. Create a new Boolean variable and give it a suitable name. You can see here I've called mine "Is Sprint Active?", but ultimately it doesn't really matter what you call it as long as it's descriptive (so that you can remember what it's for later)

As you can see from this picture, when the "Sprint" action is Pressed, we set the "Is Sprint Active?" variable to true, when the "Sprint" action is Released, we sit it to false.

The Toggle Sprint action you can ignore, but it's basically the same thing for the "Toggle Sprint" action, except every time you press it, it takes the current value of "Is Sprint Active?" and flips it to the opposite value.

This isn't pictured in the above example, but every time you modify this variable, you'll want to modify the maximum walk speed on the CharacterMovement component. This controls how fast your character can go.

In this screenshot, I have two variables here (both with "Is Instance Editable" ticked in their settings, so the values can be modified from the settings of the Character Blueprint), these two settings represent the maximum speed when sprint is off, and the maximum speed when sprint is on.

This should give you a very basic version of sprint. To make it look good you can set up your Animation Blueprint to play a different running animation when sprint is active, to give you something like this (sorry for the image being a little washed out, I forgot to turn off HDR colour settings on my desktop)

YouTube Video - Unreal Run Sprint Example

---
Tags: unreal-4
---


# Question
Title: Move rigidbody using WASD keys but rotate it based on camera/mouse movement
I am very new to unity and my scripts are based on some scripts found on the web.

I want to make a first person view so the camera is attached to my rigidbodys head. Then i want to move my rigidbody based on keyboard input (wasd) and rotate it using the mouse movement.

Until now, i used the following code for moving my rigidbody:

```
void Update() {

    /* calculate rigidbody movement */
    movement = new Vector3( Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;

    /* calculate mouse look to rotate the rigidbody*/
    mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
    mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
    smoothV.x = Mathf.Lerp(smoothV.x, mouseDelta.x, 1f / smoothing);
    smoothV.y = Mathf.Lerp(smoothV.y, mouseDelta.y, 1f / smoothing);
    mouseLook += smoothV;

}

void FixedUpdate() {

    /* apply rigidbody movement from Update() */
    transform.Translate( movement * moveSpeed * Time.deltaTime );
    /* apply rigidbody rotation from Update() */
    transform.localRotation = Quaternion.AngleAxis(mouseLook.x, transform.up);
    /* apply camera rotation from Update() */
    Camera.main.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);

}

```

I learned today that i dont have to move a rigidbody's transform but now i am totally confused and it seems i have to restart my whole (first!) project.

So when i use MovePosition and MoveRotation, how do i rotate it based on the camera perspective/mouse movement?

I think the movement Vector is ok so i can simply rewrite the FixedUpdate to something like

```
rigidbody.MovePosition(movement * speed * Time.deltaTime)

```

but i am totally stuck on how to apply the camera rotation to my rigidbody to use it like

```
void FixedUpdate() {
    /* move the rigidbody */
    rigidbody.MovePosition(movement * moveSpeed * Time.deltaTime);
    /* rotate the camera */
    camera.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);

    /* but how can i rotate the rigidbody based on the cameras rotation??? */
    rigidbody.MoveRotation(?????);

}

```

I hope its clear what i want, thank you!

# Answer
This is the movement code for my character script:

```
private Camera cam;

private void Start ()
{
    cam = Camera.main;
}

private void FixedUpdate ()
{
    Move();
}

private void Move ()
{
    // Getting the direction to move through player input
    float hMove = Input.GetAxis("Horizontal");
    float vMove = Input.GetAxis("Vertical");
    float speed = 5.0f;

    // Get directions relative to camera
    Vector3 forward = cam.transform.forward;
    Vector3 right = cam.transform.right;

    // Project forward and right direction on the horizontal plane (not up and down), then
    // normalize to get magnitude of 1
    forward.y = 0;
    right.y = 0;
    forward.Normalize();
    right.Normalize();

    // Set the direction for the player to move
    Vector3 dir = right * hMove + forward * vMove;

    // Set the direction's magnitude to 1 so that it does not interfere with the movement speed
    dir.Normalize();

    // Move the player by the direction multiplied by speed and delta time
    transform.position += dir * speed * Time.deltaTime;

    // Set rotation to direction of movement if moving
    if (dir != Vector3.zero)
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(forward), 0.2f);
    }

}

```

and this is my camera script (sorry about the wierd indenting, copying and pasting from visual studio messed it up and I don't know how to fix it):

```
using UnityEngine;

public class CameraScript : MonoBehaviour
{
// Angle to clamp the camera at on the up/down axis
private const float Y_ANGLE_MIN = -50.0f;
private const float Y_ANGLE_MAX = 50.0f;

// The game object's transform for the camera to look at
public Transform target;

private Transform camTransform;

// Distance between the player and the camera
private float distanceBetween = 2f;
private float currentX = 0.0f;
private float currentY = 0.0f;

// How much the camera reacts to movement of the mouse
private float sensitivityX = 6.0f;
private float sensitivityY = 3.0f;

private void Start()
{
    camTransform = transform;
}

private void Update()
{
    currentX += Input.GetAxis("Mouse X") * sensitivityX;
    currentY -= Input.GetAxis("Mouse Y") * sensitivityY;

    currentY = Mathf.Clamp(currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
}

private void LateUpdate()
{
    int layerMask = 1 << 9;
    layerMask = ~layerMask;

    Vector3 dir = new Vector3(0.5f, 1.6f, -distanceBetween);
    Quaternion rot = Quaternion.Euler(currentY, currentX, 0);
    camTransform.position = target.position + rot * dir;

}
}

```

If you need any clarification or find any errors, please let me know :) Also, this is my first time answering, so if I'm missing something please tell me that too.

Good luck!
> 1 votes

# Answer
Okay so after quickly trying your code I see that the rotation of the camera was not working on X-Axis,

The problem was at this line in the `FixedUpdate()`

`camera.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);`

So I have modified `FixedUpdate()`

```
    void FixedUpdate()
    {
        rigidbody.MovePosition(movement * moveSpeed * Time.deltaTime);

        // I tried my best to explain this in my answer
        cam.transform.localRotation = Quaternion.Euler(-mouseLook.y, mouseLook.x, 0f);

        rigidbody.MoveRotation(Quaternion.Euler(cam.transform.localRotation.eulerAngles));
    }

```

Notice that how I put the `mouseLook.x` and `mouseLook.y` in different order, now this is tricky part to explain but I will try to explain,

Assume we have set our pointer to 0,0 on the screen, when we move the mouse on the left it will return minus value on X-Axis and when we move the mouse right it will return positive value on the X-Axis,

Same for Y-Axis when we move Up it returns positive value and negative when we move down

Now assume we have move the mouse left, now in order to rotate the camera to the left side we have to rotate it around Y-Axis with some minus values

Imagine `mouseLook` Returns `-1,0` when we move left, now to rotate camera on left we need to do `0, -1, 0` on its rotation,

Same goes for Y-Axis, we move the pointer up it returns `0,1`, now to rotate camera up we need to do `-1, 0, 0`

I know it is very confusing and my explaination skills are equally horrible but to keep things simple remember this,

to rotate camera up we need to manipulate its X-Axis with minus values,
to rotate camera down we need to manipulate its X-Axis with plus values,
to rotate camera left we need to manipulate its Y-Axis with minus value,
to rotate camera Right we need to manipulate its Y-Axis with plus value.
> 0 votes

---
Tags: unity, rigidbody
---


# Question
Title: Workflow for authoring hitbox data for a 2D fighting/platformer game
I understand that collisions in fighting games are detected using hitboxes and hurtboxes associated with specific frames of the animation

I am looking for techniques to author the data for these hitboxes to use in my Java platformer game (I'm not using a pre-existing engine)

I have a single hitbox for the character working, but as I add animations with sprites of variable sizes, I need to move from a single static hitbox to something that fits the animation frames.

So far I've considered:

* Manually picking position & size numbers for each frame, and typing them out in a text file like a JSON data structure asset to load into my game.

This works for short animations, but seems like it wouldn't scale to larger animation sets of 30-100 frames each.
* Automated image segmentation with rectangles. I wrote an algorithm which divides the image into n rectangles with their transparent parts trimmed.

However, it is far from optimized, and may produce inappropriate results. It cannot be relied to automate the task.

What method can I use to create suitable hitboxes for a large number of animation frames?

# Answer
> 4 votes
Handling hitbox and hurtboxes is something usually the artist and game designers decide. In the ideal situation these boxes are manually created for each frame of animation.

The main reason for creating them manually is because these boxes are context sensitive- that is, you need to understand what part of the character is dealing damage or what part of the character is defending and so on.

DMGregory provided answers with regard to how these boxes work and how one can implement them in the comment section of the question.

What if the animation contains a lot of frames? Keyframing and interpolation is your best bet.

In the animation use keyframes when and where boxes should appear, disappear and their locations. Interpolate the frames inbetween to transition the hit/hurt boxes. This way you only have to position these boxes at key moments and positions while the rest is calculated. If you have a fixed number of frames you can pregenerate the boxes as a data structure. If you have interpolated animations (example using Spine software or other skeletal animation software) you could do the boxes on the fly (some tools support this out of the box).

**Regarding automated hitbox generation**

Let's have a look at the animation of Ryu:

The animator has created a bunch of sprites that follow a sequence. Now it is hard for an automated process to understand the first frame of the **wind down** part is where the attach ends. There is still a 'fist' in that frame, but it is no longer dangerous. Thus the artist has to tell the game what is needed.

**Traditional sprite frames**

So you would need to define for each individual frame where the hit and hurtboxes are. Now in some animation tools you can define the hitboxes and export the data.

In your game you would read your sprite data (which may contain sequence and timing data) and also the hitbox/hurtbox data. Upon collision you then check what frame you are and where these boxes are located and act accordingly.

**Interpolation**

If you use *skeletal* (or *rigged*) animation, it would mean that the artist poses the model for set intervals (let's say Ryu consists out of separate sprites for arms, legs, head and body) and move these parts to key moments in time. Now attach hitboxes accordingly on that same timeline. Imagine Ryu then smoothly transition from one frame to the next based on linear interpolation.

Then use that information to transition between the keyframes and recalculate the boxes as well.

Your workflow needs both the animation and a somthing to provide hitboxes for the (key)frame data. This is then exported as datapackages your game can read.

**Conclusion**

For hit and hurtboxes, you will need to add a step in your workflow to generate the required information. If you have really lengthy animations (30+ frames) you may try to combine the traditional animation with the interpolation technique.

---
Tags: 2d, collision-detection, sprites, tools, asset-workflow
---


# Question
Title: How to implement trail renderer like unity?
I wang to implement a trail renderer in my course about compute graphics using OpenGL. I google this question and search it in https://gamedev.stackexchange.com/ and find nothing except unity trail renderer. However this is my course project and I really really want a trail effect in my project.Is there any website or paper to solve my question?

# Answer
> 3 votes
The Unity trail renderer is basically a procedurally created triangle strip. This should be relatively easy to do on your own. Add an array to your game object which keeps track of the past positions and rotations of your object. Then create the geometry of your trail object each frame by creating vertices from these positons and rotations. Use the rotation to calculate a point slightly to the left and another point slightly to the right of the position. If you want the trail to become thinner in the end, reduce the distance the further the point is in the past. Set an appropriate material, pass the coordinates as a vertex buffer and you are done.

---
Tags: opengl, graphics, trail-renderer
---


# Question
Title: How to rotate two textures at once in Libgdx, while keeping their relative positions the same?
I am trying to develop a game with cards, where the user can swipe left or right to tilt the cards like this. The red & white cross should stay in the same position on the yellow card as they tilt together, but you can see in the images below that their positions shift relative to one another:

I started this game with the yellow card with purple edges, and I tried to rotate it once the user swipe left or right using this code:

```
void renderCard(SpriteBatch sb , TextureRegion cardShape)
{
    sb.draw(cardShape, x, y, originX, originY, cardWidth, cardHeight, 1, 1, rotationAngle);
}

```

Once the user swipes, I modify the rotation angle in the method above.

Now, I want to add another texture region over this one, and I want to rotate it too once the user swipes.

Here is the code for that:

```
void renderCross(SpriteBatch sb,TextureRegion crossShape)
{
    sb.draw(crossShape, x+130.0f, y+130.0f, originX+130.0f, originY+130.0f, 200, 200, 1, 1, rotationAngle);
}

```

When there was no swipe performed, anything was okay, all the above are drawn. perfectly drawn.

But when I swipe left or right, there are some offsets added, as you can see in the images above.

So the question is, how do I keep the the same relative positions between these two textures, like the game started?

# Answer
You need to make it so both sprites rotate around the same point. You will need to set the origin of each sprite so that they are both in the same world space.

```
cardShape.setOrigin(0, 0); // bottom left corner
crossShape.setOrigin(-2,-2) // 2 units below and 2 units to the left

```

This should make both sprites rotate around the card bottom left corner if the crossShape is 2 units up and 2 units to the right of the cardShapes bottom left corner.
> 0 votes

---
Tags: libgdx, textures, sprites, rotation
---


title: Emotiv Epoc integration with Unity

text:
# Question
Title: Emotiv Epoc integration with Unity
I'm coding a small game on Unity to control with the Emotiv Epoc headset. However, as I'm new to Unity, I'm having some trouble setting everything up to connect the device with my game.

I downloaded the SDK from Github and tried the sample project and worked fine, but I can't translate that to my own project. I opened an issue on that github repository and I was suggested to use this new plugin.

What I see is that there's a file called EdkDll.cs that contains all the functions that I'll need in my project. I suppose that I have to build it to create the .dll that will be used on Unity, but when I try to do so on Visual Studio or MonoDevelop (and after adding the reference to UnityEngine.dll), a big part of the EdkDll.cs goes gray and I get an error on the calls to the grayed functions ("... doesn't exist in the current context"). I tried changing the .NET framework from 3.5 to other, but that didn't work either.

I think it can't be so complicated and there must be something I'm doing wrong, or maybe there's another way of getting the EdkDll.cs functions to be available from the scripts in my project.

EDIT:

In the example provided in the SDK (here), there's a script that controls the connection to the device (EmotivCtrl.cs) and another to control the player (playerCtrl.cs), and also others to control the camera and a text window, but I think I should be able to make my project work without those. The thing is that **I don't understand where or how is the connection script called**, because if I include it in the assets folder of my project and put a print inside the Awake method, it never shows.

My guess is that is called here (movm.cs): `EmoEngine.Instance.EmoStateUpdated += new EmoEngine.EmoStateUpdatedEventHandler(engine_EmoStateUpdated);`, but the function `engine_EmoStateUpdated` doesn't seem to be accessed either.

These are the scripts to control the device and the player of my project:

movm.cs (to control the player):

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

public class movm : MonoBehaviour
{
    private Rigidbody rb;
    EmoEngine engine;

    void engine_EmoStateUpdated(object sender, EmoStateUpdatedEventArgs e)
    {
        Debug.Log("empieza engine");
        EmoState es = e.emoState;
        Debug.Log("despues");
        /*if (e.userId != 0)
            return;*/
        Debug.Log("Corrent action: " + es.MentalCommandGetCurrentAction().ToString());
        if (es.MentalCommandGetCurrentAction() == EdkDll.IEE_MentalCommandAction_t.MC_PUSH)
        {
            //Vector3 movement = new Vector3(cam.transform.forward.x, cam.transform.forward.y, cam.transform.forward.z);
            //rb.AddForce(movement * speed);
            rb.AddForce(Vector3.up);
            Debug.Log("Push");
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("empieza movm");
        rb = GetComponent<Rigidbody>();
        Debug.Log("rigid");
        EmoEngine.Instance.EmoStateUpdated += new EmoEngine.EmoStateUpdatedEventHandler(engine_EmoStateUpdated);
        Debug.Log("asdasd");
    }

    void FixedUpdate()
    {
        if (Input.GetKey("w"))
        {
            gameObject.transform.Translate(2f * Time.deltaTime, 0, 0);
        }
    }

}

```

EmotivCtrl.cs (to connect to the Emotiv Epoc device):

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

public class EmotivCtrl : MonoBehaviour {
    public GameObject modal;
    public Text message_box;
    public InputField userName;
    public InputField password;
    public InputField profileName;

    public static EmoEngine engine;
    public static int engineUserID = -1;
    public static int userCloudID = 0;
    static int version  = -1;

    /*
     * Create instance of EmoEngine and set up his handlers for
     * user events, connection events and mental command training events.
     * Init the connection
    */
    void Awake ()
    {
        Debug.Log("awake");
        engine = EmoEngine.Instance;
        engine.UserAdded                      += new EmoEngine.UserAddedEventHandler (UserAddedEvent);
        engine.UserRemoved                    += new EmoEngine.UserRemovedEventHandler (UserRemovedEvent);
        engine.EmoEngineConnected             += new EmoEngine.EmoEngineConnectedEventHandler (EmotivConnected);
        engine.EmoEngineDisconnected          += new EmoEngine.EmoEngineDisconnectedEventHandler (EmotivDisconnected);
        engine.MentalCommandTrainingStarted   += new EmoEngine.MentalCommandTrainingStartedEventEventHandler (TrainingStarted);
        engine.MentalCommandTrainingSucceeded += new EmoEngine.MentalCommandTrainingSucceededEventHandler (TrainingSucceeded);
        engine.MentalCommandTrainingCompleted += new EmoEngine.MentalCommandTrainingCompletedEventHandler (TrainingCompleted);
        engine.MentalCommandTrainingRejected  += new EmoEngine.MentalCommandTrainingRejectedEventHandler (TrainingRejected);
        engine.MentalCommandTrainingReset     += new EmoEngine.MentalCommandTrainingResetEventHandler (TrainingReset);
        engine.Connect ();
        Debug.Log("fini");
    }

    /*
     * Init the user, password and profile name if you want it
    */
    void Start(){
        Debug.Log("START");
        userName.text = "";
        password.text = "";
        profileName.text = "";
    }

    /*
     * Call the ProcessEvents() method in Update once per frame
    */
    void Update () {
        engine.ProcessEvents ();
    }

    /*
     * Close the connection on application exit
    */
    void OnApplicationQuit() {
        Debug.Log("Application ending after " + Time.time + " seconds");
        engine.Disconnect();
    }

    /*
     * Several methods for handling the EmoEngine events.
     * They are self explanatory.
    */
    void UserAddedEvent(object sender, EmoEngineEventArgs e)
    {
        message_box.text = "User Added";
        engineUserID = (int)e.userId;
    }

    void UserRemovedEvent(object sender, EmoEngineEventArgs e)
    {
        message_box.text = "User Removed";
    }

    void EmotivConnected(object sender, EmoEngineEventArgs e)
    {
        Debug.Log ("conectado");
        message_box.text = "Connected!!";
    }

    void EmotivDisconnected(object sender, EmoEngineEventArgs e)
    {
        message_box.text = "Disconnected :(";
    }

    public bool CloudConnected()
    {
        if (EmotivCloudClient.EC_Connect () == EdkDll.EDK_OK) {
            message_box.text = "Connection to server OK";
            if (EmotivCloudClient.EC_Login (userName.text, password.text)== EdkDll.EDK_OK) {
                message_box.text = "Login as " + userName.text;
                if (EmotivCloudClient.EC_GetUserDetail (ref userCloudID) == EdkDll.EDK_OK) {
                    message_box.text = "CloudID: " + userCloudID;
                    return true;
                }
            }
            else
            {
                message_box.text = "Cant login as "+userName.text+", check password is correct";
            }
        }
        else
        {
            message_box.text = "Cant connect to server";
        }
        return false;
    }

    public void SaveProfile(){
        if (CloudConnected ()) {
            int profileId = -1;
            EmotivCloudClient.EC_GetProfileId(userCloudID, profileName.text);
            if (profileId >= 0) {
                if (EmotivCloudClient.EC_UpdateUserProfile (userCloudID, (int)engineUserID, profileId) == EdkDll.EDK_OK) {
                    message_box.text = "Profile updated";
                } else {
                    message_box.text = "Error saving profile, aborting";
                }
            } else {
                if (EmotivCloudClient.EC_SaveUserProfile (
                    userCloudID, engineUserID, profileName.text,
                    EmotivCloudClient.profileFileType.TRAINING) == EdkDll.EDK_OK) {
                    message_box.text = "Profiled saved successfully";
                } else {
                    message_box.text = "Error saving profile, aborting";
                }
            }
        }

    }

    public void LoadProfile(){
        if (CloudConnected ()) {
            int profileId = -1;
            EmotivCloudClient.EC_GetProfileId(userCloudID, profileName.text);

            if (EmotivCloudClient.EC_LoadUserProfile (
                userCloudID, (int)engineUserID,
                profileId,
                (int)version) == EdkDll.EDK_OK) {
                message_box.text = "Load finished";
            }
            else {
                message_box.text = "Problem loading";
            }
        }
    }

    public void TrainPush(){
        engine.MentalCommandSetTrainingAction((uint)engineUserID, EdkDll.IEE_MentalCommandAction_t.MC_PUSH);
        engine.MentalCommandSetTrainingControl((uint)engineUserID, EdkDll.IEE_MentalCommandTrainingControl_t.MC_START);
    }

    public void TrainNeutral(){
        engine.MentalCommandSetTrainingAction ((uint)engineUserID, EdkDll.IEE_MentalCommandAction_t.MC_NEUTRAL);
        engine.MentalCommandSetTrainingControl((uint)engineUserID, EdkDll.IEE_MentalCommandTrainingControl_t.MC_START);
    }

    public void TrainingStarted(object sender, EmoEngineEventArgs e){
        message_box.text = "Trainig started";
    }

    public void TrainingCompleted(object sender, EmoEngineEventArgs e){
        message_box.text = "Training completed!!";
    }

    public void TrainingRejected(object sender, EmoEngineEventArgs e){
        message_box.text = "Trainig rejected";
    }

    public void TrainingSucceeded(object sender, EmoEngineEventArgs e){
        message_box.text = "Training Succeeded!!";
        //modal.GetComponent<MessageBox> ().init ("Training Succeeded!!", "Do you want to use this session?", new Decision (AceptTrainig));
    }

    public void AceptTrainig(bool accept){
        if (accept) {
            engine.MentalCommandSetTrainingControl ((uint)engineUserID, EdkDll.IEE_MentalCommandTrainingControl_t.MC_ACCEPT);
        } else {
            engine.MentalCommandSetTrainingControl ((uint)engineUserID, EdkDll.IEE_MentalCommandTrainingControl_t.MC_REJECT);
        }
    }

    public void TrainingReset(object sender, EmoEngineEventArgs e){
        message_box.text = "Command reseted";
    }

    public void Close(){
        Application.Quit ();
    }
}

```

# Answer
> 0 votes
You do not need to build the dll yourself (unless you intend to make changes to it).

Pre-compiled binaries for various platforms are available in the /bin/ folder of the repository you've linked.

All of the .cs files in the Unity Plugin folder are to be placed inside your Unity assets folder. They'll be compiled as part of your Unity scripting C# project.

These files provide the glue and convenience functions that let your own C# code make use of the functionality baked into the dlls.

Be sure to consult the Unity documentation on including and configuring native plugins (like dlls) in your project.

---
Tags: unity
---


title: Unity - IsTouchingLayers problem

text:
# Question
Title: Unity - IsTouchingLayers problem
I'm experimenting with 2d physics, and the problem is this: The `IsTouchingLayers` function reveals that the object is touching a layer, but only if I use the`-1` parameter which is equivalent to `Physics2D.AllLayers`.

These are the tests done on Visual Studio in debug in the immediate control window:

```
?Physics2D.AllLayers
-1

?GroundCheck.IsTouchingLayers(-1)
true

?GroundCheck.IsTouchingLayers(0)
false
?GroundCheck.IsTouchingLayers(1)
false
?GroundCheck.IsTouchingLayers(2)
false
?GroundCheck.IsTouchingLayers(3)
false
?GroundCheck.IsTouchingLayers(4)
false
?GroundCheck.IsTouchingLayers(5)
false
?GroundCheck.IsTouchingLayers(6)
false
?GroundCheck.IsTouchingLayers(7)
false
?GroundCheck.IsTouchingLayers(8)
false
?GroundCheck.IsTouchingLayers(9)
false
?GroundCheck.IsTouchingLayers(10)
false
?GroundCheck.IsTouchingLayers(11)
false
?GroundCheck.IsTouchingLayers(12)
false
?GroundCheck.IsTouchingLayers(13)
false
?GroundCheck.IsTouchingLayers(14)
false
?GroundCheck.IsTouchingLayers(15)
false
?GroundCheck.IsTouchingLayers(16)
false
?GroundCheck.IsTouchingLayers(17)
false

```

These are the layers I have in the project:

If I use the `-1` parameter it works correctly, the character jumps when it touches the ground and does not jump when it is in the air, but it will definitely jump by touching any layers. And anyway I want to understand why.

What am I doing wrong ?

*Thank you*

# Answer
I think it is a problem of misunderstanding, and lack of good documentation from Unity's side, of how the Layers are represented on Editor and how their values really are. If you read IsTouchingLayer's documentation, you can see that just by mere semantics the int you have to provide is that of a layer mask. LayerMasks make use of a technique called bit-masking, which is a technique used to store many flags into a chain of bits, for optimization purposes. So, for example, being an integer a 4 bytes (32 bits) type, you can store up to 32 flags (saving you the need to potentially declare up to 32 bools, for example).

So, if you consulted the links I provided and understood the basics of bit-masking, we can now understand more clearly why the Layers presented on editor are between 0 and 32:

* Layer 0 (Default) = 1 \<\< 0 = 1
* Layer 1 (TransparentFX) = 1 \<\< 1 = 2
* Layer 2 (IgnoreRaycast) = 1 \<\< 2 = 4
* ...
* Layer 32 (CustomLayer) = 1 \<\< 32 = 2,147,483,647
* So basically: Layer N (CustomLayer) = 1 \<\< N = 2 raised to the N

So what you must pass are the numbers of the Layers but using bit shifting (so for example, if you wanted to pass the layer 4, you can either pass it as 1 \<\< 4 or 16). And you can also pass multiple layer values, say you want to pass layers 4, 5 and 7:

```
int layerMask = (1 << 4) | (1 << 5) | (1 << 7)

```

And that is why the use of an exposed (public or serializable) LayerMask, instead of you yourself doing bit shifting operations, is sometimes the way to go, it does things more easily. So you could do instead:

```
public class Example : MonoBehaviour
{
    public LayerMask layerMask;
    public Collider2D ground;

    private void Awake()
    { /// LayerMask has an implicit conversion to int
        Debug.Log(ground.IsTouchingLayers(layerMask));
    }
}

```

Hope it helps.
> 4 votes

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


title: Foreach/list loop problem

text:
# Question
Title: Foreach/list loop problem
I am having a problem with a foreach loop. When my AOE ability hits an enemy it creates a CircleCollider2D and puts all the enemies on a list, which then the loop goes through and adds damage to their scripts.

```
private void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "Enemy")
    {
        targets.Add(other);

        foreach (Collider2D enemy in targets)
        {
            EnemyHealth hp = enemy.GetComponentInChildren<EnemyHealth>();

            hp.TakeDamage(abilityConfig.baseDamage);

            print(enemy.name + " takes " + abilityConfig.baseDamage + "damage!");
        }
    }
}

```

But as you can see from the picture below the loop goes 3 times over one enemy, 2 times over the second one and once over the third.

As these enemies are the same type they all have the same EnemyHealth script. If anyone would point me in the right direction I would greatly appreciate it.

# Answer
`OnCollisionEnter` executes for each entity that collided. So you don't need `foreach` loop at all.

```
private void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Enemy")
    {
        EnemyHealth hp = enemy.GetComponentInChildren<EnemyHealth>();
        hp.TakeDamage(abilityConfig.baseDamage);
        print(enemy.name + " takes " + abilityConfig.baseDamage + " damage!");
    }
}

```
> 4 votes

# Answer
In response to your comment, if you want to hit every enemy than i suggest you get all the reference of your enemies and then apply the damage like following

```
private void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "Enemy")
    {
        // Change targets type to List<GameObjects>
        targets.Clear();
        targets.AddRange(GameObject.FindGameObjectsWithTag("Enemy"));

        foreach (GameObject enemy in targets)
        {
            EnemyHealth hp = enemy.GetComponentInChildren<EnemyHealth>();

            hp.TakeDamage(abilityConfig.baseDamage);

            print(enemy.name + " takes " + abilityConfig.baseDamage + " damage!");
        }
    }
}

```

We are here basically checking if we hit any enemy, if thats the case we are first clear the list then add all the enemies to the list, so no duplicates there,

Then we are looping through all pretty much the same
> 0 votes

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


# Question
Title: Detect when an Oculus headset is stationary/idle using transform.hasChanged
I want to know how can I change in unity the thershold of the method below:

> transform.haschanged

At the moment it is so sensitive and it triggers with 0.00001 change in the camera.

We have created an Interactive VR video in unity and we want that everytime the user doesnt use the oculus for 30 seconds, a trailer video starts to play!

We have created the code below but even when the oculus is on the ground, still moves a bit (too sensitive):

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

public class Trailer : MonoBehaviour
{

public int timeOut;

private int timeOutTimer = 0;

private Quaternion gameObjectrotation;
private VideoPlayer videoPlayer;
public float dynamicRange = 100f;

// Use this for initialization
public void Awake()
{
    Vector3 lastPos;
    videoPlayer = GetComponentInParent<VideoPlayer>();
    gameObjectrotation = Camera.main.gameObject.transform.rotation;

    InvokeRepeating("ScreenSaver", 0, 1.0f);
}

public void ScreenSaver()
{

    timeOutTimer++;

    var wMinus = gameObjectrotation.w - dynamicRange;
    var wPlus = gameObjectrotation.w + dynamicRange;
    var xMinus = gameObjectrotation.x - dynamicRange;
    var xPlus = gameObjectrotation.x + dynamicRange;
    var yMinus = gameObjectrotation.y - dynamicRange;
    var yPlus = gameObjectrotation.y + dynamicRange;
    var zMinus = gameObjectrotation.z - dynamicRange;
    var zPlus = gameObjectrotation.z + dynamicRange;

    var cameraW = Camera.main.gameObject.transform.rotation.w;
    var cameraX = Camera.main.gameObject.transform.rotation.x;
    var cameraY = Camera.main.gameObject.transform.rotation.y;
    var cameraZ = Camera.main.gameObject.transform.rotation.z;

    if (cameraW >= wMinus && cameraW <= wPlus && cameraX >= xMinus && cameraX <= xPlus && cameraY >= yMinus && cameraY <= yPlus && cameraZ >= zMinus && cameraZ <= zPlus && timeOutTimer >= timeOut)
    {
        //Show video
        videoPlayer.gameObject.SetActive(true);
        videoPlayer.Play();
    }
    else
    {
        //Hide Video
        videoPlayer.gameObject.SetActive(false);
        videoPlayer.Stop();
        videoPlayer.frame = 1;
    }

    if (cameraW > wPlus || cameraW < wMinus || cameraX > xPlus || cameraX < xMinus || cameraY > yPlus || cameraY < yMinus || cameraZ > zPlus || cameraZ < zMinus)
    {
        timeOutTimer = 0;
    }

    gameObjectrotation = Camera.main.gameObject.transform.rotation;
}
}

```

Any help would be appreciated! Cheers

# Answer
If you are using the Oculus SDK instead of OpenVR you can check with the proximity sensor of the oculus if somebody is wearing it or not. If I understood your use case right, this would be the preferred solution.

```
OVRManager.HMDMounted += HandleHMDMounted;
OVRManager.HMDUnmounted += HandleHMDUnmounted;

void HandleHMDMounted() {
   // Do stuff
}

void HandleHMDUnmounted() {
   // Do stuff
}

```

This worked for me on a Rift.
> 2 votes

# Answer
Reading the docs on transform.hasChanged, there is no threshold at all:

> Note that operations which can change the transform **will not actually check if the old and new value are different** before setting this flag. So setting, for instance, transform.position will always set hasChanged on the transform, regardless of there being any actual change.

ie. this is just a dirty flag to help you skip unnecessary checks when the transform *couldn't* have changed, not a measure of how much it's changed.

So, if you want to look for *significant* changes, then this is not the correct tool for the job.

Instead, you're better off caching your last known position/orientation in your own script, and updating them / resetting your idle timer anytime the current value is more than a custom threshold away from that cached value.

eg.

```
public float translationThreshold = 0.001f;
public float rotationThreshold = 0.001f;

Vector3 lastPosition;
Quaternion lastRotation;
float idleSeconds;

void Update() {
    var camera = Camera.main.transform;

    bool moved = (camera.position - lastPosition).sqrMagnitude > translationThreshold;
    bool turned = Quaternion.Dot(camera.rotation, lastRotation) < (1f - rotationThreshold);

    if(moved | turned) {
        idleSeconds = 0f;
        lastPosition = camera.position;
        lastRotation = camera.rotation;
    } else {
        idleSeconds += Time.deltaTime;
    }
}

```
> 0 votes

---
Tags: unity, c#, transformation, virtual-reality, oculus
---


title: Why do games have consumables?

text:
# Question
Title: Why do games have consumables?
Thinking along the lines of this question, and the too awesome to use trope in general. Why do game designers *want* to include consumable items in their games?

Mortal Kombat 11 got me thinking... Why include consumables that give you an edge in battle at all?

I’m looking for concrete answers for what it is that consumables add to gameplay, whether it be about those that one can buy with real money, or those that you just get by playing the game, or whether they are available in limited or unlimited quantities.

# Answer
Well, in a roguelike or something, where eventually if you don't use your consumables they expire (because you die, or win), then consumables provide another layer of medium- to long-term strategic planning for the players to think about. Instead of just making sure you use your renewable resources effectively in each encounter, you now can also consider spending consumables per encounter at a sustainable rate, but not too few that you die (and lose all your items).

For some games, consumables are a way to keep players engaged (monetarily-speaking) by letting players buy the same bonus over and over again. Instead of having to keep adding power creep upgrades for your most paying customers to buy (and thus making it so the non-paying players don't even think they have a chance because they're so far behind), you can sell them the same item repeatedly, every time the previous copy they purchased expires.
> 39 votes

# Answer
Consumables can be a way for your player to pass difficulty spikes in your game.

Common game design wisdom is to create a gradually increasing difficulty curve. But when your game is complex and its pacing more driven by narrative than gameplay concerns, then this is easier said than done. So you will often end up with situations which are suddenly far above the difficulty curve.

Imagine your player facing such a challenge at one point of your game and they can not overcome it. They are simply not skilled enough and they don't have the patience to train. This could be the point where the player abandons your game in frustration. Or it could be the point where the player looks through their inventory, consumes every consumable they have which gives them an advantage, passes the challenge and continues with the game.

So consumables are one design element which adds *dynamic difficulty* to your game. When the player is not challenged enough, they will feel inclined to hoard consumables and in turn make the game more difficult for themselves. When the player feels overwhelmed, they will use their consumables to bring the difficulty down.

It is one of the few ways to create dynamic difficulty which is both under the control of the player (unlike automatically making enemies weaker when the player loses) and plausible within the fiction of the game (unlike a difficulty setting in the game options).
> 29 votes

# Answer
In addition to what Foxwarrior said, consumables are a perfect way to include effects that would break your game if they were available all the time. Imagine you make a game level that is exactly balanced with your player abilities, and then some player gains an unlimited healing capability. The balance is right out the window, the level will be too easy, you will have to introduce much harder levels afterwards to account for that healing capability. Worse, in a group of players one will be assigned the boring task of a "Healer".

Give the player a single potion of healing he can consume - the balance stays where it is. It's just a nice one time bonus for emergencies.
> 19 votes

# Answer
In some genres (specially MMORPGs), consumables are used as Money Sinks. They prevent inflation and prevent money to become useless once you have acquired everything buyable that's not consumable.
> 15 votes

# Answer
Consumables can be used as a push-your-luck or risk-reward mechanic. Does the player want to use them now? Or is it better to wait until later? in Foxwarrior example the player gets the consumables at a certain rate and don't want to use them any faster, because if they run out, the player could find themselves in a dire situation. That is a risk to be managed.

For another example, we could design the game with stretches where there is no access to some kinds of consumables, usually accompanied with closing the door behind the player. This will lead to three main behaviors:

* The player would have to manage what they got carefully (do not use much more than needed).
* If the player runs out or is running out of the consumable then the player will advance more slowly. This means the player will pay more attention to their situation and ways to get around without the consumable. This gets the player to try alternatives ways to progress and also increases the duration of the game.
* On failure and retry, the player will probably look for ways to stock on large amounts of the consumable. The design could also leverage that to get the players to explore.

---

Even though it is not what we usually think as a consumable, consider a shooter where the player can run out of bullet (not unheard of). Aside from the behaviors above (preserving bullets, aiming better - or perhap trick shots -, and looking for bullets), it will force the player to try other weapons. That helps ensure that all weapons have a chance to see play. Furthermore, in competitive game-play, trying to make the other player run out of ammo sometimes is a viable strategy.
> 4 votes

# Answer
Consumables add **resource management** to a game. They allow/require a player to manage limited resources, gather, collect and consume them and plan strategically when and how much to focus on it.

The incentive for the player has been detailed in other answers ("ace up the sleeve", mastering spikes, etc.)

The incentive for the game developer is to add this aspect of resource management and thus more depth to a game and it allows the developer to be a bit more lazy. Instead of ensuring that an encounter can always be mastered by the player, adding some consumables to allow the player to overcome even (slightly) overpowered encounters or solve puzzles that require specific values or abilities (that you can alternatively provide through consumables).
> 4 votes

# Answer
It's called having An Ace Up Your Sleeve. Knowing it's there releases endorphins. Using it probably inhibits your serotonin re-uptake.
> 2 votes

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


title: Score multiplier based on lowest time

text:
# Question
Title: Score multiplier based on lowest time
I'm making a score system that will be based on several factors, how many collectibles you have obtained, how few hits you have taken, etc. I want to add in a multiplier based on how quickly the player manages to finish the game.

So far the only thing I've thought of is to have a maximum time, and to subtract the final time from that number. So as an example, say I set the maximum number to 300 seconds and somebody beat the game in 220 seconds, that would leave 80. This could be divided into a smaller number and then used as a multiplier on the total score.

It works but feels a little limited. What would be a better way to achieve this?

# Answer
So it sounds like you want an equation that starts at a large number where t = 0, and approaches 1 as t approaches infinity, yes? For example it would be a multiplier of 10 if they complete the level in 0 seconds, and a multiplier of 1 if they complete the level in infinity seconds. Here’s a starting point:

$$\frac{9}{100 ^ {t/300}} + 1$$

Where t is the amount of time taken, 9 is 1 less than the maximum multiplier (10 in this case), and 100 and 300 can be tuned to adjust how quickly the multiplier approaches 1. With 100 and 300, the multiplier moves down from 10 to 2 at about 150 time units, and is very close to 1 at 300 time units.
> 1 votes

# Answer
You can use this formula:

$$\frac{t\_{half}}{t\_{half} + t} \cdot {x}$$

If *t* = 0, score equals to *x*, the maximum score.
If *t* = *thalf*, score equals to half of *x*.
If *t* goes to infinity, score goes to 0.
> 1 votes

---
Tags: algorithm, scoring
---


title: UE4 Error lighting needs to be rebuilt

text:
# Question
Title: UE4 Error lighting needs to be rebuilt
I opened a blank project that came with two types of flooring, a table with two chairs and a statue.

The only things I modified was the size of one of the floors and the texture of the two floors.

When I did this, the following message appeared: **LIGHTING NEEDS TO BE REBUILT (2 unbuilt objects)**

**I clicked on the option below (Compile Only Lighting):**

**Compilation failed (view image below), the following error appeared (0xc000007b):**

Note that the Swarm Agent is working.

I restarted the program several times. I cleared the cache. I fixed the program. I started a new project. All this did not result in anything.

**Below are some links that I researched and tried to solve the problem, doing almost everything I was told:**

https://answers.unrealengine.com/questions/201327/lightning-build-failed-swarm-failed-to-kick-off.html

https://answers.unrealengine.com/questions/12975/unreal-engine-wont-launch-error-code-0xc000007b.html

# Answer
> 1 votes
**I do not remember exactly what modification I did on my computer, but when I tried to open the UE4 the following error appeared:**

*(image taken from the internet)*

It is not the first time that this error occurs, but there I went to solve it again (If I remember correctly I deleted the folder with the libraries (.dll) that resolved it the first time, so I had to download it again):

But before, a poetic pause... One day Albert Einstein said: ***Insanity is to keep doing the same thing and expect different results***.

So this time I looked for another place to try to solve this error, :

(**VIDEO LINK**) =\> https://www.youtube.com/watch?v=kA4N0x4iG54

In this video the man orders to download a compressed file that contains three folders.

(**COMPRESSED FILE**) =\> http://www.mediafire.com/file/at50mz3rkobxe4i/Erro+0xc000007b.rar

You should copy all libraries from the first folder and paste them into the sytem32 folder (if your system is 32-bit) and the system32 and SysWOW64 folders (if your system is 64-bit).

**Your pasting must be of the type that replaces existing files:**

**You will need to give administrator permission for the computer to do this:**

**There will be an "error", you select the "do this for all current items" box and then click ignore:**

**Once you click Ignore you will notice that there are numerous selected files. Press the delete key and enter to delete them (again you will have to provide administrator permission):**

NOTE =\> **For users of a 64-bit computer, you will have to do this in both folders (system32 and SysWOW64).**

In the second folder of the file that the video man made available has the directX installer. **I RECOMMEND NOT TO USE, BECAUSE WITH ME IT DID NOT WORK.** I even had to reinstall directX.

(**OFICIAL LINK OF DIRECTX**) =\> https://support.microsoft.com/pt-br/help/179113/how-to-install-the-latest-version-of-directx

**Just install DirectX.**

In the third folder of the file that the video man provided, there is another installer (all versions of Visual Studio) that also did not work for me.

(**OFICIAL LINK 64-bit**) =\> https://www.microsoft.com/pt-br/download/confirmation.aspx?id=36805

*Sorry, I downloaded 32-bit too, but I can not find the link.*

**Just install all versions of Visual Studio from Microsoft.**

That way I killed two birds with one stone.

**The lighting build works and the error has been fixed.**

---
Tags: lighting, unreal-4
---


# Question
Title: 2D vehicle collision detection and rotation
I'm attempting to make a simple 2D car game from scratch, but I can't figure out the collision detection between a vehicle and a road. The vehicle should also rotate appropriately to its position on the road, as following (the vehicle is a rectangle and the road is a curve.):

As you can see, the vehicle collides with the road (but before it's being drawn, so that a user doesn't see that collision). Once the intersection is detected, the vehicle needs to be pushed away and rotated appropriately, as it's driving upwards:

The problem is the vehicle may have any rotation (assuming it won't be so fast to go through the road, missing the collision detection), as well as the road's curve may be directed towards any axis, making the algorithm hard to cover any possible situation.

Have you any idea how to achieve that?

# Answer
> 0 votes
The answer is there's no silver bullet. You're doing discrete physics, and therefore you're missing a lot of information. For example you don't know which point on the car collided first, you can only make the assumption it's the deepest point. You also don't know 100% which part of the road that point hit. In your above drawing, you can only assume based on the car's velocity it was probably the inclined portion as the car moved forward into it. In general game physics just needs to look close to right. It appears you're fairly familiar with the base concepts of realtime physics simulation, but here's a great resource to help solidify those foundations: https://www.toptal.com/game/video-game-physics-part-i-an-introduction-to-rigid-body-dynamics

If you continue with discrete physics i'd recommend sitting down and thinking about what edge cases you might encounter, what information you have, and how you can use that information to iron out as many situations as possible. Start with the general case, then add exceptions in your algorithm until it's mostly right. If your game has only a few cars, you might consider implementing continuous detection using Conservative advancement. This method has some bad worst-case scenarios, but if you only have 10-20 cars you're very unlikely to see this have a huge impact. Erin Catto, the maker of box2D, has a great talk on his take with conservative advancement which he calls Bilateral Advancement. Here's some resources to get you started on those topics.

Conservative Advancement: https://wildbunny.co.uk/blog/2011/04/20/collision-detection-for-dummies/

Erin Catto GDC Talk: https://www.youtube.com/watch?v=7\_nKOET6zwI

---
Tags: 2d, collision-detection, mathematics, side-scroller
---


# Question
Title: Spawning player at a certain point after a new scene was loaded
I have a Game Manager with a DontDestroyOnLoad function on it, before loading a scene I'm passing the variables needed to reset players position to a certain position. This is what my code looks like;

```
public IEnumerator LoadingNextLevel(int levelToLoad, string spawnPoint)
{
    pState.movingToNextLevel = true;
    fadeToBlack.SetTrigger("FadeOut");

    yield return new WaitForSeconds(0.5f);
    SceneManager.LoadScene(levelToLoad);
    fadeToBlack.SetTrigger("FadeIn");
    pState.movingToNextLevel = false;
    if (spawnPoint == "Red")
    {
        player.transform.position = GameObject.FindGameObjectWithTag("Red").transform.position;
    }
    else if (spawnPoint == "Blue")
    {
        player.transform.position = GameObject.FindGameObjectWithTag("Blue").transform.position;
    }
}

```

This doesn't give me any error, nor it does the job. What am I doing wrong?

# Answer
A few different ways to handle but being this is in your persisting gamemanager code you can just add the async operation and first make sure the level is loaded. then you can find and set the spawns then change the positions.

```
public IEnumerator LoadingNextLevel(int levelToLoad, string spawnPoint)
{
    pState.movingToNextLevel = true;
    fadeToBlack.SetTrigger("FadeOut");

    yield return new WaitForSeconds(0.5f);
    AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(levelToLoad);
    fadeToBlack.SetTrigger("FadeIn");
    pState.movingToNextLevel = false;
    // Wait until the asynchronous scene fully loads
    while (!asyncLoad.isDone)
    {
        yield return null;
    }
    if (spawnPoint == "Red")
    {
        player.transform.position = GameObject.FindGameObjectWithTag("Red").transform.position;
    }
    else if (spawnPoint == "Blue")
    {
        player.transform.position = GameObject.FindGameObjectWithTag("Blue").transform.position;
    }
}

```
> 1 votes

---
Tags: unity, c#, 2d, scene
---


# Question
Title: Unity - adding camera constraint to prevent the player from seeing beyond the scene
Like the title says, I'm after some kind of constraint for the camera to prevent the player from seeing beyond the scene and seeing the Skybox. I came across the code to add a `Mathf.Clamp`, but I can't get it to work.
I'm currently trying to make a 2.5D platformer in which the camera follows the player (ahead), which leads to seeing beyond the scene to the far left and right. I already have an invisible wall in place to prevent the player from falling off, but I would love to also clamp the camera from going any further.

This is the script I have at the moment:

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

public class CameraController : MonoBehaviour
{
    [SerializeField] GameObject player = null;
    [SerializeField] [Range(0.1f, 2f)] float followAhead = 2f;
    [SerializeField] [Range(0.1f, 2f)] float smoothing = 1f;

    //public PlayerController playerController;

    private float minPosition = -9.37f;
    private float maxPosition = 4.68f;
    private Vector3 cameraClamp;

    const float m_minY = 2f;
    Vector3 targetPosition;
    Vector3 cameraOffset;

    void Start()
    {
        cameraOffset = transform.position - player.transform.position;
    }

    void Update()
    {
        targetPosition = (player.transform.position + (player.transform.forward * followAhead)) + cameraOffset;
        //smoothedForward = Vector3.MoveTowards(smoothedForward, playerController.GetTravelDirection(), 0.5f * Time.deltaTime);
        //targetPosition = (player.transform.position + (smoothedForward * followAhead));
        //transform.position = player.transform.position + cameraOffset;
        targetPosition.y = Mathf.Min(targetPosition.y, m_minY);
        transform.position = Vector3.Lerp(transform.position, targetPosition, smoothing * Time.deltaTime);
        cameraClamp.x = Mathf.Clamp(transform.position.x, -9.37f, 4.68f);
    }
}
```
</code></pre>

# Answer
> 1 votes
When clamping the camera to your bounds, you want to make sure to re-assign the position like so:

```
// Set these in the inspector to tune your bounds.
public Vector3 MinCamPosition;
public Vector3 MaxCamPosition;

void Update()
{
    transform.position = new Vector3(
        Mathf.Clamp(transform.position.x, MinCamPosition.x, MaxCamPosition.x),
        Mathf.Clamp(transform.position.y, MinCamPosition.y, MaxCamPosition.y),
        Mathf.Clamp(transform.position.z, MinCamPosition.z, MaxCamPosition.z)
    );
}

```

Or you can use `Vector3.Min`/`Max` to express this more concisely:

```
    transform.position = Vector3.Max(
        MinCamPosition,
        Vector3.Min(MaxCamPosition, transform.position)
    );

```

---
Tags: unity, c#, camera, skybox
---


# Question
Title: How to solve problem with Terrain Flashing and then disappears when flying away?
I am making flight simulator( my first Unity project) , the biggest challenge so far is terrain, so whenever I fly away from it (not that far) the terrain starts flashing and disappears which is just green mountains, so when i come back to it, i have no idea where its position is, but it suddenly appears (again flashing) when I am close , the terrain size is normal but it's on top of a huge other terrain (about 100,000 * 100,000 which is the max),I tried changing pixel error and base map distance, no change, I looked at big terrain solutions online, but non of them really helped me, Any advice? Thanks

# Answer
> 0 votes
It has been a while since I asked this question, I remember that I found a solution (may or may not work for you), and wanted to share it anyway.

None of the intensity number setting worked for me, what I ended up doing is that since I originally have the terrain on top of the ocean (a large radius body of water that I put), the ocean ends up appearing at high altitude and the terrain disappears, the solution is to simply not place the terrain over water, so I had four bodies of water intersecting at the for edges of my terrain instead of one body of water where the terrain sits, therefore there is nothing below the terrain, it doesn't flash or disappear at higher altitude anymore.

# Answer
> 0 votes
The only solution I've seen(though it may not work well for a flight simulator) I've seen with messed up terrain in the distance is to add a fog, to mask the messed up terrain in the disatnce. Go to lighting tab, and it should be close to the bottom of the lighting tab. You simply click it on, though make sure it's intensedy is super low(0.001) so what the player sees isn't just a bunch of fog when flying. I hope this helped in making the essed up terrain invisible.

---
Tags: unity, terrain, resolution, terrain-rendering
---


# Question
Title: Why are my records duplicated when writing them to a file?
I am writing data to a file every two seconds. I used InvokeRepeating and everything is Ok except that every record is saved 3 times in the file:

```
void Start(){
    File.WriteAllText(filePath_users, "timestamp" + "," + "id" + "," + "pos" + "," + "rot" + System.Environment.NewLine);
    InvokeRepeating("SaveUsersTracking", 1.0f, 2.0f);
}

void SaveUsersTracking(){
    //save this data every two seconds...
    File.AppendAllText(filePath_users, System.DateTime.Now.ToString() + "," + "U1" + "," + "(-2.7, 1.3, -1.8)" + "," + "(0.2, -0.7, 0.2)" + System.Environment.NewLine);
}

```

My results look like:

```
timestamp,id,pos,rot
4/20/2019 8:09:47 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)
4/20/2019 8:09:47 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:47 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:49 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)
4/20/2019 8:09:49 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:49 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:51 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)
4/20/2019 8:09:51 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record
4/20/2019 8:09:51 PM,U1,(-2.7, 1.3, -1.8),(0.2, -0.7, 0.2)//I don't need this record

```

# Answer
> 1 votes
Remove the `2.0f` from the end of `InvokeRepeating` The second argument is a repeat rate so it is saving it 3 times (the executed plus the 2 repeats).

```
void Start(){
    File.WriteAllText(filePath_users, "timestamp" + "," + "id" + "," + "pos" + "," + "rot" + System.Environment.NewLine);
    InvokeRepeating("SaveUsersTracking", 1.0f);
}

void SaveUsersTracking(){
    //save this data every two seconds...
    File.AppendAllText(filePath_users, System.DateTime.Now.ToString() + "," + "U1" + "," + "(-2.7, 1.3, -1.8)" + "," + "(0.2, -0.7, 0.2)" + System.Environment.NewLine);
}

```

---
Tags: unity, file
---


# Question
Title: Multi-level 3D grid based pathfinding in Unity
I'm trying to come up with a way to pathfind on multiple levels. See image:

The orange walls would be considered a ladder, connecting you to the upper levels.

At first I thought of looking at it as though it were top down 2d, but I also need to be able to go under things at some point. How can I compute these paths?

# Answer
> 1 votes
Pathfinding in general is a graph searching problem. Since you are doing a grid based solution, Unity's nav mesh might not be what you want. You should look into A\* search as there's many resources out there for it. Your graph has nodes and directional edges. Wherever your character can stand and occupy space is a node (each block face in your 3D world) and each edge is a link showing the character can move from one block face to the next. Assuming you know A\* given your mention of 2D pathfinding, your problem boils down to, how can I get a graph representation of my game world. Assuming you have some data structure holding all the data of where blocks are placed (a 3D array with true/false for example) you can figure out how they are connected. 2 blocks adjacent to eachother on a flat surface means their top faces are linked in your navigation graph. A block placed above an adjacent block (i.e. 1 to the right and one up of another block) means the other block's top face connects to that block's side face IF there's a ladder. You can continue this logic until you have a script that builds a graph representation of your world. Then just run A\*

---
Tags: unity, c#, 3d, path-finding, grid
---