Home > database >  How to make player move on x axis with Input.Touch
How to make player move on x axis with Input.Touch

Time:10-30

With my current setup, I have player that moves forward thru space and by pressing "A" and "D" on the keyboard I can move it on x axis. It looks something like subway surfers except you are allowed freely to move on the x axis, its not restricted to three lines. So here is my code that I have right now... I have tried at least 5 different ways but nothing seems to work.

    public float speed = 5;
    public Rigidbody rb;
    public bool CanMove = false;
    float horizontalInput;
    [SerializeField] float horizontalMultiplier = 2;
    Vector3 horizontalMove;
    Vector3 RbPositionCheck;

    private void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            Vector3 touchPosition = Camera.main.ScreenToViewportPoint(touch.position);
            Mathf.Round(touchPosition.x);
        }
    
        
        if (CanMove == true)
        {
            #region horizontalInput
            horizontalInput = Input.GetAxis("Horizontal");
            #endregion

            #region Vector3 Calculations
            Vector3 forwardMove = transform.forward * speed * Time.deltaTime;
            horizontalMove = transform.right * horizontalInput * speed * Time.deltaTime * horizontalMultiplier;
            #endregion

            #region RbPositionCheck and Mathf.Clamp
            RbPositionCheck = rb.position;
            RbPositionCheck.x = Mathf.Clamp(RbPositionCheck.x, -4f, 4f);
            #endregion

            #region rb.MovePosition
            rb.MovePosition(RbPositionCheck   forwardMove   horizontalMove);
            #endregion
        }
    }

So In the upper part of code there are values and variables, I made that first if statement but I have no idea what to do with it...(it needs to work on Touchscreen with that one) and I made the other one that perfectly works with keyboard on Computer. Can you give me some tips or solutions on how to fix this?

CodePudding user response:

Input.GetAxis comes from InputManager, and by default its nothing to do with touch input (I think there is no option for that, perhaps some plugins make it work with it).

You can get the Touch, as you do in the example, and store its position, then in the next frame (in Update) if the touch is still in progress, you can calculate the delta position, and move your object according to that.

https://docs.unity3d.com/ScriptReference/Touch.html

https://docs.unity3d.com/ScriptReference/Touch-phase.html

  • Related