Hey everyone, I’ve been having some difficulties with a projectile script thats really been causing problems for me. I’ve finally managed to instantiate the projectile in the correct direction with the ray pointing in the right direction as well, but ever since I started using “transform.forward”, the bullet flys in all kinds of directions. Does anyone know how to stop it from doing that?
using UnityEngine;
using System.Collections;
public class MusketBullet : MonoBehaviour {
//Variables Start___________________________________
//The explosion effect is attached to this
//in the inspector
public GameObject mudParticle;
//A quick reference.
private Transform myTransform;
//The projectiles flight speed.
private float projectileSpeed = 20;
//Prevent the projectile from causing
//further harm once it has hit something.
private bool expended = false;
//A ray projected in front of the projectile
//to see if it will hit a recognisable collider.
private RaycastHit hit;
//The range of that ray.
private float range = 1.5f;
//The life span of the projectile.
private float expireTime = 10;
//Variables End_____________________________________
// Use this for initialization
void Start()
{
myTransform = transform;
transform.Rotate(0.0f, 270.0f, 0.0f);
//As soon as the projectile is created start a countdown
//to destroy it.
Destroy (gameObject, expireTime);
}
// Update is called once per frame
void Update ()
{
//Translate the projectile in the up direction (the pointed
//end of the projectile).
myTransform.Translate(transform.forward * projectileSpeed * Time.deltaTime);
//If the ray hits something then execute this code.
Debug.DrawRay( myTransform.position, myTransform.forward * range, Color.red );
if(Physics.Raycast(myTransform.position,myTransform.forward, out hit, range) && expended == false)
{
//If the collider has the tag of Floor then..
Debug.Log( "Ray Hit (floorMud) : " + hit.collider.transform.tag );
{
expended = true;
//Instantiate an explosion effect.
Instantiate(mudParticle, hit.point, Quaternion.identity);
//Make the projectile become invisible.
myTransform.renderer.enabled = false;
}
}
}
IEnumerator DestroyMyselfAfterSomeTime()
{
//Wait for the timer to count up to the expireTime
//and then destroy the projectile.
yield return new WaitForSeconds(expireTime);
Destroy(myTransform.gameObject);
}
}