How do I make a laser that bounces around a room?
Hi there, I am working on my first project of 2021 and have run into a little issue. I am trying to make a "laser pinball" sort of 2D game in which a laser is shot from a turret at an angle chosen by the user (they aim and shoot it), the beam then bounces around the room, interacting with various obsticales throughout whilst attempting to hit a goal located somewhere in the room.
I have attempted to script the laser via tutorials and personal knowledge... but I can't quite figure it out! I think all the pieces are here..
So far the laser shoots and stops once it hits a wall (polygon collider 2D). At this point I am unable to figure out how to script the laser reflecting off of the walls.
Here's my script: (c#)
public class Laser : MonoBehaviour
{
[SerializeField] private float defDistanceRay = 100;
public Transform laserFirePoint;
public LineRenderer m_lineRenderer;
public Transform CrosshairPos;//
public Transform m_transform;
private Vector3 laserDir;//
private void Awake()
{
laserDir = new Vector3();
m_transform = GetComponent<Transform>();
}
private void Update()
{
ShootLaser();
}
void ShootLaser()
{
laserDir = (CrosshairPos.position - m_transform.position).normalized;//
if (Physics2D.Raycast(m_transform.position, laserDir))
{
RaycastHit2D _hit = Physics2D.Raycast(m_transform.position, laserDir);
Draw2DRay(laserFirePoint.position, _hit.point);
}
else
{
Draw2DRay(laserFirePoint.position, laserDir * defDistanceRay);
}
}
void Draw2DRay(Vector3 startPos, Vector3 endPos)
{
m_lineRenderer.SetPosition(0, startPos);
m_lineRenderer.SetPosition(1, endPos);
}
}
Any help is much appreciated!
Your answer
Follow this Question
Related Questions
How to change the position of a Raycast (on Center of the Player 2D)? 0 Answers
Tiles are only being removed if raycast fired between 0 and 90 degrees clockwise from character 0 Answers
LineRenderer Raycast Gun Bug 1 Answer
Making a GameObject follow the direction of a RayCast 1 Answer
Why does this code run infinitely? 1 Answer