sphere1 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere1.name = "Sphere1";
sphere1.transform.position = Camera.main.transform.position + new Vector3(0, 0, 0.1f); // the camera is inside sphere1
sphere1.transform.localScale = new Vector3(10, 10, 10);
sphere2= GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere2.name = "Sphere2";
sphere2.transform.position = Camera.main.transform.position + Camera.main.transform.forward * 3f; // the camera is outside sphere1
sphere2.transform.localScale = new Vector3(3,3,3); // Scale as needed
下面的常规碰撞检测代码,只能检测到sphere 2,而不能检测到sphere 1,尽管两个sphere都有sphere collider。 这是应为,camera在sphere 1内部,会直接输出"No hit"。 (Debug.DrawRay只会出现在scene view,而不会出现在gameview)
GameObject controller = rightController;
Ray ray = new Ray(controller.transform.position, controller.transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000))
{
// Here, you could check the name of the hit object or compare the GameObject directly
if (hit.collider.gameObject == sphere1.gameObject)
{
// logic
}
else
{
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red, 10f);
Debug.Log(ray.origin);
Debug.Log(ray.direction);
Debug.Log("No hit");
}
在我的程序中,我使用sphere 1来展示360图片,因此我的相机必须在sphere内部。一种解决方案是,从sphere1外面射出raycast,如下代码所示(还未测试):
public void OnOptionSelected(InputAction.CallbackContext context) {
if (context.action.name == "SelectOption") {
if (context.performed) {
GameObject controller = rightController;
// Assuming sphereRadius is the radius of your sphere
float sphereRadius = 10.0f; // Replace with your actual sphere radius
// Start the ray just outside the sphere's surface
Vector3 rayOriginOutsideSphere = controller.transform.position - controller.transform.forward * sphereRadius;
Ray ray = new Ray(rayOriginOutsideSphere, controller.transform.forward);
RaycastHit hit;
// Increase the maxDistance by the sphereRadius to account for the new origin
float maxDistance = 1000 + sphereRadius;
if (Physics.Raycast(ray, out hit, maxDistance)) {
// Here, you could check the name of the hit object or compare the GameObject directly
if (hit.collider.gameObject == sphereDisplay.gameObject) {
// This is where you handle the hit
OnClickToSelectOption("SphereDisplay_" + hit.collider.gameObject.name, "Sequential");
preferedOptionAreaID = curDisplayedOptionAreaID;
}
} else {
Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.red, 10f);
Debug.Log(ray.origin);
Debug.Log(ray.direction);
Debug.Log("No hit");
}
}
}
}
(在上图中,360图片的球体是不能使用从camera射出的raycast进行检测的。但是白色的小球和正方体可以。)