Inconsistent raycast2D reflecting
I'm struggling to grasp why I am getting inconsistent raycast reflecting. The raycast starts from the player and when it hits a wall it will reflect. It does this 3 times total .The first reflect is always correct but the following reflects seem to get stuck on the other side of colliders sometimes. This is what should happen.
This is what happens 50% of the time.
The walls have a Tilemap Collider2D with a composite collider. This is the code for calculating the reflection.
private void FindPath() {
var mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var delta = mouse - transform.position;
var ray = new Ray2D(transform.position, delta);
Debug.DrawLine(ray.origin, mouse, Color.red, 0f);
for (int i = 0; i < 3; i++) {
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
if (hit) {
if (hit.transform.CompareTag("Wall")) {
Debug.Log("Point " + (i + 1) + " : " + hit.point);
var deflectRotation = Quaternion.FromToRotation(-ray.direction, hit.normal);
var deflectDirection = deflectRotation * hit.normal;
Debug.DrawRay(hit.point, deflectDirection, Color.magenta, 0f);
ray = new Ray2D(hit.point, deflectDirection);
}
else {
break;
}
}
}
}
Any help would be appreciated.
Your answer
Follow this Question
Related Questions
Raycast not detecting bullet 0 Answers
Checking for Raycast distances not working as expected. 0 Answers
Making a GameObject follow the direction of a RayCast 1 Answer
Raycast2D don't hit anything below 0 Answers
Rigidbody blocking raycasts 2D 0 Answers