- Home /
How do I instantiate a projectile along the path of a raycast?
using UnityEngine;
using System.Collections;
public class PoopieShot2 : MonoBehaviour
{
public float hitForce = 1000f;
public Camera myCam;
public GameObject blast;
public GameObject explosion;
void Update ()
{
// GetComponent<AudioSource>().Play();
RaycastHit hit;
Ray ray = myCam.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay (ray.origin, ray.direction * hitForce, Color.red);
if (Physics.Raycast (ray, out hit, hitForce))
{
}
if(Input.GetButtonDown("Fire1"))
{
Instantiate(blast, transform.position, transform.rotation);
if (hit.rigidbody != null)
{
hit.rigidbody.AddForceAtPosition (ray.direction * hitForce, hit.point);
Debug.Log("Hit");
Instantiate(explosion, hit.point, Quaternion.identity);
Destroy(hit.transform.gameObject);
}
}
}
}
This what I have as of now, I can hit rigidbodies with this but I can't seem to get the projectile to fly towards them, it's always off to the side. Also, could someone tell me how I can delay an explosion on a game object, like delaying the destruction of it after a raycast, or should I just program any destructible objects to blow up after being hit by a ray cast on a separate script? Anyway, thanks for your help in advance!
Comment
Best Answer
Answer by JinJin · Mar 13, 2015 at 06:24 PM
change
Instantiate(blast, transform.position, transform.rotation);
to
Instantiate(blast, transform.position, Quaternion.LookRotation(ray.direction));