我正在研究增强现实程序,我需要通过触摸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;
}
}
}
}
答案 0 :(得分:2)
对于对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
}
}
}
}
在我的情况下,我将这些用于地平面检测,但它也可以与基于目标的增强一样工作
答案 1 :(得分:0)
我昨天解决了这个问题。你需要选择世界中心。选择你的ARCamera" World Center Mode"参数来自" FIRST_TARGET"到" SPECIFIC_TARGET"并选择了您的目标,即您的虚拟世界中心。然后在播放模式下尝试。字符将在您的SPECIFIC_TARGET X& Z轴。