- Home /
Problem with bullet projectiles direction
Basically the bullets seem to instantiate in a certain direction which doesn't change but I don't seem to be able to find what's wrong. I believe it has to do with world space and local space. This is my code so far
 using UnityEngine;
 using System.Collections;
 
 public class Artificial_Intelligence : MonoBehaviour {
     
 private GameObject player;
 public int rotation_speed;
 public int speed;
 public int power;
 public int spawndistance;
 public GameObject prefab;
     
     // Use this for initialization
     void Start () {
      player = GameObject.Find("Player");
     
     }
     
     // Update is called once per frame
     void Update () {
         
         if (Vector3.Distance(player.transform.position, transform.position) < 7) {
         Quaternion finalrotation = Quaternion.LookRotation(player.transform.position - transform.position, Vector3.up);
     finalrotation.x = 0;
     finalrotation.z = 0;
     transform.rotation = Quaternion.Slerp(transform.rotation, finalrotation, Time.deltaTime * rotation_speed);
     Instantiate (prefab,transform.position, transform.rotation);
     prefab.rigidbody.AddForce(Vector3.forward * power);
     Physics.IgnoreCollision(prefab.collider, collider);
     transform.Translate(Vector3.forward * Time.deltaTime * speed);
         }
     }
I think the problem is that you instantiate your prefab (i suppose the projectile) with the position and rotation of the parent of this script, ins$$anonymous$$d of player's. Can you tell me what this script is attached to ?
Shouldn't it be prefab.rigidbody.AddForce(transform.rotation Vector3.forward power) ?
Answer by Seth-Bergman · Nov 08, 2012 at 07:33 PM
there are a couple of issues here:
 //you need to declare a reference to the instantiated object
 GameObject myBullet = Instantiate (prefab,transform.position, transform.rotation) as GameObject;
 // use transform.forward for the relevant direction
 myBullet.rigidbody.AddForce(myBullet.transform.forward * power);
 Physics.IgnoreCollision(myBullet.collider, collider);
 transform.Translate(Vector3.forward * Time.deltaTime * speed);
mainly, for AddForce to work right we need to convert our local direction to a world direction, which is what transform.forward does
also, you are instantiating a bullet every frame, that will add up quickly.. you should probably cut that back..
Answer by JustinRyder · Nov 08, 2012 at 08:22 PM
 rigidbody.AddForce(Vector3.forward, Space.Self);
 
 rigidbody.AddForce(transform.forward);
These will both add a forward force in local space.
Your answer
 
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Create variable based on local axis 1 Answer
Distribute terrain in zones 3 Answers
instantiate object 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                