Here is my code (not mine, tho)
private void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
}
private void Update()
{
castRay();
}
void castRay()
{
ray = new Ray(transform.position, transform.up);
lineRenderer.positionCount = 1;
lineRenderer.SetPosition(0, transform.position);
count += Time.deltaTime * lineDrawSpeed;
for(int i = 0; i < reflect; i++)
{
Debug.DrawRay(ray.origin, ray.direction * count);
if(Physics.Raycast(ray, out hit, count))
{
lineRenderer.positionCount += 1;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, hit.point);
ray = new Ray(hit.point, Vector3.Reflect(ray.direction, hit.normal));
print(hit.distance);
if(hit.transform.tag !="Mirror")
{
break;
}
}
else
{
lineRenderer.positionCount += 1;
lineRenderer.SetPosition(lineRenderer.positionCount -1, ray.origin + ray.direction * count);
}
}
}
and video Raycast(test) - YouTube
Add a RigidBody2D to the object with the LineRenderer and the following code should move the line object as you wish, just without drawing the Ray:
[SerializeField] private int lineDrawSpeed;
private RigidBody2D rigidbody; //initialize in the Start()
void Update()
{
transform.Translate(Vector3.right * Time.deltaTime * lineDrawSpeed);
}
void OnCollisionEnter2D(Collision2D collision)
{
var reflectedPosition = Vector2.Reflect(transform.right, collision.contacts[0].normal);
rigidbody.velocity = reflectedPosition.normalized * lineDrawSpeed;
var direction = rigidbody.velocity;
rigidbody.freezeRotation = false;
rigidbody.MoveRotation(Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
rigidbody.angularVelocity = 0f;
}
You should get a normalized reflected Vector (normalized vector has magnitude = 1). This will keep your desired length and speed. Then the easier way is to find the angle of rotation with the inverse (arcus) tangent of y/x from your normalized reflected vector.