首页 > 解决方案 > Unity-如何通过触摸输入移动?

问题描述

我在为我的代码实现触摸移动时遇到了一些问题。有人可以写信给我我需要做什么才能让它工作吗?

我想像 Input.GetAxis("Horizo​​ntal");

这是我与轴一起移动的工作代码

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

public class Player : MonoBehaviour
{

    public float speedY = 5f, speedX = 3f, boundX = 3f;
    
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float input = Input.GetAxis("Horizontal");
        print(input);
       
        }

    }
    void Move()
    {
        Vector2 temp = transform.position;
        temp.y += speedY * Time.smoothDeltaTime;
        temp.x += speedX * Time.smoothDeltaTime * Input.GetAxis("Horizontal");
           
        transform.position = temp;
    }
}

这是我的解决方案,我认为它会起作用,但它不起作用......

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

public class Player : MonoBehaviour
{

    public float speedY = 5f, speedX = 3f, boundX = 3f;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float input = Input.GetAxis("Horizontal");
        print(input);
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.position.x > (Screen.width / 2))
            {
                Move();
                Debug.Log("Go right");
            }
            if (touch.position.x < (Screen.width / 2))
            {
                Debug.Log("justleft");
            }
        }
}


    }
    void Move()
    {
        Vector2 temp = transform.position;
        temp.y += speedY * Time.smoothDeltaTime;
        temp.x += speedX * Time.smoothDeltaTime * Input.touchCount;
        transform.position = temp;
    }
}

当我单击最后一段代码之类的代码时,我看不到调试。

有人可以给我写解决方案吗?或帮我一些小费。

太感谢了

标签: unity3dtouchmove

解决方案


如果我理解正确,你可以像这样实现

void Update()
{
    //Because you always wanna move up
    transform.position += Vector2.up * Time.deltaTime;

    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        if (touch.position.x > (Screen.width / 2))
        {
            //Since i do not know how much right you wanna go
            // This will just go left or right as long as there is a touch 
            transform.position += Vector2.right * Time.deltaTime * speedX;
            Debug.Log("Go right");
        }
        if (touch.position.x < (Screen.width / 2))
        {
            transform.position += Vector2.left* Time.deltaTime * speedX;
            Debug.Log("justleft");
        }
    }
}

推荐阅读