Question by
zoilei7 · Jul 20, 2020 at 12:46 PM ·
2draycastlaserlaser beam
Bouncing laser, wierd flickering
Hello Guys!
I am trying to make a 2D bouncing laser, but sometimes it reflects, sometimes dont. The script should make X number of rays but it does not. The Scene view shows how the laser should bounce with the little white line, but somehow it doesnt bounce there. Any idea how to fix it to have a continous laser beam?
Some screenshots:
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LaserShot : MonoBehaviour
{
LineRenderer lineRenderer;
public float maxLength;
public int reflections;
Ray2D ray;
RaycastHit2D hit;
public GameObject prefab;
// Start is called before the first frame update
void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
}
// Update is called once per frame
private void Update()
{
ray = new Ray2D(transform.position, transform.up);
Debug.DrawRay(transform.position, transform.up);
lineRenderer.positionCount = 1;
lineRenderer.SetPosition(0, transform.position);
float remainLength = maxLength;
for (int i = 0; i < reflections; i++)
{
hit = Physics2D.Raycast(ray.origin, ray.direction);
if (hit.collider != null)
{
lineRenderer.positionCount += 1;
Vector3 lrpoint = hit.point;
lrpoint.z = -1;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, lrpoint);
//Instantiate(prefab, hit.point, Quaternion.identity);
remainLength -= Vector2.Distance(ray.origin, lrpoint);
Vector2 dir = ray.direction;
ray = new Ray2D(lrpoint, Vector2.Reflect(dir, hit.normal));
Debug.DrawRay(hit.point, Vector2.Reflect(dir, hit.normal));
if (hit.collider.tag != "Wall")
{
break;
}
}
else
{
lineRenderer.positionCount += 1;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, ray.origin + ray.direction * remainLength);
}
}
}
}
screenshot-from-2020-07-20-14-44-28.png
(491.1 kB)
screenshot-from-2020-07-20-14-43-42.png
(445.3 kB)
Comment
Your answer
Follow this Question
Related Questions
Raycast Reflection 2D 1 Answer
How to shoot a laser beam in a 2.5d game 0 Answers
Need Raycast2d to point where my ship is looking 0 Answers
2D raycast only returns true. 1 Answer
Making a GameObject follow the direction of a RayCast 1 Answer