Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Gameobject keeps moving after input is pressed

Discussion in 'Input System' started by LarryWells, Aug 15, 2020.

  1. LarryWells

    LarryWells

    Joined:
    Jun 1, 2016
    Posts:
    30
    Hello, so I was following a tutorial and did the same code as them but have different results. I bound the Input system for wasd and the keys work but when I let go the object keeps moving. I believe the issue is on the press it gets the vector information for velcoity but it never resets it so it keeps going but the guy in the tutorial wrote it this way and had no issue. Thoughts?

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.InputSystem;
    6.  
    7. public class Player : MonoBehaviour
    8. {
    9.  
    10.     private InputMaster controls; //New input action system
    11.     private Vector2 moveAxis; //2D axis to be generated from input actions
    12.     private float speed = 5.0f;
    13.     void Awake()
    14.     {
    15.         controls = new InputMaster();
    16.         controls.Player.Movement.performed += HandleMoved;
    17.     }
    18.  
    19.     void Update()
    20.     {
    21.         transform.position += new Vector3(moveAxis.x, 0, moveAxis.y) * Time.deltaTime * speed;
    22.     }
    23.  
    24.  
    25.     private void HandleMoved(InputAction.CallbackContext context)
    26.     {
    27.         moveAxis = context.ReadValue<Vector2>();
    28.     }
    29.  
    30.     private void OnEnable()
    31.     {
    32.         controls.Enable();
    33.     }
    34.     private void OnDisable()
    35.     {
    36.         controls.Disable();
    37.     }
    38. }
    So what happens is my update always uses the vector it grabbed when I pushed the key and just keeps pushing the object that way but in the tutorial whenever the guy let go the object stopped and he didnt reset the vector anywhere in the code.
     
  2. coderD1mka

    coderD1mka

    Joined:
    Jun 26, 2019
    Posts:
    8
    You don`t handle controls.Player.Movement.canceled event that is reason why You get a permanent pressed button state.
    Try add this code in Awake method:
    controls.Player.Movement.canceled += HandleMoved;
     
  3. LarryWells

    LarryWells

    Joined:
    Jun 1, 2016
    Posts:
    30
    Ty so much! worked