Physics.Boxcast, hit.point bugged?
I'm trying to visualize several HitCast methods in Debug mode, I'm having a issue with Physics.Hitcast: the resulting RayCastHit.point sometimes is right, some other times is just the origin of the Gameobject shooting the Boxcast. I looked up the problem and 1) My Boxcast is not starting inside the object (as you can see in the picture) 2) The gameobject from where the Boxcast starts, has no colliders anyway
What is even more curious is that even if the hit.point is wrong, hit.distance is correct.. Here is my code
private Transform tr;
private LayerMask collisionLayers = 255;
private bool[] hitDetected = new bool[128];
private RaycastHit currentHit;
RaycastHit hit;
private void Start() {
tr = GetComponent<Transform>();
collisionLayers = 255;
}
private void Update() {
hitDetected[0] = Physics.BoxCast(tr.position, Vector3.up * rayscanBoxWidth / 2 + Vector3.right * rayscanBoxWidth / 2, tr.forward, out hit, transform.rotation, rayscanLength, collisionLayers, QueryTriggerInteraction.Ignore);
if (hitDetected[0]) {
Debug.Log(hit.point + " " + hit.distance + " " + hit.transform.name);
}
}
private void OnDrawGizmos() {
Gizmos.color = hitDetected[0] ? Color.red : Color.green;
Gizmos.DrawRay(tr.position, tr.forward * (rayscanLength));
if (hitDetected[0]) {
Gizmos.DrawCube(hit.point, Vector3.one * rayscanBoxWidth);
}
}
Answer by Zankaster · Sep 24, 2019 at 04:58 PM
I want to share the solution to this problem in case someone stumbles in this issue. As you can see from my code, my boxcast has no depth on the z axis, I wanted to do a "PlaneCast", so the plane is cast exactly from the start and for the length I specify, but I guess this causes some problems in the way Unity does its calculations, so you need to provide at least a small value on all the box sizes (x,y,z), I tried with a value like 0.01f and it works now. So, to be clear, you need a value higher than zero on all the components of the halfExtents parameter.
Since I ran into this same thing, I also wanted to note another way this bug is triggered: by a thin (or zero) thickness collider. It worked fine with Raycast, but BoxCast would cause it to say it hit the right collider and give the right hit.distance, but the hit.point would be the exact same point as the starting point for the cast.
Your answer
Follow this Question
Related Questions
RayCastHit Not Returning Rigidbody 0 Answers
Advanced AI sight? AI can detect you if part of you is visible to them. Is it Possible? 1 Answer
How to cast a Ray using local pivot of an object? 1 Answer
Why doesnt the value change? 2 Answers
How to instantiate objects to mesh while restricting the spawn area on a single axis? 2 Answers