Unity2D - 如何将对象移动到触摸位置

时间:2016-07-21 02:21:49

标签: c# android unity3d

我使用我的Android设备来检测触摸的位置并移动我的物体,但是我的物体改变了位置,远离我的相机视图,我是否需要使用ScreenToWorldPoint?它是这样,我该如何使用它?

这是我的代码:

void Update() {
    for (var i = 0; i < Input.touchCount; i++) {
        if (Input.GetTouch(i).phase == TouchPhase.Began) {
            transform.position = new Vector3 (Input.GetTouch(i).position.x, Input.GetTouch(i).position.y, transform.position.z);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以尝试这样:

private void Update()
{
    for (var i = 0; i < Input.touchCount; i++)
    {
        if (Input.GetTouch(i).phase == TouchPhase.Began)
        {
            var worldPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
            transform.position = worldPosition;
        }
    }
}

答案 1 :(得分:0)

您可以尝试一下,

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

public class SelectObject : 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;
            }
        }
    }
}