Home > Enterprise >  Unity C# is reading input without any physical input
Unity C# is reading input without any physical input

Time:04-11

I've been following a youtube tutorial and when I followed and rewrote the input it worked but Unity kept reading input when there was none. Video Link to tutorial: https://www.youtube.com/watch?v=_Pm16a18zy8&list=PLLf84Zj7U26kfPQ00JVI2nIoozuPkykDX

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    public bool isMoving;

    private Vector2 input;

    private void Update()
    {
        if (!isMoving)
        {
            input.x = Input.GetAxisRaw("Horizontal");
            input.y = Input.GetAxisRaw("Vertical");

            if (input != Vector2.zero)
            {
                print(Vector2.right   "|"   Vector2.left   "|"   Vector2.up   "|"   Vector2.down);
                var targetPos = transform.position;
                targetPos.x  = input.x;
                targetPos.y  = input.y;

                StartCoroutine(Move(targetPos));
            }
        }
    }

    IEnumerator Move(Vector3 targetPos)
    {
        isMoving = true;

        while((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
            yield return null;
        }
        transform.position = targetPos;

        isMoving = false;
    }
}

CodePudding user response:

I just made a test project with this script and it seems to work as intended for me. Feel free to elaborate but if you mean that it reads input for a few frames after you stop input until the character stops, then that is a product of how you have movement in a coroutine. That style of movement would work fine for a point and click or something where you want to move the character to a specific point on the screen but for input it will feel laggy. I would suggest either adding a rigidbody2D to the player and moving it by adjusting its velocity or by directly changing the transform.position just not in a coroutine, but if your issue is something else feel free to give me more info.

CodePudding user response:

Most commonly this turns out to be caused by some type of input device being connected that you didn't intend to be reading input from - e.g. a game controller, flight stick, driving wheel or similar. Try disconnecting nonessential USB devices and see if the input readings go away.

  • Related