【问题标题】:Unity OnMouseDrag() Drag and Dropunity OnMouseDrag() 拖放
【发布时间】:2014-07-10 17:17:59
【问题描述】:

尝试在 x 和 y 轴上拖放游戏对象。由于某种原因,即使鼠标没有移动,x、y 和 z 的值也会随着时间的推移而变小。谁能解释为什么会这样?

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);
    }
}

【问题讨论】:

    标签: c# user-interface unity3d


    【解决方案1】:

    您的z 应该是与相机的距离:z=(Camera.main.transform.position-gameObject.transform.position).magnitude。即使这样,由于浮点精度问题(取决于规模和运气),您也可能会遇到一些漂移。

    如果您会遇到漂移问题,请尝试缓存 z 值。

    此外,如果您使用 Camera.main.ScreenPointToRay 并将其投射到 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)。

    【讨论】:

    • 你能告诉我任何关于如何使用光线投射对平面的好的教程吗?
    • 用一个例子编辑了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多