I am making a game which involves two turrets which rotate 360 degrees and fire when I press the space bar. I am stuck with making the bullets actually fire in the direction the turret is facing. I am trying to get the rotation from the parent object of the turret because that part that actually swivels. When I am running the game and I rotate the turrets using the keyboard it is the pivot (the parent object of the turret) y-axis which changes. I need to find a way to get the rotation of the y-axis and have the bullet fire in that direction. The way I am currently trying to get the rotation is leaving me with numbers which are barely above zero (might as well be zero) even though I can see in the inspector that the y value is changing so obviously I am grabbing the wrong value.
using UnityEngine;
using System.Collections;
public class TurretScript : MonoBehaviour {
public Rigidbody2D Bullet;
public float bulletSpeed = .01f;
private float turretRotationSpeed = 5f;
void Update () {
if(Input.GetKey(KeyCode.S) && gameObject.tag == "T1")
counterClockwise();
if(Input.GetKey(KeyCode.J) && gameObject.tag == "T2")
counterClockwise();
if (Input.GetKey (KeyCode.F) && gameObject.tag == "T1")
clockwise ();
if (Input.GetKey (KeyCode.L) && gameObject.tag == "T2")
clockwise ();
if (Input.GetKey (KeyCode.Space)) {
fire ();
}
}
fire(){
Rigidbody2D newBullet = (Rigidbody2D) Instantiate(Bullet, transform.GetChild(0).position, transform.rotation);
float xDir = transform.parent.rotation.x;
float yDir = transform.parent.rotation.y;
Debug.Log (xDir + " " + yDir);
Vector2 force = new Vector2 (xDir * bulletSpeed, yDir * bulletSpeed);
newBullet.AddForce(force);}
}
I've just realized you're using RigidBody2D, so my bullet's update isn't appropriate, but I guess you'll be able to figure out by yourself the AddForce part of the problem.
– CletI do actually have an empty game object attached to the end of the turret. I had to do that so that the bullets would spawn at the end of the gun instead of halfway down the barrel. It is the GetChild of Rigidbody2D newBullet = (Rigidbody2D) Instantiate(Bullet, transform.GetChild(0).position, transform.rotation); However, its rotation does not change when I move the gun and am watching it in the inspector. The only rotation that changes is that of the pivot.
– michellejeanThe rotation you see in the inspector is in local space i.e. its rotation according to its parent. If the transform is a child of the turret, it is normal that its rotation stays the same even when the turret's rotation change. If the transform is setup as I mentioned in my answer, you just have to send a force towards the transform's forward direction by using transform.forward
– Clet