# Question
Title: unity 3d mouselook script help, weird issue
I'm coming back to Unity after a year or two of busy college and I'm having to relearn everything I've forgotten. One thing I cant seem to get right is this basic mouselook script I wrote. Here is the code:

```
    float x;
    float y;
    public float sensitivity = 75.0f;
    public float maxVerticalAngle = 75.0f;
    public Rigidbody Character;

    void Awake()
    {
        Vector3 euler = transform.rotation.eulerAngles;
        x = euler.x;
        y = euler.y;
    }

    // Update is called once per frame
    void Update()
    {
        x += Input.GetAxis("Mouse Y") * (sensitivity * Time.deltaTime);
        y += Input.GetAxis("Mouse X") * (sensitivity * Time.deltaTime);
        x = Mathf.Clamp(x, -maxVerticalAngle, maxVerticalAngle);

        //apply this just to the camera and it works
        transform.rotation = Quaternion.Euler(-x, y, 0.0f);

        //apply x changes to camera and y changes to parent rigidbody capsule and it no longer works correctly
        transform.rotation = Quaternion.Euler(-x, 0.0f, 0.0f);
        Character.transform.rotation = Quaternion.Euler(0.0f,y,0.0f);
    }

```

Okay, now at the end is where my problem occurs. Let me explain a little: if I apply the quaternion with both x and y changes to the rotation then it works smoothly and the camera rotates on both axes. If, however, I apply the change in x to the camera to allow looking up and down, and I apply the change in y to the rigidbody capsule I have as a parent to the camera the script is attached to then I get a weird problem. The camera rotates up and down smoothly, but the capsule twitches and only rotates a few degrees. If, however, I comment out the line where I apply changes to the camera rotation then the parent capsule rotates normally now.

TL;DR Camera is child to a capsule. When applying rotational changes to the camera and rigidbody one line after the other, the camera rotates fine, but the rigidbody does not. If I comment out the camera's rotation changes then the rigidbody rotates fine again.

I think the problem may be that I'm rotating a parent object to the camera and I'm using mouse movement to rotate the rigidbody. I'm unsure though. Please help.

If you want to recreate what I've done, then child a camera to a capsule and apply the script. Add the capsule to the rigidbody in the script and comment out this:

```
//apply this just to the camera and it works
transform.rotation = Quaternion.Euler(-x, y, 0.0f);

```

Edit: Thank you for the help. If you need more info, then please ask!

# Answer
If you want to rotate the camera up & down *relative to its rigidbody parent* then set its `localRotation` property instead of `rotation`.

By setting the `rotation` field directly to an orientation with no yaw, you're telling Unity you want it to make a compensating rotation that undoes the parent's yaw so the camera can keep looking toward the world forward direction. Since you do this before applying more yaw to the parent, you still see one frame's worth of yaw after this compensation is applied, leading to the stuttery appearance of only rotating a few degrees.
> 0 votes

---
Tags: unity, c#, camera, mouse, first-person-shooter
---


# Question
Title: Creating an animation for materials in code (Unity)
I have a function where you click on an object and it changes the color and emission of a specific material, every object has multiple materials with different order.

```
var emissionColor = mat.GetColor("_EmissionColor");
List<Material> materials.AddRange(t.GetComponent<MeshRenderer>().materials);

 foreach (var m in materials)
    {
        if (m.name.Equals(matName))
        {
            //Debug.Log(m.name);
            m.EnableKeyword("_EMISSION");
            m.color = mat.color;
            m.SetColor("_EmissionColor", emissionColor);

        }
    }

```

So far I'm changing the color once but I would like to have it transition into a different color every 10 seconds, I tried using the animator but it keeps changing the wrong material. Is there a way to do this animation in code?

# Answer
I didn't want to delete this question because it might help someone else facing this problem. Basically I used the code above in a function (ChangeColor) that I call twice with a different mat every time. In order to get that delay I used `Invoke("ChangeColor", delay);` for the second time that I change the material's color.
> 0 votes

---
Tags: unity, animation
---


title: How to handle levels in Unity3d

text:
# Question
Title: How to handle levels in Unity3d
I’m making a top-down 2d game in Unity3D for Android-based smartphones. Currently I have two scenes - a preloader and the game itself with all the stuff I need packed into one scene file. Also there is a very simple game-state-manager in my scene.

My question now is: Is it better to script all the levels within one scene-file or should I seperate them into unique scene-files? I’m just asking because basically the levels are very similar to each one - only the background and the sprites are different. Is there a problem with memory management if I use one scene only?

# Answer
> 7 votes
Originally, the intention of Unity was that each level of a game should be an own scene. That's why the method to switch to a different scene used to be Application.LoadLevel (nowadays, you should use SceneManager.LoadScene instead).

You can of course still use that paradigm. The advantage of this method is that you have a very short test-cycle. You can load and edit a level in the Unity scene editor and test-play it just by pressing the play-button.

But many games use a different architecture: Just one general "Play" scene which instantiates the level at runtime.

The information about the level can be loaded from a custom file format. The play scene would have some controller which loads that file and instantiates the necessary objects based on the information in it.

You can also create each level as one prefab and then instantiate the level-prefab from your play scene.

When you wonder which one of these paradigms you should use for your game, consider the following points:

* How important is an instant test-cycle for you? Yes, we all love short test cycles, but are you sure you can keep it that short with reasonable effort?
* How much stuff do you have in every single level which is always identical? If it's a lot of stuff, then adding it again for every new level can be quite tedious.
* How often do you have something in a level which is completely unique to that level? If you do this often, then it might make sense to use separate scenes for levels.
* Is the Unity scene editor the right tool for building levels for your game or would it be a worthwhile investment to use a separate level editor? If you go this route, you will likely end up with a one-scene architecture.
* Do you want baked lightmaps for your levels? Then you will need one scene per level, because lightmap baking only works for individual scenes, and all the objects you want to bake into the lightmap need to be present in the editor.

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


# Question
Title: How can I generate vertex data from an SVG?
I am trying out the Phaser game engine, and am interested in making a vector graphics game (simple black and white like *Asteroids*), but I want to use vector graphics instead of raster PNGs.

I was looking at this example, which looks like what I want to do...

Where I am stuck is, say I draw a simple Asteroids style ship in Illustrator, consisting of 3 connected lines. How do I export that data into an array of vertices that would work with the `setPolygon()` method in Phaser/Box2d?

