Why is the reflected ray the same length as the previous and how to fix it
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 https://youtu.be/yk49ONeXCGs
Answer by NMatanski · Jan 27, 2020 at 10:24 AM
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.
Thanks! But after the first reflection, annoying shaking appears, do you know how to fix that?
Your answer
Follow this Question
Related Questions
is my Raycast being reflected correctly and why is it giving me an infinite loop? 0 Answers
Raycast line renderer not drawing correctly 0 Answers
Line Renderer on top of Mesh 1 Answer
Raycasting Animations 0 Answers
Track an object and fire? 0 Answers