2017-08-07 69 views
0

我试图从来源内部投射射线到球体。 我的主相机位置(0,0,0) 球体位置(0,0,0)半径:300 我想知道hit.position和hit.collider.gameobject 我正在尝试下面的教程。 http://answers.unity3d.com/questions/129715/collision-detection-if-raycast-source-is-inside-a.html碰撞检测如果Raycast来源在对撞机内

即使我试过教程,我无法从控制台窗口看到理想的结果。 (在我的控制台窗口中没有Debug.Log结果) 我该怎么做?

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class EyeTrackingPoint : MonoBehaviour 
{ 
    public float sphereRadius = 300; // position(0,0,0) radius 300 
    public GameObject screen3D; // sphere 

    public void Update() 
    { 
     Camera cam = Camera.main; // position(0,0,0) 
     RaycastHit hit; 
     Ray ray = new Ray(cam.transform.position,cam.transform.rotation * Vector3.forward * sphereRadius); 
     ray.direction = -ray.direction; 
     if (Physics.Raycast(ray,out hit)&&hit.collider.gameObject.Equals(screen3D)) 
     { 
      Debug.Log(hit.point); 
     } 
    } 
} 

谢谢您的阅读。

回答

2

Raycast在团结中必须符合这些事情;使用射线应该从哪里出发的世界点。使用该射线的方向。你需要指定它应该检查的层。最重要的是,只有碰撞对象才能被击中,即使游戏对象位于正确的层中,但没有主动对撞机,也不会发生任何事情。示例;

{ 
    RaycastHit hit = Physics.Raycast(start, direction, 1000f, 1<<10); 
    } 

成功的raycast信息保存在RaycastHit中; 1000f是一个浮点值,它限制了光线投射的范围。这样,你可以控制它看起来物体的距离。

如果你没有在raycast中指定图层遮罩,它将返回第一个与任何类型的主动对撞机匹配的对象,而不管它在哪一层。