Change Horizontal and Vertical input via script

60 Views Asked by At

I have a script where I use input.GetAxisRaw("Horizontal") to set x and the same with Vertical for y. These keys are predefined directly in the unity settings but I would like to be able to change it via a variable so that the player can choose his keys. How to do this ? should it be replaced by keyCode or can directly change via the Horizontal and vertical keys via script? thanks in advance

The code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
   public float MoveSmoothTime;
   public float GravityStrenght;
   public float JumpStrenght;
   public float WalkSpeed;
   public float RunSpeed;

   private CharacterController Controller;
   private Vector3 CurrentMoveVelocity;
   private Vector3 MoveDampVelocity;

   private Vector3 CurrentForceVelocity;

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

    void Update()
    {
        Vector3 PlayerInput = new Vector3
        {
            x = Input.GetAxisRaw("Horizontal"),
            y = 0f,
            z = Input.GetAxisRaw("Vertical")
        };

        if(PlayerInput.magnitude > 1f)
        {
            PlayerInput.Normalize();
        }

        Vector3 MoveVector = transform.TransformDirection(PlayerInput);
        float CurrentSpeed = Input.GetKey(KeyCode.LeftShift) ? RunSpeed : WalkSpeed;

        CurrentMoveVelocity = Vector3.SmoothDamp(
            CurrentMoveVelocity,
            MoveVector * CurrentSpeed,
            ref MoveDampVelocity,
            MoveSmoothTime
        );

        Controller.Move(CurrentMoveVelocity * Time.deltaTime);

        Ray groudCheckRay = new Ray(transform.position, Vector3.down);
        if(Physics.Raycast(groudCheckRay, 1.1f))
        {
            CurrentForceVelocity.y = -2f;

            if (Input.GetKey(KeyCode.Space))
            {
                CurrentForceVelocity.y = JumpStrenght;
            }
        }
        else
        {
            CurrentForceVelocity.y -= GravityStrenght * Time.deltaTime;
        }

        Controller.Move(CurrentForceVelocity * Time.deltaTime);
    }
}

I tried replacing with getKey but it didn't work because for x axis on need 2 directions/inputs.

0

There are 0 best solutions below