Forum rules - please read before posting.

Controlling player movement with keyboard

Hi,

How can it be done?
Control player movement with keyboard,

So I have point and click game, but want in additon to clicking in some spot to move player, move player with AWSD and arrows.

My first guess, make Input.GetKeyDown("a") for all necessary keys, and for every key some function,
like

void Update()
{
if (Input.GetKeyDown("a"))
{
Move Player: single mouse click in player position += Vector3.left );
}
}

Comments

  • Of course player must obey path finding in navmesh area

  • You can instruct the player to pathfind towards some point with the MoveToPoint function, i.e.:

    Vector3 rightPosition = KickStarter.player.transform.position + Vector3.right;
    KickStarter.player.[MoveToPoint](/scripting-guide/class_a_c_1_1_char.html#ae20ae5cab243a8885097e918f02b1086 "MoveToPoint") (rightPosition);
    

    You can similarly make him stop moving when responding to Input.GetKeyUp with the Halt function:

    KickStarter.player.Halt ();
    

    However, this approach isn't the best because you'll likely get issues when approaching NavMesh borders that aren't extremes (e.g. on corners). What may happen here is that the player will try to move around the NavMesh (as though you're clicking some distance away from the NavMesh).

    You could try using Raycasting from the player's position, on the NavMesh layer, in the direction you want to travel, to detect where the NavMesh actually ends in that direction.

    Perhaps easier, however, might be to swap between Direct and Point And Click movement modes according to input, i.e.:

    void Update ()
    {
        Vector2 directInput = new Vector2 ("Horizontal", "Vertical");
        if (directInput.sqrMagnitude == 0f)
        {
            AC.KickStarter.settingsManager.movementMethod = MovementMethod.PointAndClick;
        }
        else
        {
            if (AC.KickStarter.settingsManager.movementMethod == MovementMethod.PointAndClick)
            {
                AC.KickStarter.player.Halt();
            }
            AC.KickStarter.settingsManager.movementMethod = MovementMethod.Direct;
        }
    }
    

    Here, the player wouldn't obey the NavMesh, but you could place down colliders along the border to prevent him from moving off it.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.