测量特定对象的光线投射点

时间:2017-08-07 02:44:43

标签: c# unity3d unity5 unityscript

相机正在将光线投射到任何其他物体上。 我正在尝试测量特定对象(screen3D)的生命点(x,y,z)。 这是我的代码

public class MainActivity : Activity
{
    Button btnDrapDrop;
    AbsoluteLayout layout;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Second);
        btnDrapDrop=FindViewById<Button>(Resource.Id.btnDrapDrop);
        layout = FindViewById<AbsoluteLayout>(Resource.Id.layout);

        //register the  long click event of drap button
        btnDrapDrop.LongClick += BtnDrapDrop_LongClick;
        //register the drag event of the layout
        layout.Drag += BtnDrapDrop_Drag;
    }

    private void BtnDrapDrop_Drag(object sender, View.DragEventArgs e)
    {
        AbsoluteLayout layout = (AbsoluteLayout)sender;

        switch (e.Event.Action)
        {
            case DragAction.Drop:
                float x=e.Event.GetX();
                float y = e.Event.GetY();
                btnDrapDrop.TranslationX = x;
                btnDrapDrop.TranslationY = y;
                layout.Invalidate();
                return;
        }
    }

    private void BtnDrapDrop_LongClick(object sender, Android.Views.View.LongClickEventArgs e)
    {
        ClipData dragData = ClipData.NewPlainText("", "");
        View.DragShadowBuilder myShadow = new View.DragShadowBuilder(btnDrapDrop);
        btnDrapDrop.StartDrag(dragData, myShadow, null, 0);
    }
}

}

但是,我得到了null引用异常错误。我该怎么做来修复我的错误。 nullReferenceException:未将对象引用设置为对象的实例 EyeTrackingPoint.Update()(在Assets / EyeTrackingPoint.cs:14)

EyetrackingPoint.cs:14

public class EyeTrackingPoint : MonoBehaviour {
public float sphereRadius=250.0f;
public GameObject screen3D;
public Vector3 ScreenPosition;
private void Update()
{
    RaycastHit hit;
    Camera cam = Camera.main;
    Ray ray = new Ray(cam.transform.position, cam.transform.rotation * Vector3.forward * sphereRadius);
    if( Physics.Raycast( ray, out hit) || hit.collider.gameObject.Equals(screen3D)) 
    {
        Debug.Log(hit.point);   
    }
}

感谢您的阅读。

1 个答案:

答案 0 :(得分:1)

它与||有关。那应该是&&而不是||

||表示即使hit.collider.gameObject.Equals(screen3D)Physics.Raycast( ray, out hit),也会检查下一个false条件。

如果Physics.Raycast( ray, out hit)falsehit.collider.gameObject.Equals(screen3D)已执行,则hit变量将为null,当您尝试使用{{1}时,您将获得null异常}。

当您使用hit.collider时,&&只会在hit.collider.gameObject.Equals(screen3D)Physics.Raycast( ray, out hit)的情况下进行检查,这是您想要的正确行为。

所以你应该使用它:

true

OR

if (Physics.Raycast(ray, out hit) && hit.collider.gameObject == screen3D)
{
    Debug.Log(hit.point);
}