Hello!
I am currently implementing a rotating beam weapon for a 2D game which reflects/ricochets from its original point of contact with a 2D collider and continues until hitting another 2d collider.
Using the initial 2D raycast hit to begin another raycast with its direction obtained via reflection I have only had success when the direction of the initial raycast hits colliders at specific angles.
I’ve hit a roadblock finding an explanation for this behaviour, and would appreciate any insight into what is causing it and how it can be fixed.
My code is below, and here is a video of the problem in action.
public class Laser : MonoBehaviour
{
public Transform laserHit; // point where laser initially hits
public Transform laserRicochetHit; // point where laser ricochet hits
private LineRenderer lr;
void Awake ()
{
lr = GetComponent<LineRenderer>();
lr.enabled = true;
lr.useWorldSpace = true; // world origin instead of the parent object origin
lr.numPositions = 3; // 0 - origin, 1 - initial wall hit, 2 - ricochet hit
}
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.parent.up);
laserHit.position = hit.point;
// create a ricochet line via raycasting
Vector2 ricoDir = Vector2.Reflect(transform.parent.up, hit.normal); // direction for ricochet raycast
RaycastHit2D ricochetHit = Physics2D.Raycast(hit.point, ricoDir);
laserRicochetHit.position = ricochetHit.point;
// set line positions
lr.SetPosition(0, transform.position); // origin
lr.SetPosition(1, laserHit.position); // initial wall hit
lr.SetPosition(2, laserRicochetHit.position); // ricochet hit
// draw debug lines
Debug.DrawLine(transform.position, hit.point);
Debug.DrawLine(hit.point, ricochetHit.point);
}
}
I am new to Unity and C#, and would appreciate any and all comments. Thanks!