2014-07-10 127 views
1

嘗試在x和y軸上拖放遊戲對象。由於某些原因,即使鼠標沒有移動,隨着時間的推移,x,y和z的值也會變小。任何人都可以解釋爲什麼會發生?Unity OnMouseDrag()拖放

using UnityEngine; 
using System.Collections; 

public class Drag : MonoBehaviour { 

    Vector3 point; 
    float x; 
    float y; 
    float z; 

    void Update() { 

    } 

    void OnMouseDrag() 
    { 
     x = Input.mousePosition.x; 
     y = Input.mousePosition.y; 
     z = gameObject.transform.position.z; 

     point = Camera.main.ScreenToWorldPoint (new Vector3 (x, y, z)); 
     gameObject.transform.position = point; 

     Debug.Log ("x: " + point.x + " y: " + point.y + " z: " + point.z); 
    } 
} 

回答

0

z應該是從攝像機的距離:z=(Camera.main.transform.position-gameObject.transform.position).magnitude。即使是這樣,由於浮點精度問題(取決於規模和運氣),您可能會遇到一些漂移。

如果您遇到漂移問題,請嘗試緩存z值。

此外,你將有更多的控制權(沒有浮漂的問題),如果你使用Camera.main.ScreenPointToRay和raycasted,對一個Plane

Vector3 ScreenPosToWorldPosByPlane(Vector2 screenPos, Plane plane) { 
    Ray ray=Camera.main.ScreenPointToRay(new Vector3(screenPos.x, screenPos.y, 1f)); 
    float distance; 
    if(!plane.Raycast(ray, out distance)) 
     throw new UnityException("did not hit plane", this); 
    return ray.GetPoint(distance); 
} 

Plane使用應該是這樣的:

Plane plane=new Plane(Vector3.up, Vector3.zero); 

它的定位在Vector3.zero的位置,它朝上(Vector3.up)。

+0

你能指點我一些關於如何在飛機上使用光線投射的好教程嗎? –

+0

用一個例子編輯我的答案。 –