Slant Physics Raycast Implementation

人走茶凉 提交于 2021-01-28 07:10:56

问题


For my 3d car game, I was doing Physics raycast to detect obstacles and based on detect take turn left or right side. Currently, I was doing straight raycast and I can't able to detect left and right side existed obstacles.

So I decided to do little bit slant raycast to detect something from the left and right side. The following image explains a better way my question:

This code is running at present:

    Ray rayRight = new Ray(thisTransform.position + Vector3.up * 0.2f + thisTransform.right * detectAngle * 0.5f + transform.right * detectAngle * 0.0f * Mathf.Sin(Time.time * 50), transform.TransformDirection(Vector3.forward) * detectDistance);
    Ray rayLeft = new Ray(thisTransform.position + Vector3.up * 0.2f + thisTransform.right * -detectAngle * 0.5f - transform.right * detectAngle * 0.0f * Mathf.Sin(Time.time * 50), transform.TransformDirection(Vector3.forward) * detectDistance);

    Debug.DrawRay(rayRight.origin, rayRight.direction * detectDistance, Color.red);
    Debug.DrawRay(rayLeft.origin, rayLeft.direction * detectDistance, Color.red);

Now please give me a guidance to do slant physics raycast to detect obstacles.


回答1:


Use a differnt direction than Vector3.forward?

Define two Vector3 fields in your class (names below are suggestions), then in Start() initalize them like

float angle = 15.0f //or whatever you need.
leftRayDirection = Quaternion.AngleAxis(-angle, Vector3.up) * Vector3.forward;
rightRayDirection = Quaternion.AngleAxis(angle, Vector3.up) * Vector3.forward;

and use those instead of just Vector3.foward (ofc you still need to transform them, with transform.transformDirection).

Or if you want them to sweep, just calculate them in Update().

edit: Another option would be to store the 2 Quaternions in a field and use them to rotate transform.forward (which is the same as transform.transformDirection(Vector3.forward)) like.

//Field
Quaternion leftRayRotation;

//in Start()
leftRayRotation = Quaternion.AngleAxis(-angle, Vector3.up);

//before Raycasting
Ray leftRay = new Ray(transform.position + leftRayOffset, leftRayRotation * transform.forward);


来源:https://stackoverflow.com/questions/57417158/slant-physics-raycast-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!