- Home /
My bullet has no velocity after it is spawned.
I can instantiate my bullet but no code i put after it will give it a velocity. Addforce and transform won't work. I keep getting errors maybe because I'm using Unity 5. Please help me. I can post the whole code if requested but I'm pretty sure all I need is this last line. Also I'm not getting an error as technically the prefab is spawned it just doesn't have any velocity. The prefab for the bullet has a simple destroy gameobject when it collides script.
using UnityEngine;
using System.Collections;
public class EnemyAIScript : MonoBehaviour
{
public Transform player;
public float playerDistance;
public float rotationDamping;
public float chaseStartRange;
public float moveSpeed;
public static bool isPlayerAlive = true;
public float fireRate;
public float maxFire;
public float nextFire;
public GameObject BulletPrefab;
public float BulletSpeed;
void Update ()
{
Vector3 direction = transform.position;
if (isPlayerAlive)
{
playerDistance = Vector3.Distance (player.position, transform.position);
if (playerDistance < 20f)
{
lookAtPlayer ();
}
if (playerDistance < 20f)
{
if (playerDistance > 8f)
{
chase ();
}
else if (playerDistance < 8f)
{
attack ();
}
}
}
}
void lookAtPlayer ()
{
Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * rotationDamping);
}
void chase ()
{
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
void attack ()
{
if (Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate (BulletPrefab, GameObject.Find ("spawnPoint").transform.position, Quaternion.identity);
}
}
Answer by LSPressWorks · Mar 31, 2015 at 02:55 PM
From what I can tell of that you're not actually calling the function to apply speed to that object after it's instantiated.
i.e.
var spawnedBullet : GameObject;
nextFire = Time.time + fireRate;
spawnedBullet = Instantiate (BulletPrefab, GameObject.Find ("spawnPoint").transform.position, Quaternion.identity);
spawnedBullet.RigidBody.AddForce(x,y,x,ForceMode);
Sorry. Unfortunately this didn't work. $$anonymous$$onodevelop first asked me to change the colon between var spawnedBullet and GameObject, and when I did the errors flooded in fro mthere. Thanks for trying to help me.
Actually managed to solve the problem. I added a public Vector3 velocity at the top of the script and then added; nextfire = Time.time + firerate
Rigidbody instantiatedProjectile = Instantiate
(BulletPrefab, GameObject.Find
("spawnPoint").transform.position, Quaternion.identity) as
Rigidbody;
instantiatedProjectile.velocity =
transform.TransformDirection (new Vector3 (0, 0, BulletSpeed));
Thanks for answering again though.