Why are my bullets spawning only from the original muzzle transform?
This is for a top-down 2D game:
After successfully spawning bullets from my player instance's transform, now that I disable the bullets as a trigger, there is some collision issues throwing the player around. To solve this, I created a child empty named "Muzzle", on my player object. However, when I fire bullets, they only spawn from the original position of my muzzle object, regardless of where the player moves. I have focused on the muzzle object while testing and it does indeed move with the player, yet the bullets persist on using the first location.
Any help would be very appreciated!
Here's the pertinent code (don't mind the commenting):
public Player_Controller player_script;
public Player_Stats stats_script;
public GameObject bullet;
public GameObject muzzleObj;
private Rigidbody2D pRb;
private float bulletSpeed;
//private Vector3 offsetPosition;
private Quaternion offsetRotation;
private Vector3 muzzle;
// Use this for initialization
void Start () {
//muzzleObj = transform.FindInChildren ("Muzzle").gameObject;
//muzzleObj = GameObject.Find("Muzzle");
pRb = player_script.Player1.GetComponent<Rigidbody2D> ();
bulletSpeed = 500.0f;
}
// Update is called once per frame
void Update () {
muzzleObj = GameObject.Find("Muzzle");
//muzzle = transform.Find ("Muzzle").gameObject.transform.position;
//muzzle = transform.FindInChildren("Muzzle").position;
muzzle = muzzleObj.transform.position;
if (muzzle == null) {
Debug.Log ("null");
}
Fire ();
}
void FixedUpdate (){
}
void Fire (){
if(Input.GetMouseButtonDown(0)){//Left click is 0, right click is 1, middle click is 2
GameObject bulletClone;
float maxBulletTime = 500;
float bulletTime = 0;
//offsetPosition = new Vector3(pRb.transform.position.x, pRb.transform.position.y, pRb.transform.position.z);
offsetRotation = Quaternion.Euler (pRb.transform.rotation.x, pRb.transform.rotation.y, pRb.transform.rotation.z);
//Spawn bullet at Player1's location and with same orientation
bulletClone = Instantiate(bullet, muzzle, offsetRotation);
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
Vector3 bTarget = mousePos - bulletClone.transform.position;
bTarget = bTarget.normalized;//REMEMBER! Normalizing this prevents the speed to arrive to target point from changing based on how far away target point is from origin point.
bulletClone.GetComponent<Rigidbody2D>().AddForce(bTarget * (bulletSpeed * Time.deltaTime), ForceMode2D.Impulse);
/*if(bulletTime == maxBulletTime){
Destroy(bulletClone);
}else{*/
//Add force to the cloned bullet in it's forward direction
//bulletClone.transform.position = Vector3.MoveTowards(bulletClone.transform.position, bTarget, (bulletSpeed));// * Time.deltaTime));
// bulletTime += Time.deltaTime;
//}
}
}
"muzzleObj" is assigned an instance in the editor when I test.
I receive no errors.
Answer by turosteel · Jan 07, 2018 at 06:02 AM
I don't know why....
but it now works....
Strange.