我正在开发一个增强现实程序,我需要通过触摸在 x 和 z 坐标中移动对象。我在 vuforia 网站上找到了一个代码来移动对象。我测试了这段代码,但有一些问题,比如物体在 Y 方向移动,所以它会播放 !!!!!! 但我只想在 x z 中移动我的对象(在地面场景中) 我试图更改代码来自己做,但没有任何结果。 如果你明白了,请帮助我。
using UnityEngine;
using System.Collections;
public class MyDragBehaviour : MonoBehaviour
{
private float maxPickingDistance = 2000;// increase if needed, depending on your scene size
private Transform pickedObject = null;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
foreach (Touch touch in Input.touches)
{
Debug.Log("Touching at: " + touch.position);
//Gets the ray at position where the screen is touched
Ray ray = Camera.main.ScreenPointToRay(touch.position);
if (touch.phase == TouchPhase.Began)
{
Debug.Log("Touch phase began at: " + touch.position);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit, maxPickingDistance))
{
pickedObject = hit.transform;
}
else
{
pickedObject = null;
}
}
else if (touch.phase == TouchPhase.Moved)
{
Debug.Log("Touch phase Moved");
if (pickedObject != null)
{
Vector2 screenDelta = touch.deltaPosition;
float halfScreenWidth = 0.5f * Screen.width;
float halfScreenHeight = 0.5f * Screen.height;
float dx = screenDelta.x / halfScreenWidth;
float dy = screenDelta.y / halfScreenHeight;
Vector3 objectToCamera =
pickedObject.transform.position - Camera.main.transform.position;
float distance = objectToCamera.magnitude;
float fovRad = Camera.main.fieldOfView * Mathf.Deg2Rad;
float motionScale = distance * Mathf.Tan(fovRad / 2);
Vector3 translationInCameraRef =
new Vector3( motionScale * dy,0, motionScale * dx);
Vector3 translationInWorldRef =
Camera.main.transform.TransformDirection(translationInCameraRef);
pickedObject.position += translationInWorldRef;
}
}
else if (touch.phase == TouchPhase.Ended)
{
Debug.Log("Touch phase Ended");
pickedObject = null;
}
}
}
}
最佳答案
对于任何对操作 vuforia 感兴趣的人,您可以使用 Lean Touch library用于平移、旋转、缩放等等(它会说已弃用,但效果一样好)。
不幸的是,Lean Touch 没有为 zOx 平面中的翻译制作的脚本。为此,我根据 aldonaletto's answer 制作了这个脚本.对于多个对象,您可以使用 Unity's Touch API 轻松添加某种选择。
using UnityEngine;
public class MyDragBehaviour : MonoBehaviour
{
void Update()
{
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
// create ray from the camera and passing through the touch position:
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
// create a logical plane at this object's position
// and perpendicular to world Y:
Plane plane = new Plane(Vector3.up, transform.position);
float distance = 0; // this will return the distance from the camera
if (plane.Raycast(ray, out distance))
{ // if plane hit...
Vector3 pos = ray.GetPoint(distance); // get the point
transform.position = pos; // pos has the position in the plane you've touched
}
}
}
}
在我的例子中,我将它们用于地平面检测,但它与基于目标的增强一样有效
关于android - AR Vuforia 仅在 x z (Unity3D) 中通过触摸移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27822276/