如何通过在屏幕上滑动手指来放置物体?

时间:2017-07-28 13:42:39

标签: c# android unity3d google-project-tango tango

使用this教程,我们可以通过手指点击在表面上放置对象。

如何在屏幕上滑动手指的同时更改脚本以放置对象,以便放置对象就像"绘画"它们应该放置的区域?

以下是从教程中放置的脚本:

using UnityEngine;
using System.Collections;

public class KittyUIController : MonoBehaviour
{
    public GameObject m_kitten;
    private TangoPointCloud m_pointCloud;

    void Start()
    {
        m_pointCloud = FindObjectOfType<TangoPointCloud>();
    }

    void Update ()
    {
        if (Input.touchCount == 1)
        {
            // Trigger place kitten function when single touch ended.
            Touch t = Input.GetTouch(0);
            if (t.phase == TouchPhase.Ended)
            {
                PlaceKitten(t.position);
            }
        }
    }

    void PlaceKitten(Vector2 touchPosition)
    {
        // Find the plane.
        Camera cam = Camera.main;
        Vector3 planeCenter;
        Plane plane;
        if (!m_pointCloud.FindPlane(cam, touchPosition, out planeCenter, out plane))
        {
            Debug.Log("cannot find plane.");
            return;
        }

        // Place kitten on the surface, and make it always face the camera.
        if (Vector3.Angle(plane.normal, Vector3.up) < 30.0f)
        {
            Vector3 up = plane.normal;
            Vector3 right = Vector3.Cross(plane.normal, cam.transform.forward).normalized;
            Vector3 forward = Vector3.Cross(right, plane.normal).normalized;
            Instantiate(m_kitten, planeCenter, Quaternion.LookRotation(forward, up));
        }
        else
        {
            Debug.Log("surface is too steep for kitten to stand on.");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

当触摸相位结束时,您可以在触摸移动时产生它们,而不是产生小猫:TouchPhase.Moved。请注意 - 这会在您拖动时产生很多小猫,因为在Update()方法中每帧检查一次。考虑添加时间延迟,或仅在手指移动一定距离后产生。

    void Update ()
    {
        if (Input.touchCount == 1)
        {
            // Trigger place kitten function when single touch moves.
            Touch t = Input.GetTouch(0);
            if (t.phase == TouchPhase.Moved)
            {
                PlaceKitten(t.position);
            }
        }
    }

可以像这样实施距离检查:

float Vector3 oldpos;

void Update ()
{
    if (Input.touchCount == 1)
    {
        Touch t = Input.GetTouch(0);
        if (t.phase == TouchPhase.Began)
        {
            oldpos = t.position; //get initial touch position
        }
        if (t.phase == TouchPhase.Moved)
        {
            // check if the distance between stored position and current touch position is greater than "2"
            if (Mathf.Abs(Vector3.Distance(oldpos, t.position)) > 2f)
            {
                PlaceKitten(t.position);
                oldpos = t.position; // store position for next distance check
            }
        }
    }
}