1
\$\begingroup\$

I'm trying to implement a jump method into my FPSInput script. I know how to make this work for a Rigidbody, but how can I accomplish this with my Character Controller? Does CharacterController have a method comparable to AddForce?

First Person Movement Input:

public class FPSInput : MonoBehaviour {
    public float speed = 6.0f;
    public float gravity = -9.8f;

    private CharacterController _charController;

    void Start() {
        _charController = GetComponent<CharacterController>();
    }

    void Update() {
        float deltaX = Input.GetAxis("Horizontal") * speed;
        float deltaZ = Input.GetAxis("Vertical") * speed;
        Vector3 movement = new Vector3(deltaX, 0, deltaZ);
        movement = Vector3.ClampMagnitude(movement, speed);

        movement.y = gravity;

        movement *= Time.deltaTime;
        movement = transform.TransformDirection(movement);
        _charController.Move(movement);
    }
}

Works for Rigidbody only:

public class Jump : MonoBehaviour {

    public Vector3 jumpVector;

    // Update is called once per frame
    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            GetComponent<Rigidbody>().AddForce(jumpVector, ForceMode.VelocityChange);
            }
        } 
}
\$\endgroup\$
1
1
\$\begingroup\$

Couldn't find a solution that works like AddForce, but I solved this using a verticalVelocity variable that gets passed into a Vector3 jumpVector variable which calls Move on the characterController.

public class FPSInput : MonoBehaviour {
    public float speed = 6.0f;
    public float gravity = -9.8f;

    private float verticalVelocity;
    private float jumpForce = 15.0f;
    private float gravityJump = 14.0f;

    private CharacterController _charController;

    void Start() {
        _charController = GetComponent<CharacterController>();
    }

    void Update() {
        float deltaX = Input.GetAxis("Horizontal") * speed;
        float deltaZ = Input.GetAxis("Vertical") * speed;
        Vector3 movement = new Vector3(deltaX, 0, deltaZ);
        movement = Vector3.ClampMagnitude(movement, speed);

        movement.y = gravity;

        movement *= Time.deltaTime;
        movement = transform.TransformDirection(movement);
        _charController.Move(movement);

        if (_charController.isGrounded) {
            if (Input.GetKeyDown (KeyCode.Space)) {
                verticalVelocity = jumpForce;
            }
        }

        Vector3 jumpVector = new Vector3(0, verticalVelocity, 0);
        _charController.Move (jumpVector * Time.deltaTime);

    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .