Search code examples
c#unity-game-enginecollision-detectionmove

How can I make my character jump around when I move it?


I want to make a rabbit first person simulator, so I need to make every time my character moves, jumps, I try to do it like this:

if (Input.GetAxis("Vertical") > 0)

  transform.position += new Vector3(transform.forward.x, 2f, transform.forward.z) * 2 * Time.deltaTime;

It works, but the problem is that when colliding with another element, the character slides up and ends up on top of the object.

I leave a gif to understand what happens:

enter image description here


Solution


  • Use Raycast on your forward movement to check if you hit anything. if it returns nothing then you can make a move to forward. (Take a look here)

    using UnityEngine;
    
    // C# example.
    
    public class ExampleClass : MonoBehaviour
    {
        public float maxDetectionDistance = 1;
        void Update()
        {
            RaycastHit hit;
            var isHit = Physics.Raycast(transform.position, transform.forward, out hit, maxDetectionDistance);
            // Does the ray intersect any objects excluding the player layer
            if (!isHit)
            {
                if (Input.GetAxis("Vertical") > 0)
                {
                    // your movement function
                    transform.position += new Vector3(transform.forward.x, 2f, transform.forward.z) * 2 * Time.deltaTime;
                }
            }
            else
            {
                Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
                Debug.Log("Did Hit");
    
            }
        }
    }