I’ve noticed that whenever I leave an impact effect it does not stick to my enemies. It sort of looks like its stuck in space and doesn’t follow the object as its pushed back.
Can someone please explain to me what can be done in order to have my impact effect stick on the surface of objects it collides with?
Thanks again for any insight that is given.
Below is my projectile code.
using UnityEngine;
using System.Collections;
public class Projectile : MonoBehaviour
{
public GameObject impactPrefab;
public Rigidbody thisRigidbody;
private Collider thisCollider;
public int damage = 10;
public bool LookRotation = true;
private bool Missile = false;
private bool explodeOnTimer = false;
float timer;
private Vector3 previousPosition;
void Start()
{
thisRigidbody = GetComponent<Rigidbody>();
thisCollider = GetComponent<Collider>();
previousPosition = transform.position;
}
void FixedUpdate()
{
if (LookRotation && timer >= 0.05f)
{
transform.rotation = Quaternion.LookRotation(thisRigidbody.velocity);
}
CheckCollision(previousPosition);
previousPosition = transform.position;
}
void CheckCollision(Vector3 prevPos)
{
RaycastHit hit;
Vector3 direction = transform.position - prevPos;
Ray ray = new Ray(prevPos, direction);
float dist = Vector3.Distance(transform.position, prevPos);
if (Physics.Raycast(ray, out hit, dist))
{
transform.position = hit.point;
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, hit.normal);
Vector3 pos = hit.point;
Instantiate(impactPrefab, pos, rot);
if (!explodeOnTimer && Missile == false)
{
Destroy(gameObject);
}
else if (Missile == true)
{
thisCollider.enabled = false;
thisRigidbody.velocity = Vector3.zero;
Destroy(gameObject, 5);
}
}
}
void OnCollisionEnter(Collision collision)
{
IDamageable damageable = collision.gameObject.GetComponent<IDamageable>();
if (damageable != null)
{
damageable.DealDamage(damage);
}
if (collision.gameObject.tag != "FX")
{
ContactPoint contact = collision.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, contact.normal);
Vector3 pos = contact.point;
Instantiate(impactPrefab, pos, rot);
if (!explodeOnTimer && Missile == false)
{
Destroy(gameObject);
}
else if (Missile == true)
{
thisCollider.enabled = false;
thisRigidbody.velocity = Vector3.zero;
Destroy(gameObject, 5);
}
}
}
}
You can parent the object being instantiated to the object that was collided with. Something like this should work.
var impactEffect = Instantiate(impactPrefab, pos, rot);
impactEffect.transform.SetParent(transform, true);
Bonus tip! Use gameObject.CompareTag(“SomeTag”) rather than gameObject.tag == “SomeTag” if you can help it. It’s ever so slightly faster and doesn’t generate garbage.
What the code does is make your impact prefab a child object of the enemy GameObject after instantiating it, thus making it “stick” to the enemy by following its position and rotation.
It’s the runtime equivalent of dragging a GameObject onto another GameObject in the hierarchy window.