Organically toggle between indirect and direct movement control

By organically I mean no menu or toggle button. Just use whatever and it works. I don’t mean it’s a good solution (since I find it more valuable for this excercise to write your own thing), but yeah, just wanted to share.

While doing past excercises, I came up with another solution. It’s not the best, but it was the easiest at the moment and I didn’t want to drag too much (since the lesson was about something else, it just bugged me so I solved it before).

ANYWAY, what I did was changing some lines inside the original ThirdPersonUserControl and ThirdPersonController in order to implement a followTarget that would be set and unset depending on the last movement input. This is all I added to the ThirdPersonController class:

public bool followTarget;

Just to share the same reference to the same object. Then I access it and change at both input components.

ThirdPersonUserControl

            // pass all parameters to the character control script
            if (!m_Character.followTarget) {
                //encapsulated this line within this if statement
                m_Character.Move(m_Move, crouch, m_Jump);
            }

On PlayerMovement though I did several changes. But all is done at FixedUpdate so I’ll just post that method.
PlayerMovement.cs


```// Fixed update is called in sync with physics
    private void FixedUpdate()
    {
        if (Input.GetMouseButton(0)) {
            switch (cameraRaycaster.layerHit) {
                case Layer.Walkable:
                    currentClickTarget = cameraRaycaster.hit.point;  // So not set in default case
                    m_Character.followTarget = true;
                    break;
                case Layer.Enemy:

                default:
                    break;
            }
        }
        if (m_Character.followTarget) {
            Vector3 moveVector = (currentClickTarget - transform.position);
            moveVector.y = 0;
            if (moveVector.magnitude < 0.25f) {
                m_Character.followTarget = false;
            }
            m_Character.Move(moveVector.normalized, false, false);
        }
    }

And that pretty much summarizes what I did. Main thing is adding that followTarget flag that says if we are in a state where the character moves towards a target, or if we are directly moving the character via keyboard/gamepad. I didn’t cared much about simultaneous access to the variable since the player shouldn’t be using both things at the same time, it’s redundant. And as far as I was able to see, they kind of cancelled each other, so it’s not gonna make unexpected behaviours (glitch or be exploitable).

Privacy & Terms