# Answer
Perhaps the following function (it's JavaScript) could help you.

The first parameter is an element of type SVG, it can be a path, rect, circle, etc. The second parameter is the distance of segments. Returns an array as a javascript object, which is generally used in Phaser or matter js.

```
function toVertex(pathSVG, n){
  let pathLength = pathSVG.getTotalLength();
  let vtx = [];
  var i = 0;
  while(i < pathLength){
    let arr =  pathSVG.getPointAtLength(i);
    vtx.push({x:arr.x, y:arr.y});
    i+=n;
  }
  return vtx;
}

```
> 1 votes

---
Tags: box2d, phaser, vector-art
---


# Question
Title: Spherecast - enabling MeshRenderer of selector target around prefabbed object once hit and disabling Meshrenderer when not hit anymore
I have an interesting problem - I have been looking up for solutions on this but I think there is something I am missing and I require a little more knowledge.

I have a scene and the scene has an Oculus OVRRig set up. I have a script with sphereCast connected to the right hand. This Spherecast shoots out to select a particular layer. This is all working fine.

I have also the setting of an alpha color on the cross hair brings up the object when the SphereCast hits.

It is up until here it all works fine. It is here I reiterate that my object is a spawned prefab - which seems to be causing trouble. I say this because I cannot select and change the material of the crossHair as it affects all the prefabs.

I simply cannot deactivate it once the SphereCast stops pointing at it.

Two Pieces of code. The first sets up the sphere cast - attaches to a specific target and sets up a bool - Switcher - for the next scene to allocate the MeshRenderer for the crosshair.

```
public float radius;//For the radius of the SphereCast
public LayerMask LayerMask1;//The current Layer I use for focusing on the Raycasting Objects
public float MaxtDistance;// The Overall reach of the Spherecast

public GameObject currentHitObject;
public Vector3 up;
public RaycastHit hit;
public Vector3 startPos;
public int moveSpeed;
public bool TransitionSwitcher = false;
public bool Switcher = false;

void Update()
{
    startPos = transform.position;
    up = transform.forward;

    if (TransitionSwitcher)
    {
        StartCoroutine(MoveTo());
    }

    if (Physics.SphereCast(startPos, radius, up, out hit, MaxtDistance, LayerMask1, QueryTriggerInteraction.UseGlobal))
    {
    //    Transform target = hit.collider.transform.GetChild(2).GetChild(0);
     //   target.GetComponent<MeshRenderer>().enabled = true;
        // OVRInput.SetControllerVibration(0.3f, 0.3f, OVRInput.Controller.RTouch);
        TransitionSwitcher = true;
        Switcher = true;
        currentHitObject = hit.transform.gameObject;
    }
    else
    {
        OVRInput.SetControllerVibration(0.0f, 0.0f, OVRInput.Controller.RTouch);
        Switcher = false;
    }

}
IEnumerator MoveTo()
{
    hit.collider.gameObject.transform.position = Vector3.Lerp(hit.transform.position, startPos, Time.deltaTime * moveSpeed);
    TransitionSwitcher = false;
    yield return null;
}

```

This second piece of code takes the Bool Switcher from the code above and either switches on or off the renderer. I know why it isn't working properly in this - it allocates the boolean to all the prefabs this is attached to.

```
public GameObject cube;
public GameObject crossHair;
public bool result = false;

// Use this for initialization
void Start()
{
    cube = GameObject.FindWithTag("Player");
    crossHair.GetComponent<MeshRenderer>().enabled = false;
}

void Update()
{
    bool result = cube.GetComponent<Sphere2>().Switcher;
    print(result);

    if (result == true)
    {
        print("on");
        OVRInput.SetControllerVibration(0.3f, 0.3f, OVRInput.Controller.RTouch);
        crossHair.gameObject.GetComponent<MeshRenderer>().enabled = true;
    }
    else if (result == false)
    {
        print("off");
        OVRInput.SetControllerVibration(0.0f, 0.0f, OVRInput.Controller.RTouch);
        crossHair.gameObject.GetComponent<MeshRenderer>().enabled = false;
    }
}

```

Can anyone point me in the right direction with this? It doesn't have to be the solution handed to me - rather how do I turn specific meshrenderers on and off when my spherecast hits them and leaves their reach respectively?

# Answer
I fixed it in a Eureka but feeling dumb moment. So maybe this will be useful to someone out there - so they don't spend an entire day on it too.

I used a temp variable. Boy don't I feel silly.

Anyways here's the code (cut down a little):

```
    public Transform TempTarget;

void Update()
{
    startPos = transform.position;
    up = transform.forward;

    if (TransitionSwitcher)
    {
        StartCoroutine(MoveTo());
    }

    if (Physics.SphereCast(startPos, radius, up, out hit, MaxtDistance, LayerMask1, QueryTriggerInteraction.UseGlobal))
    {
      Transform target = hit.collider.transform.GetChild(2).GetChild(0);
      TempTarget = target;
        target.GetComponent<MeshRenderer>().enabled = true;
        TransitionSwitcher = true;
        currentHitObject = hit.transform.gameObject;
    }
    else
    {
        OVRInput.SetControllerVibration(0.0f, 0.0f, OVRInput.Controller.RTouch);
        TempTarget.GetComponent<MeshRenderer>().enabled = false;//
       // Switcher = false;
    }

}

```
> 0 votes

---
Tags: unity, c#, raycasting, instancing
---


# Question
Title: How do I use guilayout toggle event to check if true or false?
```
OnGUI()
{
            for (int i = 0; i < scenes; i++)
            {
                GUILayout.Toggle(false, SceneManager.GetSceneAt(i).name);
            }

            if (GUILayout.Toggle(true, "New Scene"))
            {
                Debug.Log("True now !");
            }
}

```

First in the loop I'm adding some toggles. Then I want to do that if specific toggle is checked(true) do something and if unchecked(false) do something else.

But the way I did it it's just changing the toggle to true automatic.

# Answer
> 0 votes
The idiom with most of these GUI controls is to store a member variable representing the current state / value held inside the control. When you draw the control, you pass that variable so that it's drawn in the correct state. The function then returns the new value of the variable based on user input.

```
bool isToggleChecked;

void OnGUI() {
    isToggleChecked = GUILayout.Toggle(isToggleChecked, "Toggle Name");

    if(isToggleChecked) {
        // What to do if the toggle is in the checked state
    } else {
        // What to do if the toggle is in the unchecked state
    }
}

```

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


# Question
Title: Unity - DontDestroyOnLoad - FindObjectsOfType(GetType()).Length is always returning 1
I'm trying to have an object with the `DontDestroyOnLoad` property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs.

This answer suggests the following code:

```
public void Awake()
{
    DontDestroyOnLoad(this);

    if (FindObjectsOfType(GetType()).Length > 1)
    {
        Destroy(gameObject);
    }
}

```

Despite this, I still end up with duplicate objects. `FindObjectsOfType(GetType()).Length` is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy.

I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but `GameObject.Find("ObjectNameHere(Clone)")` is always returning false. However, the above solution seems simpler so I'd prefer to figure out `FindObjectsOfType(GetType()).Length`.

# Answer
You better use Singleton pattern which ensures that object will exist in in a single copy:

```
public class ExampleClass: MonoBehaviour {
    public static ExampleClass instance = null;

    void Start () {
        if (instance == null) {
            instance = this;
        } else if(instance != this){
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);

        InitializeManager();
    }

    private void InitializeManager(){
        // TODO: add initialization code here
    }
}

```

And you don\`t even need to use heavy FindObjectsOfType() method.
> 2 votes

# Answer
Try this. It compares time alive on different instances of the class, ensuring that your first instance will be the one that survives.

```
public class ExampleClass : MonoBehaviour {

    float time = 0;

    void Awake () {
        DontDestroyOnLoad(this);
    }

    void Update () {
        time += Time.deltaTime;
    }

    private void OnLevelWasLoaded(int level)
    {
        foreach (ExampleClass classInstance in FindObjectsOfType<ExampleClass>())
        {
            if (classInstance.time < time)
            {
                Destroy(classInstance);
            }
        }
    }
}

```

Hope this helps. It's not the way you would like, but it is functional.
> 1 votes

---
Tags: unity, c#, unity-networking, instancing, unet
---


# Question
Title: Get the length of an animation from the Animator
How do find the length of an animation that is included in the Animator attached to a GameObject?

# Answer
> 0 votes
The only way I could find to do it by name is to iterate through the animations:

```
var animController = GetComponent<Animator>().runtimeAnimatorController;
var clip = animController.animationClips.First(a => a.name == "[The animation's name]");
Debug.Log(clip.length);

```

A constant time solution is to use an instance variable:

```
public AnimationClip clip;

void Start () {
    Debug.Log(clip.length);
}

```

# Answer
> 0 votes
```
   float GetAnimationClipLength(Animator animator, int clipIndex){
   return animator.runtimeAnimatorController.animationClips[clipIndex].length;
   }

```

clips indexes are in the order they were added to the animator controller, ex: index = 0 it's the very first clip added to the animator.

clips refer to the actual animation files, not the states of the animation state machine. Of course, if you put an index value either negative or greater than animationClips.Length -1( the number of clips in the animator controller) it will throw Array out of Range error.

---
Tags: unity
---


# Question
Title: How is entering cover animation done for cover system?
I am trying to create a cover system for my 3rd person shooter game in Unity.

My implementation is a basic one :

```
On Player enter Trigger
  Player move to preset cover position
  Player play Enter Cover animation (eg: dash to cover)

```

This is fine without root motion enabled, when it is enabled (so the movements look natural), instead of dash & stop behind the cover, the Player will dash and stuck himself inside the cover (due to root motion). So I am curious, what is a good way to do the animation for cover system?

# Answer
> 1 votes
If you're relying entirely on root motion to move your character's correctly, you have to ensure the character is in a precise spot before triggering the animation -- if your "hide in cover" animation displaces a character's center to the left two feet, their center must be two feet (plus their radius) away from the cover to start with. Otherwise they'll clip into the local geometry.

The simple option is to just adjust the displacement in the animation and/or adjust the starting position in the world where you trigger the animation (your "preset cover position").

If you rely only on root motion, though, you have to do a lot of precise positioning of the "cover positions" and such, and that can be tedious to maintain. Your distances must all be fixed according to the distances in the animation, and that constrains your options for actual environment art.

Instead, you can disable root motion temporarily to "line the character up" by interpolating their rotation and position. If they're far away, use a root-motion based locomotion action to get them within a reasonable tolerance, and then interpolate them with root motion disabled to position them precisely, and then re-engage root motion to do the "hide."

You can still play the same animations without root motion -- up to a certain threshold, the player won't notice some slight footsliding or misalignment of the animation versus the ground, especially if it happens quickly or there's a camera cut to help mask it.

---
Tags: unity, animation
---


# Question
Title: Authorization in scaling multiplayer game
I have an architectural problem associated with authorization.

I'm making an MMORPG multiplayer mobile game without separation onto different servers. What I mean by that is that a player from USA could have a mission with someone from China.

Currently I have an authentication microservice that issues JWT tokens. Another types of microservices are game microservices that handles all game logic. By design they would scale to meet the demand.

Every account can have multiple characters created, but only one can be online at the time.

**My question is**: How can I ensure that only 1 character can be online? Do I attach selected character to JWT? But the player can request another JWT with another character and the previous one would be valid as well until it expires. In this case I would need to look up database with every request, but that defies the purpose of JWT. Should I be using JWT or is there another way authorize players?

# Answer
> 1 votes
FWIW I've never used JWT on any MMO or online game I've worked on, nor have I seen it used for such. Because of the issues you note in your question, it doesn't sound like the right tool for the job (or at least, it isn't the right tool *on its own*).

Generally, you'd simply boot the older connections when a newer connection came in. The method you use to authorize the connections doesn't really matter. You should authorize them *somehow* but beyond that, it shouldn't be too much of an issue.

In your server logic when you detect a new, valid connection from an account you simply disconnect any existing connections from that account elsewhere. You can do this before you complete the handshaking for the new connection that puts the player into the game proper.

It's probably better to do this proactively, rather than (say) invalidating the "token" used for the earlier sessions and *waiting* for them to disconnect as a result of trying to send data across an unauthenticated connection. It makes for a better user experience (you can specifically say on the disconnected client that it was "disconnected because you connected elsewhere"), and it minimizes the amount of time the account is connected from two locations.

You generally do *not* want to take an approach where you deny subsequent connections until the first connection goes away (the inverse of the above). This annoys players who accidentally leave their client running at home, go on vacation, and then can't play from their laptop until they go home again to disconnect the old session (or wait for it to time out or hope for the power to go out or whatever).

---
Tags: architecture, authentication
---


# Question
Title: Projectile Not Correctly Inheriting Parent Velocity (Unity3D)
I am trying to fire projectiles from a player who is moving at very high speeds. The issue is that the bullets do not seem to inherit the angular velocity. If the player is moving in a straight line at 500 U/s, then the bullet correctly inherits that velocity and adds its own speed onto that:

```
GameObject bullet = Instantiate(projectile, gun.transform.position, gun.transform.rotation);
bullet.GetComponent<Rigidbody>().velocity = r.velocity + bullet.transform.forward *bulletSpeed;

```

However, if the player is turning really quickly, it does not inherit the rotational velocity, and the bullet looks like it veers off to the side.

How can I implement this? I tried assigning the angular velocity of the player to the bullet, but this just caused the bullet to spin while moving in the same direction.

Some extra details:

* I am using rigidbody.MoveRotation() to rotate my player, but I manually calculated angularVelocity to assign it to the bullet
* I tried moving the player with AddTorque(), but could not produce any results with the bullets

# Answer
We can slightly improve the perceived course of the projectile by taking the velocity of the muzzle of the gun, rather than the velocity of the body's pivot. This will include any sideways linear velocity due to the gun swinging around at an offset from the body's center of mass as the body rotates:

```
// I'd recommend defining your prefab as Rigidbody type, so that you
// can get it directly from the Instantiate without a GetComponent call
Rigidbody projectile;

void Fire() {
    Rigidbody bullet = Instantiate(
        projectile,
        gun.transform.position,
        gun.transform.rotation
    );

    // Inherit not just the linear velocity of the parent's center of mass,
    // but also the sideways motion due to the parent's angular velocity.
    Vector3 inheritedVelocity = r.GetPointVelocity(gun.transform.position);
    bullet.velocity = inheritedVelocity + bullet.transform.forward * bulletSpeed;
}

```

To make this work, you'll need the body to have a valid angular velocity. Assuming you're setting the rotation each frame, you can adapt your existing `MoveRotation` code to use this instead:

```
void MoveRotationWithAngularVelocity(Quaternion rotation) {
    Quaternion delta = rotation * Quaternion.Inverse(r.rotation);

    float angle;  Vector3 axis;
    delta.ToAngleAxis(out angle, out axis);

    // I don't recall the range returned by ToAngleAxis, so this is just to be safe.
    if(Mathf.Abs(angle) > 180f) {
        axis = -axis;
        angle = 360f - Mathf.Abs(angle);
    }

    // Compute an angular velocity that accomplishes this rotation in 1 time step.
    r.angularVelocity = angle * Mathf.Deg2Rad * axis / Time.deltaTime;
}

```

The difference between the normal `MoveRotation` and this one is that the object will keep spinning with inertia on subsequent updates, but if you're setting its rotation each `FixedUpdate` anyway then the angular velocity calculated will naturally go to zero once it arrives at the target rotation.

Note that this will not ensure that the bullet stays in line with the barrel as the barrel continues to rotate through a wide angle. That doesn't happen in real physics: think of a rock released from a spinning sling - the rock inherits the linear velocity of the end of the sling at the moment of release, and zips off in a straight line, not an expanding spiral revolving about the sling's pivot.

If you want to trace such a spiral instead of the normal straight-line trajectory that physics suggests, then you'll need a script on the bullet to apply additional compensating accelerations each frame. If that's what you need, comment and I'll add formulas for calculating those accelerations.
> 1 votes

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


# Question
Title: What verb describes when you hold a joystick to the right or left?
I'm trying to describe a the scenario where you use a joystick to turn the camera. However, I'm struggling to find the word for this. Saying the joystick is "pressed" could mean the joystick is pressed in (as in when you press a playstation controller's joystick and it clicks).

What word describes when a joystick is held in a cardinal direction?

# Answer
> 5 votes
It isn't probably universal, but, as Ferreira said, it is probably **Tilt**. A good bit of Xbox 360 games refer to the action you are describing as "titling the joystick to the \[direction\]".

# Answer
> 2 votes
Another term I've seen before in real games is :

> "**Push** the joystick *{forward, backward, to the left, to the right}*".

Because your thumb makes a push motion in an axis, which most likely will be forward or backward from his point of view, or on the left or the right.

It all depends on your audience and the medium your game is on, but on consoles, this is the better form to make it accessible to casual players.

---
Tags: input, terminology, joystick
---


# Question
Title: How to fix animation event being called twice? Unity
I'm using the ThirdPersonController prefab on Unity and trying to make my character footsteps be heard. To add sound to the character's steps I'm using the animation event method, where I assign a function to a keyframed event. The code for step sound works well. However, every time I move my character the steps are heard twice, even when I stop walking I can heard a second step. I've noticed that the animations have "Loop Time" on them. When I unchecked this option, I can hear the steps correctly but the character won't walk and instead the animation would freeze. I can only walk if I jump and move forward.

The ThirdPersonController code:

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

    namespace UnityStandardAssets.Characters.ThirdPerson
    {
    [RequireComponent(typeof(Rigidbody))]
    [RequireComponent(typeof(CapsuleCollider))]
    [RequireComponent(typeof(Animator))]
    public class ThirdPersonCharacter : MonoBehaviour
    {
        private int count;
        public Text countText;

        [SerializeField] float m_MovingTurnSpeed = 360;
        [SerializeField] float m_StationaryTurnSpeed = 180;
        [SerializeField] float m_JumpPower = 12f;
        [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
        [SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the
    character in sample assets, will need to be modified to work with others
        [SerializeField] float m_MoveSpeedMultiplier = 1f;
        [SerializeField] float m_AnimSpeedMultiplier = 1f;
        [SerializeField] float m_GroundCheckDistance = 0.1f;

        Rigidbody m_Rigidbody;
        Animator m_Animator;
        bool m_IsGrounded;
        float m_OrigGroundCheckDistance;
        const float k_Half = 0.5f;
        float m_TurnAmount;
        float m_ForwardAmount;
        Vector3 m_GroundNormal;
        float m_CapsuleHeight;
        Vector3 m_CapsuleCenter;
        CapsuleCollider m_Capsule;
        bool m_Crouching;
        public bool isStop = false;
        public GameObject destroyedVersion;

        void Start()
        {
            m_Animator = GetComponent<Animator>();
            m_Rigidbody = GetComponent<Rigidbody>();
            m_Capsule = GetComponent<CapsuleCollider>();
            m_CapsuleHeight = m_Capsule.height;
            m_CapsuleCenter = m_Capsule.center;

            m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
            m_OrigGroundCheckDistance = m_GroundCheckDistance;
            count = 0;
            SetCountText();

        }

        public void Move(Vector3 move, bool crouch, bool jump)
        {
            if (isStop) {

                m_Rigidbody.velocity = Vector3.zero;
                m_ForwardAmount = 0f;
                m_TurnAmount = 0f;
                UpdateAnimator(move);

                return;

            }

            // convert the world relative moveInput vector into a local-relative
            // turn amount and forward amount required to head in the desired
            // direction.
            if (move.magnitude > 1f) move.Normalize();
            move = transform.InverseTransformDirection(move);
            CheckGroundStatus();
            move = Vector3.ProjectOnPlane(move, m_GroundNormal);
            m_TurnAmount = Mathf.Atan2(move.x, move.z);
            m_ForwardAmount = move.z;

            ApplyExtraTurnRotation();

            // control and velocity handling is different when grounded and airborne:
            if (m_IsGrounded)
            {
                HandleGroundedMovement(crouch, jump);
            }
            else
            {
                HandleAirborneMovement();
            }

            ScaleCapsuleForCrouching(crouch);
            PreventStandingInLowHeadroom();

            // send input and other state parameters to the animator
            UpdateAnimator(move);
        }

        void ScaleCapsuleForCrouching(bool crouch)
        {
            if (m_IsGrounded && crouch)
            {
                if (m_Crouching) return;
                m_Capsule.height = m_Capsule.height / 2f;
                m_Capsule.center = m_Capsule.center / 2f;
                m_Crouching = true;
            }
            else
            {
                Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
                float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
                if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
                {
                    m_Crouching = true;
                    return;
                }
                m_Capsule.height = m_CapsuleHeight;
                m_Capsule.center = m_CapsuleCenter;
                m_Crouching = false;
            }
        }

        void PreventStandingInLowHeadroom()
        {
            // prevent standing up in crouch-only zones
            if (!m_Crouching)
            {
                Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
                float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
                if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
                {
                    m_Crouching = true;
                }
            }
        }

        void UpdateAnimator(Vector3 move)
        {
            // update the animator parameters
            m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
            m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
            m_Animator.SetBool("Crouch", m_Crouching);
            m_Animator.SetBool("OnGround", m_IsGrounded);
            if (!m_IsGrounded)
            {

                m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);

            }

            // calculate which leg is behind, so as to leave that leg trailing in the jump animation
            // (This code is reliant on the specific run cycle offset in our animations,
            // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)

            float runCycle =
                Mathf.Repeat(
                    m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
            float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
            if (m_IsGrounded)
            {
                m_Animator.SetFloat("JumpLeg", jumpLeg);
            }

            // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
            // which affects the movement speed because of the root motion.
            if (m_IsGrounded && move.magnitude > 0)
            {
                m_Animator.speed = m_AnimSpeedMultiplier;
            }
            else
            {
                // don't use that while airborne
                m_Animator.speed = 1;
            }
        }

        void HandleAirborneMovement()
        {
            // apply extra gravity from multiplier:
            Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
            m_Rigidbody.AddForce(extraGravityForce);

            m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;

        }

        void HandleGroundedMovement(bool crouch, bool jump)
        {
            // check whether conditions are right to allow a jump:
            if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
            {
                // jump!
                m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
                m_IsGrounded = false;
                m_Animator.applyRootMotion = false;
                m_GroundCheckDistance = 0.1f;
            }
        }

        void ApplyExtraTurnRotation()
        {
            // help the character turn faster (this is in addition to root rotation in the animation)
            float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
            transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
        }

        public void OnAnimatorMove()
        {
            // we implement this function to override the default root motion.
            // this allows us to modify the positional speed before it's applied.
            if (m_IsGrounded && Time.deltaTime > 0)
            {
                Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;

                // we preserve the existing y part of the current velocity.
                v.y = m_Rigidbody.velocity.y;
                m_Rigidbody.velocity = v;
            }
        }

        void CheckGroundStatus()
        {
            RaycastHit hitInfo;
#if UNITY_EDITOR
            // helper to visualise the ground check ray in the scene view
            Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
#endif
            // 0.1f is a small offset to start the ray from inside the character
            // it is also good to note that the transform position in the sample assets is at the base of the character
            if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))
            {
                m_GroundNormal = hitInfo.normal;
                m_IsGrounded = true;
                m_Animator.applyRootMotion = true;
            }
            else
            {
                m_IsGrounded = false;
                m_GroundNormal = Vector3.up;
                m_Animator.applyRootMotion = false;
            }
        }
        void OnTriggerEnter(Collider other)
        {
            if (other.gameObject.CompareTag("Puntos"))
            {
                other.gameObject.SetActive(false);
                count = count + 1;
                SetCountText();
                AudioSource source = GetComponent<AudioSource>();
                source.Play();
            }

        }
        void SetCountText() {
            countText.text = "Count: " + count.ToString();
        }

```

Steps code:

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

public class PlayerSound : MonoBehaviour {

    public AudioClip pisadita;
    public AudioSource audioS;

    /*// Use this for initialization
    void Start () {

    }

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

    }*/

    void Pisar()
    {
        //audioS.Play();

        audioS.PlayOneShot(pisadita);
    }
}

```

How could I fix either the ThirdPersonController code to have animations without the need of "Time Loop" or having my animation events not being played twice?

Thanks!

# Answer
When you have something like an animation event such as a sound and it returns twice each time it should happens once, it means that there's is potentially something wrong with one of the following things:

• 2 Animations with an Event calling the same method happens at the same time. This is a typical thing when you got a run and a walk animation blended (with a Blend Tree) in the animator layout. When you have a blend tree with 2 or more animations, if any of those animation have even just a tiny bit of weight, their events will play.

Considering that your use float(s) to manage a Blend Tree, the chance that 1 of 2 blended animation in a Blend Tree nod reach a perfect 0 is close to impossible. You might have noticed sometimes 0 (zeroes) becomes something like *0.0234e0392* or the likes of that? That's called Float Precision where the 2 last digits of a float can be wrong by a few units each frame it's used. In terms of Unity Animator's Blend Tree, the same Float Precision issue happens and you might have 1.0000001 instead of 1 in speed which means the animation is a blend of 0.00000009% Running and 99.9999999% walking or vise-versa. Even at 0.0000009% of Running, the even in the Running will still be called. This means that the Event calls (which calls for the step sound) will play in the walking and running animation that are blended together.

How can you fix this? These are 2 possible ways:

1. Don't use Animation Event with Blended animations to produce the sounds themselves. What I usually do is using a kind of Boolean double-checking pattern. I use a script that has something like 2 Boolean called CanStepL and CanStepR turned False by default. In the animation, I set an Event Call that turn that CanStedR to true at precise times when the right foot is lifted from the ground and CanStepL when it's the left foot that is lifted. All in the meanwhile, the script take notice of the distance between each foot and the ground as well as the type of ground while I'm at it so that I can change the sound if the ground is a liquid or metallic or someone else. (Why wasting such a convenient drawcall that can return what's below each foot?) When the CanStepR or CanStepL are turned True (by the Event Call) and the distance between the targeted foot (be it right or left based on which Boolean is true or false), I turn the Boolean false and play the sound so that it doesn't play twice. The main advantage of this method comes from the fact that you can exploit the raycast for more than just the sounds. As I previously stated, with this you can change the sound based on what's below the player's foot. (You do need to script some kind of Ground types system that allows the script to check the ground's script to get the infos. It's not a magic thing that is instantly done.)
2. Add some kind of conditions to the sound script command (Pisar). In the ThirdPersonController script, you got multiple data that are related to how the player move. For example, the Crouch Boolean, if true, means your character is crouched so, normally, the animation where the character is crouched should be considered as the "source" for playing the step sounds. Make it so that ThirdPersonController can communicate with the PlayerSound script and also change its internal value. In other words, add some kind of Int (Integer) or Boolean in the PlayerSound script which can be modified in some way by the ThirdPersonController to "set" the state of the player (if he's walking, running. Is he crouched? Etc.) From this, in the Pisar function that is called to play the step sound, add some conditions for the sound to be played. This way, if you got the run animation AND the walk animation both to send the EventCall "Pisar", if the script "knows" that you're either running or walking, it will only play the sound once and will ignore 1 of the 2 or even 3 (if you consider crouching) EventCalls. This method has the advantage of being easy and simple to implement as well as faster on the CPU. It doesn't give any shortcut to get anything more so it's also limited in possibilities unless you add more layers of stuff in it.

So, the general rule when using Animation EventCalls is to always consider that EventCalls in Blended animations will get called all the time even if the animation is not visually playing. Never relies on EventCalls that can be called by more than 1 animation. This is also true with animation transition times. The white (or orange) line with an arrow in the animator represent the transitions. If you select one that is white, you'll notice the "Has Exit Time" checker and a "Setting" dropdown. In that dropdown you can see the "Transition Duration (s)" and "Transition Offset". Even the Transition duration is the amount of frame/time in the animation where the current and next animation will be fused and mixed. During that transition time, both animation's EventCalls will be called. So, if you jump which cut the walking or running animation and the jump's animation transition overlapse the part of the walk/run animation that has an EventCalls for the step, you'll hear the step while the character is jumping too.

This is why it's really important to always work in controls and understanding what you're working with. In terms of game development, it's always better to have too much controls instead of not enough. Lacking in controls is what bring glitches and bugs. When animations and blended animation are involved, always keep things in a way that makes the animations only "work with" the other system and not make it take full controls.
> 3 votes

---
Tags: unity
---


# Question
Title: Need help with sorting layers on a 2D game made in Unity
I'm busy with my full blown project in unity, it's a 2D game as I thought this would make a good starting point.

So to the problem, I've got 3 elements in the game. The ground, an object and a beam. The ground is set to layer 2 and the object to 3. This gives the effect that the object is on top of the group which I need. Now the beam is what I'm having the problem with. I need the beam to be ontop of the object so on layer 4 for example, but I also need it to be behind the ground so layer 0 or 1.

If anyone can point me in the direction that may help or give me any tips i'd be grateful.

As requested I uploaded a screenshot.

So here the object(the cow) is on top of the ground layer. The beam is ontop of the object but it's also ontop of the group, I need it to be beneath the ground.

# Answer
You could use the ground as a mask for the beam, but I think it will give you an unnatural looking effect.

Another option is to separate the ground sprite into 2 parts with a horizontal slice right through the grass. The beam will be in front of the top half and behind the bottom half. Layer order goes like this.

background \> grass\_top\_half \> cow \> beam \> ground\_bottom\_half.

You can also make the slice bumpy to follow the curves of the grass.
> 1 votes

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


# Question
Title: How can I convert a string to quaternion?
```
private GameObject GetObjectFromFile(string path)
    {
        GameObject newobj = new GameObject();
        string[] text = new string[3];
        if (File.Exists(path))
        {
            text = File.ReadAllLines(path);
            foreach (string s in text)
            {

                    text = s.Split(':');
                    break;

            }
            var parent = text[0];

            var localPosition = StringToVector3(text[1]);
            var localRotation =StringToVector3(text[2]);
            var localScale = StringToVector3(text[3]);

            newobj.transform.localPosition = localPosition;
            newobj.transform.localRotation = localRotation;
            newobj.transform.localScale = localScale;
        }

        return newobj;
    }

    public static Vector3 StringToVector3(string sVector)
    {
        // Remove the parentheses
        if (sVector.StartsWith("(") && sVector.EndsWith(")"))
        {
            sVector = sVector.Substring(1, sVector.Length - 2);
        }

        // split the items
        string[] sArray = sVector.Split(',');

        // store as a Vector3
        Vector3 result = new Vector3(
            float.Parse(sArray[0]),
            float.Parse(sArray[1]),
            float.Parse(sArray[2]));

        return result;
    }

```

It's converting fine the localPosition and localScale but the localRotation is a quaternion and not vector3.

This is the text file format I'm reading from:

```
Main Camera (UnityEngine.Transform):(297.7, 5.1, 228.5):(0.0, 0.0, 0.0, 1.0):(1.0, 1.0, 1.0)

```

The part (0.0, 0.0, 0.0, 1.0) is the rotation.

# Answer
Have you tried defining a `StringToQuaternion` method analogous to your `StringToVector3`?

```
public static Quaternion StringToQuaternion(string sQuaternion)
{
    // Remove the parentheses
    if (sQuaternion.StartsWith("(") && sQuaternion.EndsWith(")"))
    {
        sQuaternion = sQuaternion.Substring(1, sQuaternion.Length - 2);
    }

    // split the items
    string[] sArray = sQuaternion.Split(',');

    // store as a Vector3
    Quaternion result = new Quaternion(
        float.Parse(sArray[0]),
        float.Parse(sArray[1]),
        float.Parse(sArray[2]),
        float.Parse(sArray[3]));

    return result;
}

```
> 1 votes

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


# Question
Title: Why do games use tick rates in their networking and servers instead of an event system?
Why do most games limit themselves with a tick rate in their networking? Isn't it better to make something like an even system where for example client A does something then the client sends related info to the server, and same for the server when something happens on it it sends a packet to the client, instead of using a tick rate and sending information only at some specific frequency. Is it cheaper/faster to send more data in a single packet or? And the same question goes for server tick rates, some servers limit themselves on specific tick rate frequencies, why do they do that? Why not just make a loop and run each tick after each other instead of having a gap between them or risking one tick to take longer than it should and causing bugs? What's the benefit of the tick rate approach for servers and for networking?

# Answer
> 2 votes
It's largely a matter of, what's the default assumption for a given segment of time in your game? Is it more likely that...

* absolutely *nothing* happens
* *something* happens

If it's more common that *something* happens than nothing, a regular server tick is a good way to go. For instance, in a multiplayer shooter game, players can change direction and fire off shots in fractions of a second, so there's stuff happening constantly. It makes sense to send regular, frequent updates to keep everyone appraised of the evolving situation, without excess overhead of trying to sleep through or skip timesteps in which nothing happens, since that's rarely if ever the case.

If it's more likely that *nothing* happens than something, then an event-based system is a good way to go. Many games with asynchronous multiplayer work this way, where the game state is only updated when one player logs in and takes their turn / actions, then sits idle until the next player needs to act. It might be minutes or hours, even days before the next event that affects a given player occurs, so doing a sub-second tick update throughout that span would be wasteful.

So, it all depends on what kind of game you're making, and what needs your server has to fulfill.

With regard to ensuring a regular tick frequency, for games that use it, I recommend checking out this earlier answer.

---
Tags: networking, client-server, server
---


title: How to create walls and rooms with Pixi

text:
# Question
Title: How to create walls and rooms with Pixi
I'm a JS dev but pretty new to Pixi and 2D developemnt so please bear with me as I explain this.

I want to write a simulator for short path finding (for evacuation purposes). I decided to use Pixi.js for this since it seems capable of doing everything I need to do. I followed this tutorial to try to learn how Pixi works and if its right for this.

The tutorial didn't seem to answer many questions I have and I still have some confusion. Before I dive into writing the code, I want to know how wall detection in Pixi acheived.

Take the below map for example: It is a 800 x 800 png file (where everything but the blue is transparent\[no grid lines\]) that i can load into Pixi as a Sprite. I created it in Tiled editor. So it can be exported as a tilemap, JSON, CSV etc. When I export it as JSON, here is the file contents: https://pastebin.com/zGh1XmR7

The blue boxes represent walls. I want to load in other various sprite objects so that it will look like this:

The people in the simulations cannot cross the blue walls and they cannot cross the pink circles (they represent danger zones). I intend to use easystar.js to find the shortest path to exits for the people sprites in the map.

So my question is this, how does Pixi recognise the blue walls? Is it something I have to do when creating the tileset png? Like something defined in the JSON file for the tileset atlas? Maybe SVG? Or is there a pixi function to do this? Is this the best approach to doing this and is Pixi even the best way to do this?

I'm looking for a tried and tested solution or a pointer in the right direction.

# Answer
> 2 votes
From my understanding, PIXI *doesn't* recognize the blue walls. Your blue walls are really just one big rectangle (a sprite), so you can detect collisions between your characters and the map itself, but not individual walls within the map.

A better approach would be to draw your walls using PIXI's graphics primitives (as lines). Then you'll have the coordinates and dimensions of individual walls.

For the actual collision detection, you'll need to use the coordinates and dimensions of both elements (a given character and a given wall) to see if they have "collided" and if so, prevent further movement of the character in that wall's direction.

PIXI does not provide collision detection.

---
Tags: collision-detection, tilesets, pixi.js
---


# Question
Title: How to apply fast & slow camera transition
I know there is a lerp function there that smoothens the camera but I wanted it to work the other way around. Lets say starting position of the player is at the left side of the camera/screen and when the players goes around the right edge (or as long as more than half width) screen travelled I want to camera to snap to the player but with smooth transition and **this is the hard part I wanted to make the camera move fast as long as it is less than half of the players distance travelled and apply a slow speed as the camera travels more than half the distance of player.**

# Answer
> 1 votes
Let `cameraX` and `playerX` being the camera's and player's X position respectively. I assume that the camera is following the player only on the X axis (from left to right) and when the camera's X is the same as player's X, then the player is exactly in the middle of the camera view. I also assume that

If, for example, `cameraX` is bigger than `playerX` then `cameraX` needs to decrease in value until it has the same value as `playerX`. You can do something simple like:

```
cameraX = playerX;

```

This will make the camera "Jump" to follow the player, no matter how far away from the camera they get. If the player teleports outside of screen boundary, on the next frame the camera will follow.

Instead what you want, is to make the `cameraX` constantly go closer and closer to the player. From the above example, you can do something like:

```
int camera_movement = 1;
int camera_collision = 10;

// Camera is on the right of the player - move it to the left
if (cameraX > playerX) {
    cameraX -= camera_movement;
}
else
// Camera is on the left of the player - move it to the right
if (cameraX < playerX) {
    cameraX += camera_movement;
}

/* Camera is close enough to the player, so just move it to the player
 * this prevents the camera from keep jumping back and forth
 */
if ( Math.abs(playerX -cameraX) < camera_collision ) {
    cameraX = playerX;
}

```

This moves the camera with a constant value towards the player, when its too close, it just "locks" on the player. Make sure to tweak `camera_movement` and `camera_collision` to suit your game.

This can work for some cases, but not for others. So another solution is:

```
cameraX = Math.Lerp(cameraX, playerX, 0.5);

```

This is using an integer `Lerp`, that makes the camera keep moving towards the player based on the distance between them. For the last argument, if you give the value `0.5`, the camera will always travel half the distance between it and the player. If you give it a lower value, it will move there slower, but smoother.

Make sure you change some of the values based on your game. From what I understand, you mentioned the player can be on the left side of the camera only, in which case you can tweak the `playerX` variable to something different than the player's X position, depending on where you want the camera to look at.

---
Tags: unity, camera
---


# Question
Title: Define a circle from a point on its circumference and an angle
I'm working on a 2D, top-down driving game with some basic AI vehicles. The AI Vehicles move along a bidirected graph of positions. Each vehicle has a current position (from the graph) and a target position, but instead of linearly interpolating directly between the positions, the vehicles each have a maximum steering angle, and so must steer their way to the next point.

The vehicle is defined geometrically as follows:

* The vehicle itself is a rectangle, comprising a center point (**O**), a width and a height.
* The vehicle has both a front (**F**) and rear (**R**) 'axis' from which the wheels are extruded.
* The vehicle is steered from the front axis, by an angle defined as (*a*). The vehicle's
* The current heading is (**A**).
* The current steering heading is (**B**).
* The desired target is (**T**).

The vehicle's heading is only changed when both the steering angle is set and there is some forward motion (i.e. the vehicle cannot turn when standing still).

As long as the target **T** is sufficiently far enough away, over time the vehicles can be correctly steered towards the targets.

The problem is, when the target is defined too close to the front axis, the vehicle can never reach the target, as the turning arc is too large (they drive around the target indefinitely).

I think the solution is to first detect if the target is 'too close', and if so, the vehicle needs to reverse a little first, and then begin driving forwards again. I think this would be achivable by defining a circle adjacent to the vehicle to detect if the target point can be reached based on the maximum turning angle and current position - but I don't know how to create such a circle. Something like:

How can I create a circle (the origin and radius) from the current vehicle position and max turn angle? Is there a different, potentially better solution?

Thanks a lot

**edit** The following is how I update the position of the vehicle. In a nutshell, the positions of the front and rear wheels are first calculated, and their positions are independently updated. Then the new position of the car is worked out from there. I cut a little for brevity, but it should be enough to see how it works:

```
private void updateVehicle(BaseVehicle pCar) {

    final float lAccelerationAmt = 30;
    final float lWheelBase = 32;

    pCar.speed += lAccelerationAmt ;

    // Extrude front and rear axels
    pCar.frontWheels.x = pCar.x + lWheelBase / 2 * cos(pCar.rotation);
    pCar.frontWheels.y = pCar.y + lWheelBase / 2 * sin(pCar.rotation);

    pCar.rearWheels.x = pCar.x - lWheelBase / 2 * cos(pCar.rotation);
    pCar.rearWheels.y = pCar.y - lWheelBase / 2 * sin(pCar.rotation);

    // Move the vehicle
    pCar.rearWheels.x += pCar.speed * delta * cos(pCar.rotation);
    pCar.rearWheels.y += pCar.speed * delta * sin(pCar.rotation);

    pCar.frontWheels.x += pCar.speed * delta * cos(pCar.rotation + pCar.steerAngle);
    pCar.frontWheels.y += pCar.speed * delta * sin(pCar.rotation + pCar.steerAngle);

    // Extrapolate the new car location
    pCar.x = (pCar.frontWheels.x + pCar.rearWheels.x) / 2;
    pCar.y = (pCar.frontWheels.y + pCar.rearWheels.y) / 2;

    // update the vehicle heading
    pCar.rotation = atan2(pCar.frontWheels.y - pCar.rearWheels.y, pCar.frontWheels.x - pCar.rearWheels.x);

}

```

# Answer
> 1 votes
Based on my comment here an Answer:

you have to move to turn your vehicle. Otherwise you would not have the Problem.
If you know the distance, you can calculate the radius:

more formulas: circular sector - Wikipedia

the origin is a little bit more complicated. You have to know around which point your vehicle turns. From this point you have a line (vector) with the length r and in an 90 angle to your car.

---
Tags: mathematics, geometry, linear-algebra
---


# Question
Title: Unity3d - Do I need to destroy gameobject AND script?
From proper leak protection do I need to delete both of these or will getting rid of one take care of both?

Currently I am destroying the script AND the gameobject

```
private void OnDestroy() {
    Destroy(this.gameObject);
    Destroy(this);
}

```

# Answer
You only need to destroy the GameObject.

By destroying the GameObject (`Destroy(this.gameObject);`), you also destroy the script (`Destroy(this)`) automatically.

Destroying the script simply removes the component from the GameObject. Destroying the GameObject removes all of its components, and the GameObject itself.

But there is an issue with your code. `OnDestroy()` is called when the component is being destroyed. (This could be because the component is destroyed, or its GameObject.) So calling the code in there is probably not what you want.
> 12 votes

---
Tags: unity, gameobject, memory-efficiency
---


# Question
Title: Can I set offset / size in scene window in Unity?
When I add component like RigidBody2D or BoxCollider, Can I set offset / size in scene window in Unity? Other than manually set value in inspector form, then look in scene window whether it is fit or not?

# Answer
Yes. Press the Edit Collider button in the inspector.

This will add handles to the green frame representing the extents of the collider, and you can drag those to reposition & resize the collider visually.

Rigidbodies / Rigidbody2Ds don't have a concept of "size" or "offset" per se - these are computed from their attached colliders. So there's no built-in way to edit those at the Rigidbody level. If you want to override their center of mass though, and manipulate this visually, we can do this with a small helper script:

```
public class CenterOfMass : MonoBehaviour {
     void OnEnable() {
         var rb = GetComponentInParent<Rigidbody2D>();

         if(rb == null) {
             Debug.LogWarning("Use center of mass script only inside a Rigidbody2D");
             return;
         }

         rb.centerOfMass = rb.GetPoint(transform.position);
     }
}

```

Put this script on an empty GameObject and position it as a child of your Rigidbody2D-containing object. The position of this child will become the center of mass when the script is initialized.
> 0 votes

---
Tags: unity
---


# Question
Title: Unity Animation isn't played once despite using trigger parameter
From the unity documentation: https://docs.unity3d.com/Manual/AnimationParameters.html

Trigger parameter: a boolean parameter that is reset by the controller when consumed by a transition (represented by a circle button)

So it should play the animantion once right?

In my current game I already set my animation transition condition to trigger, then in gameObject script I also set the parameter, but it plays more than once.

Here are my animation parameter

Here are my animation transition condition

And here are my gameObject script to set the parameter

```
Animator anim;
Start() {
        anim = GetComponent<Animator>();
    }

void shoot() {
        anim.SetTrigger("shoot");
    }

```

**EDIT:** this is the transition out of PlayerShoot, returning to PlayerIdle

# Answer
Thanks to DMGregory comments that leads to this solution.

Apparently it has to do with the post transition condition. It will play once, but in my case there isn't any valid transition from the playerShoot.

As you can see above, I set the `speed` param to be greater than 0, that leads to invalid transition when the game object is in idle state (speed 0), therefore the animation stays where is at.
> 1 votes

---
Tags: unity
---


# Question
Title: Details of what GPU actually do when clipping in 4D homogeneous space?
I am learning programmable rendering pipeline by implementing a tiny software renderer. I try to implement it in a 'hardware' style. However, I am not familiar with the GPU pipeline and got some problems of homogeneous clipping.

The homogenous clipping space contains a **w** variable which various at each vertex. Is each vertex object's homogenous coordinate (between projection matrix and homogenous division by w) at its own clipping space? If so, how to clip the lines and triangles nearer than the Frustum or even stretching behind the camera (i.e. w \<= frustum\_znear)?

**Update**: this thread says that the clipping in homogeneous space is directly an intersection problem in the 4D homogeneous space. Which means the intersection point is `p_vec4 = t * point1_vec4 + (1 - t) * point2_vec4`. Say I have `P0(-70, -70, 118, 120)` and `P1(-32, -99, -13, -11)` in 4D homogeneous space, and the intersection point with `plane w = -z` (which in NDC is z = -1) is `(-35, -96, -1, 0.9) t = 0.99`, how to get the corrresponding vertex object in NDC space?

And once I get the correct intersection point, should I do the interpolation between vertex objects produced by vertex shader to get new vertex object?

# Answer
Clipping is done in 3D space before 'w' division, not in 4D space.

The GPU finds either just the near and far planes, or all 6 3D planes of the view frustum and clip the Geo to this.

If w division was done before the sign of coordinates would flip for vertices behind the eye/camera.

If only near-far planes are used to 3D clip before w division then may rely solely on 2D clipping at the rasterizing stage for the x & y planes.

---

W is just a projection divider directly related to Z, not actually a 4th dimension. The 4x4 matrix is a "hack" to include a translation and projection division in a convenient format. It works only because positions are implied to be (x, y, z, 1) and normals are implied to be (x, y, z, 0).

But it's not actually 4 independent dimensions.

Any other value for "W" that is not 1 or 0 make little sense for geometry, it's a convenient on/off switch for turning off translation.
> 2 votes

# Answer
If you're asking about converting homogeneous clip space coords to normalized device coordinates (NDC) coords, the process is: `<x y z w> → <x/w y/w z/w>`

This GDSE Q/A on Why is clip space always referred to as “homogeneous clip space”? may also be helpful to you.
> 0 votes

---
Tags: pipeline, clipping, software-rendering, rasterization
---


# Question
Title: Problem with Unity APK Build : Default Activity (Android)
There was a project developed in Unity 4.5. I successfully updated it to Unity 2018.2.3f1 version without any error. Runs perfectly in Editor. When I create an APK (internal). I just get this screen when I open it on a mobile.

But when I make a Windows/Mac Build, it runs perfectly. I've also tried on another Editor (version 2017.3.x) and APK built from this is also good. I've re-installed Unity, nothing... Also updated the SDK but still a problem.

Some other projects' APK is built successfully with the scenes and everything but they also have some strange problems. Note: I cannot shift back to 2017.3.x. Is it a problem the latest Editor? OR Is it a problem with my machine? What possibly could that be?

# Answer
> 1 votes
I fixed it , I downgraded unity to 2018 1.2f1 I think, built it again and when I ran it everything was working fine :) Good luck with fixing the error, I hope that I helped at least a bit

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


# Question
Title: Minecraft/OpenGL - Create Multiple viewports
I'm working on a project for the game and i have been trying to draw a second smaller "window" that would act like a second camera, independent from the player.

I have looked into glViewport however i keep running into issues where the second viewport is the only one being drawn (the first one gets covered by the second and has a blank screen where the first viewport should be:

So i guess the question is: How can i have multiple windows on screen and make it so it plays nice with the game's default rendering system? I know it is possible since the game uses OpenGL, and maybe its just a simple case of putting the code in the right class.

# Answer
> Create Multiple viewports

You don't "create" viewports, because viewport is not an object. When you set a viewport you are setting the left, top, right bottom region that the GL context will use to render in the framebuffer.

It looks like what you want is render to framebuffer, that will act like a camera, and then render the content of this framebuffer on the screen.

1. Create a framebuffer with 2 textures attached to it (one texture is the color attachment, and the other texture is the depth attachment)
2. Bind to the framebuffer.
3. Render to the framebuffer.
4. Bind to the screen framebuffer (`glBindFramebuffer(0)`)
5. Render the texture that is the color attachment of the framebuffer you created into the screen framebuffer.

There are plenty of sources that explain this process with details, they are often referred as "render to texture", like this one: http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture
> 1 votes

---
Tags: opengl, rendering, camera, minecraft-modding
---


# Question
Title: Reconstruct Quaternion from 48 bit rotation data
I'm trying to reverse an animation file from a commercial multiplayer game, whose format was recently updated. The problem lies within joint rotation information, which changed from a 128bit format to a 48 bit format.

The old format actually was using a quaternion representation with 32 bit floats for each component (32 * 4 = 128 bit)

The new format was probably added for quantization purposes (serving better multiplayer performance). I played around trying to apply an euler angle representation (3 x 16 bit integers or 3 x 16 bit half floats) but i failed miserably so I think it should be still a quaternion representation of some sort.

I have located a model which has not changed at all structurally but obviously the model files have been updated to the newest format.

So I do have the byte data, I know the correct rotation angles (again from game data) that correspond to those values as well as the quaternion values from the old version of the files.

```
New Format Bytes       Rotation(deg) X,Y,Z       Quaternion
41 ED 3F ED 41 6D      0, 90.0, 89.99             0.5, 0.5, 0.5, 0.5
85 F7 2C A0 85 77      59.64, 90, 0               0.3516, 0.61347, -0.351634, 0.61347
AE CE FF BF FF 3F      -180, 0, 18.54             0.98 0.16 0 0
40 ED BE 92 BE 12      0,-90,90                   0.5, -0.5, -0.5, 0.5
DE 40 DA 42 CA 3C      -1.017, -3.633, 4.091      -0.009633918, -0.03154902, 0.03542599, 0.9988277

```

I'm currently searching the web for quaternion quantization techniques and I'm experimenting with different stuff, so if I find anything I'll make sure to update. Thanks in advance

# Answer
> 1 votes
Took me 4 days of headache and research but I got there :D

So it turns out to be a modified CryEngine 3 48bit scheme.

Just to recap, when I started working on this, having 3 components I thought that they were supposed to be euler angles. The extra bit and values being all over the place out of the expected (-180,180) range ruled that out.

This is when I started researching about packing quaternions. After I tried different formats for smaller three schemes which failed because of the values being padded. Once I realized that, I kept unpacking the values as unsigned 16 bit values and I started skipping bits to find out the range of the values. I knew since the start that 0x3FFF somehow corresponded to 0 so this is the offset I used to move the values over the domain. Eventually I found that I had to skip just one bit and that 1/0x3FFF is also the normalization constant and soon enough I realized that the values lie within the `(-1/sqrt(2), 1/sqrt(2))` range. This got me to a point where the values I calculated were 100% the same with the old quaternion values. The only thing that was changing things was the order, which is really easy to work out using the flag bits.

The main difference lies in the fact that despite all 3 components are 15bit values, they are padded with 1bit to fit in 2 bytes, and after unpacking those 3 bits are used as flags to indicate the component order. Other than that values are masked and after normalization they are brought into `(-1/sqrt(2), 1/sqrt(2))` range.

```
//Load Rotations
UInt16 c_x, c_y, c_z;
UInt16 i_x, i_y, i_z;

c_x = readUint16();
c_y = readUint16();
c_z = readUint16();

i_x = (UInt16)(c_x >> 15);
i_y = (UInt16)(c_y >> 15);
i_z = (UInt16)(c_z >> 15);

ushort axisflag = (ushort) (i_x << 0 | i_y << 1 | i_z << 2);

//Mask Values
c_x = (UInt16) (c_x & 0x7FFF);
c_y = (UInt16) (c_y & 0x7FFF);
c_z = (UInt16) (c_z & 0x7FFF);

float norm = 1.0f / 0x3FFF;
float scale = 1.0f / (float) Math.Sqrt(2.0f);

float[] values = new float[4];
values[0] = ((float)(c_x - 0x3FFF)) * norm * scale;
values[1] = ((float)(c_y - 0x3FFF)) * norm * scale;
values[2] = ((float)(c_z - 0x3FFF)) * norm * scale;
//I assume that the calculated value is positive by default
values[3] = (float)Math.Sqrt(Math.Max(1.0f - values[0] * values[0] - values[1] * values[1] - values[2] * values[2], 0.0));

Quaternion q = new Quaternion();
switch (axisflag)
    {
        case 3:
           q = new Quaternion(values[3], values[0], values[1], values[2]);
           break;
        case 2:
           q = new Quaternion(values[0], values[1], values[3], values[2]);
           break;
        case 1:
           q = new Quaternion(values[0], values[3], values[1], values[2]);
           break;
        case 0:
           q = new Quaternion(values[0], values[1], values[2], values[3]);
           break;
        default:
           break;
    }

```

---
Tags: rotation, quaternion
---