Search Unity

Question Move a gameobject with a single touch or single keydown input

Discussion in 'Getting Started' started by ozcanea, Mar 28, 2022.

  1. ozcanea

    ozcanea

    Joined:
    Feb 22, 2022
    Posts:
    1
    As a beginner, I want to move a gameobject between two positions smoothly. But I don' know why I have some problems.I tried several codes. One of them is here.When I give a touch input,it just moves a little.I have to press hundereds of times.I will be grateful if you could help me.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMove : MonoBehaviour
    6. {
    7.  
    8.     [SerializeField] Transform right;
    9.     [SerializeField] Transform middle;
    10.     [SerializeField] Transform left;
    11.     [SerializeField] float t = 2f;
    12.     int location = 1; // 0 left,1 middle , 2 right
    13.  
    14.     private void Update()
    15.     {
    16.         if (Input.touchCount > 0)
    17.         {
    18.             if (Input.GetTouch(0).phase == TouchPhase.Began && Input.GetTouch(0).position.x < Screen.width / 2)
    19.             {
    20.                 DesiredLocation(false);
    21.                 Transport(location);
    22.             }
    23.             if (Input.GetTouch(0).phase == TouchPhase.Began && Input.GetTouch(0).position.x > Screen.width / 2)
    24.             {
    25.                 DesiredLocation(true);
    26.                 Transport(location);
    27.             }
    28.         }
    29.     }
    30.     void Transport(int lane)
    31.     {
    32.         switch (lane)
    33.         {
    34.             case 0:
    35.                 transform.position = Vector3.Lerp(transform.position, left.position, t*Time.deltaTime);
    36.                 break;
    37.             case 1:
    38.                 transform.position = Vector3.Lerp(transform.position, middle.position, t*Time.deltaTime);
    39.                 break;
    40.             case 2:
    41.                 transform.position = Vector3.Lerp(transform.position, right.position, t*Time.deltaTime);
    42.                 break;
    43.         }
    44.     }
    45.     void DesiredLocation(bool isRight)
    46.     {
    47.         location += (isRight) ? 1 : -1;
    48.         location = Mathf.Clamp(location, 0, 2);
    49.     }