Unity-如何通过触摸输入移动?

时间:2019-03-07 21:18:24

标签: unity3d touch move

在我的代码中实现触摸移动时,我遇到了一些问题。有人可以给我写信以便使其正常工作吗?

我想像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;
    }
}

单击最后一个代码块之类的代码时,看不到调试。

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

非常感谢

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话,您可以像这样实现

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");
        }
    }
}