Skip to content

Instantly share code, notes, and snippets.

@david-alejandro-reyes-milian
Created June 29, 2022 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-alejandro-reyes-milian/cd739b2fc8718e37185a00e388d95db4 to your computer and use it in GitHub Desktop.
Save david-alejandro-reyes-milian/cd739b2fc8718e37185a00e388d95db4 to your computer and use it in GitHub Desktop.
Creates a ghost effect by duplicating the provided GO. Used for dashing commonly.
using System;
using UnityEngine;
public class GhostEffect : MonoBehaviour
{
[SerializeField] private GameObject ghostModel;
private GameObject _ghostModelWithMaterial;
[SerializeField] private GameObject ghostParent;
public float ghostDistance;
public Material ghostMaterial;
public float ghostLife;
private float _traveledDistance;
private Vector3 _lastPosition;
private void Start()
{
_ghostModelWithMaterial = Instantiate(ghostModel);
_ghostModelWithMaterial.SetActive(false);
ApplyMaterialTransparency();
foreach (var r in _ghostModelWithMaterial.GetComponentsInChildren<MeshRenderer>()) r.material = ghostMaterial;
}
private void ApplyMaterialTransparency()
{
var alphaColor = ghostMaterial.color;
alphaColor.a = .5f;
ghostMaterial.color = alphaColor;
}
private void FixedUpdate()
{
var parentPosition = ghostParent.transform.position;
var parentRotation = ghostParent.transform.rotation;
_traveledDistance = Vector3.Distance(_lastPosition, parentPosition);
_lastPosition = parentPosition;
if (_traveledDistance < ghostDistance) return;
_traveledDistance = 0f;
var instance = Instantiate(_ghostModelWithMaterial, parentPosition, parentRotation);
instance.SetActive(true);
Destroy(instance, ghostLife);
}
}
@david-alejandro-reyes-milian
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment