using System.Collections; using System.Collections.Generic; using UnityEngine; public class Laser : MonoBehaviour { public bool flipDirection; public int power = 1; float maxDistance = 1000.0f; bool isHorizontal; LineRenderer laserLine; GameObject lastChargePoint; void Start() { laserLine = GetComponent(); isHorizontal = GetComponent().isHorizontal; } void Update() { RaycastHit2D hit = DrawLaser(transform.position); HandleHit(hit); } RaycastHit2D DrawLaser(Vector3 startPosition) { laserLine.SetPosition(0, startPosition); RaycastHit2D hit; if (isHorizontal) { float endpointY = flipDirection ? startPosition.y - maxDistance : startPosition.y + maxDistance; hit = Physics2D.Raycast(startPosition, flipDirection ? Vector2.down : Vector2.up); if (hit.collider) laserLine.SetPosition(1, hit.point); else laserLine.SetPosition(1, new Vector3(startPosition.x, endpointY, 0)); } else { float endpointX = flipDirection ? startPosition.x - maxDistance : startPosition.x + maxDistance; hit = Physics2D.Raycast(startPosition, flipDirection ? Vector2.left : Vector2.right); if (hit.collider) laserLine.SetPosition(1, hit.point); else laserLine.SetPosition(1, new Vector3(endpointX, startPosition.y, 0)); } return hit; } void HandleHit(RaycastHit2D hit) { if (hit.collider) { if (hit.collider.tag == "Mirror") HitMirror(hit); if (hit.collider.tag == "Charge Point") HitChargePoint(hit); } else HitNothing(); } void HitMirror(RaycastHit2D hit) { if (isHorizontal) { // TODO } else { // TODO } } void HitChargePoint(RaycastHit2D hit) { if (hit.collider.gameObject != lastChargePoint) hit.collider.GetComponent().adjustCharges(power); lastChargePoint = hit.collider.gameObject; } void HitNothing() { if (lastChargePoint) lastChargePoint.GetComponent().adjustCharges(power * -1); lastChargePoint = null; } void OnDrawGizmosSelected() { float distance = 1.0f; isHorizontal = GetComponent().isHorizontal; Vector3 offset = isHorizontal ? new Vector3(0, distance, 0) : new Vector3(distance, 0, 0); Gizmos.color = Color.blue; Gizmos.DrawLine(transform.position, flipDirection ? transform.position - offset : transform.position + offset); } }