Physics2D.Raycast Reflect issue

I know I’m just being an idiot, but I’m pulling my hair out so thought I’d turn to the experts for help.

Quick background, currently working on a script that will project a trajectory however I can’t get the raycasting to work properly.

I can cast a ray, have it hit a collider and then cast another ray in the reflected direction, however I can’t then reflect another ray.

The below isn’t my actual code, but I created a greatly simplified version to work out the issue. If I do the following:

void Update () 
	{


		ray = new Ray2D (goTransform.position, goTransform.up);

		Debug.DrawRay (ray.origin, ray.direction * 50, Color.cyan);

		hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, 1 << LayerMask.NameToLayer("Middleground"));

		inDirection = Vector3.Reflect(ray.direction,hit.normal);

		Debug.DrawRay (hit.point, hit.normal*3, Color.blue);
		Debug.DrawRay (hit.point, inDirection * 100, Color.red);

		ray = new Ray2D(hit.point, inDirection);

		prevHit = hit.point;

		hit = Physics2D.Raycast(hit.point, inDirection, Mathf.Infinity, 1 << LayerMask.NameToLayer("Middleground"));

		inDirection = Vector3.Reflect(inDirection, hit.normal);

		Debug.DrawRay (hit.point, hit.normal*3, Color.blue);
		Debug.DrawRay (hit.point,inDirection * 100, Color.green);

	}

The issue is that for the second Ray, it doesn’t register a hit.point so every Ray after the first one just uses the same co-ordinates.

Again I’m clearly being an idiot and doing something monumentally stupid, but would really appreciate someone pointing out to me what stupid thing I’m doing/not doing.

Thanks for any help anyone can provide :slight_smile:

Matt

I simplified and played a bit with your code. In testing, I found that raycasting from the hit.point sometimes returned the collider that was just hit. Moving the casting point a bit up the normal seems to solve this problem. Here is the code I used that was working correctly for me:

void Update () 
{
	Debug.DrawRay (transform.position, transform.right * 50, Color.gray);
	RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right, Mathf.Infinity);
	if (hit != null && hit.collider != null) {
		Vector3 inDirection = Vector3.Reflect(transform.right,hit.normal);
	
		Debug.DrawRay (hit.point, inDirection * 100, Color.red);
		hit = Physics2D.Raycast(hit.point+hit.normal*0.01f, inDirection, Mathf.Infinity);

		if (hit != null && hit.collider != null) {
			inDirection = Vector3.Reflect(inDirection, hit.normal);
			Debug.DrawRay (hit.point,inDirection * 100, Color.green);
		}
	}
}

Note that my original cast was from transform.right rather than transform.up.

thank you this so usefull
but how can use this in game(Not Scence) ? LineRendere ?