首页 > 解决方案 > 如何在 Android 上让 3D 对象从左到右跟随我的手指?

问题描述

我是统一和游戏开发的新手,所以我尝试制作游戏。一切都很顺利,直到我考虑将游戏从 PC 更改为 Android。

PC 上的运动运行良好,但我似乎找不到任何代码用于 Android 的相同运动。

这就是我用于 PC 运动的东西

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;

    public float forwardForce = 2000f;
    public float sidewayForce = 500f;

    // Update is called once per frame
    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if ( Input.GetKey("d") )
        {
            rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (rb.position.y < -1f)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

这就是我用于 android 运动的方法,但唯一的问题是它不会前进,玩家甚至不会移动。该脚本以某种方式移动玩家所在的平台。

public class PlayerMovANDROID : MonoBehaviour
{

    // Use this for initialization
    GameObject hitObj;
    RaycastHit hit;
    private float speed = 1;

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        foreach (Touch touch in Input.touches)
        {
            switch (touch.phase)
            {
                case TouchPhase.Began:
                    Ray ray = Camera.main.ScreenPointToRay(touch.position);
                    if (Physics.Raycast(ray, out hit, 10))
                    {
                        hitObj = hit.collider.gameObject;
                    }
                    break;
                case TouchPhase.Moved:

                    // If the finger is on the screen, move the object smoothly to the touch position          
                    float step = speed * Time.deltaTime; // calculate distance to move
                    if (hitObj != null)
                        hitObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, hitObj.transform.position.z));
                    break;
            }
        }
    }
}

标签: c#androidunity3dmobileunity-remote

解决方案


您是否使用 GUI 按钮来移动播放器?

如果不是,您可以使用:horizo​​ntal=Input.GetAxis("Mouse X") 和vertical =Input.GetAxis("Mouse Y")来检测玩家将手指放在屏幕上的位置。

一旦你得到那些,你应该通过 Transform through 将它们分配给对象

transform.Rotate(horizontal, vertical ,z);

transform.Translate(horizontal, vertical ,z);

transform.position(horizontal, vertical ,z);

检查以获取更多信息。


推荐阅读