0
\$\begingroup\$

I'm trying to add a flying feature to my character. I set up the Third Person Controller using the newest StarterAssetsInputs (capsule) which contains it's own ThirdPersonController.cs and uses the new input system to move the CharacterController.

I don't want to modify the premade Unity script, so i'm accessing its contents from another script.

It's working pretty well so far. I'm changing the StarterAssets directly and force its inputs.move to have a constant value inputs.move = Vector2.up;

The result is when the character is grounded it keeps moving in the direction he had while flying. I need it to stop moving when grounded.

So the main question is:

  1. how can i reset the Input.move?
  2. Is there a better way to add constant force (on z axis) and then remove the force when grounded?

I tried a lot of different approaches

  • add a CharacterController movement instead of keeping pressed the button

https://docs.unity3d.com/ScriptReference/CharacterController.Move.html

https://answers.unity.com/questions/333155/how-to-keep-charactercontroller-grounded-without-c.html

  • reset the Inputs

https://docs.unity3d.com/ScriptReference/Input.ResetInputAxes.html

  • setting inputs.move = Vector2.zero; will stop the character completely.

Any idea folks? Here's my script

using UnityEngine;
#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
using UnityEngine.InputSystem;
#endif
using StarterAssets;


public class FLY : MonoBehaviour
{
    private ThirdPersonController ctrlScript;
    public StarterAssetsInputs inputs;

    public float distToGround = 1f;
    public bool isFlying = false;


    void Start()
    {
        ctrlScript = GetComponent<ThirdPersonController>();
    }

    void Update()
    {
        GroundedCheck();

        CharacterController controller = GetComponent<CharacterController>();


        if (isFlying)
        {
            inputs = GetComponent<StarterAssetsInputs>();

            //inputs.move = Vector2.up;

            if (inputs.jump)
            {
                ctrlScript._verticalVelocity = Mathf.Sqrt(ctrlScript.JumpHeight * -15f * ctrlScript.Gravity);
            }

            ctrlScript.Gravity = -1;

        }
        else
        {
            ctrlScript.Gravity = -15;
        }
    }
    private void GroundedCheck()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit, Mathf.Infinity))
        {
            if (hit.distance > 2f)
            {
                isFlying = true;
            }
            else
            {
                isFlying = false;
            }
            if (ctrlScript.Grounded)
            {
                isFlying = false;
            }
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.