Skip to content

Instantly share code, notes, and snippets.

@pentlander
Last active March 3, 2019 02:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pentlander/8b6e0bf38cff800801a4 to your computer and use it in GitHub Desktop.
Save pentlander/8b6e0bf38cff800801a4 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class LaserScript : Projectile {
public GameObject laserStart;
public GameObject laserMiddle;
public GameObject laserEnd;
public float maxLaserDistance;
private GameObject start;
private GameObject middle;
private GameObject end;
private float timer = 0f;
private float timerMax = 10f;
private float startSpriteWidth;
void InstantiateLaserPart(ref GameObject part, GameObject laserPart) {
if (part == null) {
part = Instantiate<GameObject>(laserPart);
part.transform.parent = gameObject.transform;
part.transform.localPosition = Vector2.zero;
part.transform.localEulerAngles = Vector2.zero;
}
}
RaycastHit2D RaycastDirection(Vector2 direction) {
return Physics2D.Raycast(
this.transform.position,
direction,
maxLaserDistance
);
}
void FadeLaser() {
timer -= Time.deltaTime;
if (timer <= 5) {
transform.localScale -= new Vector3(0f, transform.localScale.y) * Time.deltaTime;
if (transform.localScale.y <= 0.05) {
Destroy(gameObject);
}
}
}
void Start() {
timer = timerMax;
startSpriteWidth = laserStart.GetComponent<Renderer>().bounds.size.x;
InstantiateLaserPart(ref start, laserStart);
InstantiateLaserPart(ref middle, laserMiddle);
}
// Update is called once per frame
void Update() {
FadeLaser();
float currentLaserDistance = maxLaserDistance;
RaycastHit2D hit = RaycastDirection(this.transform.right);
if (hit.collider != null) {
currentLaserDistance = Vector2.Distance(hit.point, this.transform.position);
InstantiateLaserPart(ref end, laserEnd);
} else if (end != null) {
Destroy(end);
}
middle.transform.localScale = new Vector3(
currentLaserDistance - startSpriteWidth + 0.1f,
middle.transform.localScale.y,
middle.transform.localScale.z
);
middle.transform.localPosition = new Vector3(currentLaserDistance / 2f, 0f);
if (end != null) {
end.transform.localPosition = new Vector2(currentLaserDistance, 0f);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment