- Home /
Question by
ChilledSloth · Jul 12, 2020 at 02:22 PM ·
rotationprefabsinstantiate prefab
Instantiated Projectiles doesn't go in correct direction!
So, I have these projectiles instantiated at my empty object position.
As you can see in the screenshot the red capsule is supposed to be my gun and I've attached an empty GO at the tip of the capsule. when I'm rotating the capsule, the projectiles aren't rotating at the correct direction at which the red gun is facing(empty object at the tip of capsule) And they are just moving forward in the Z direction regardless of rotation. Here are my scripts.
PlayerController
public class PlayerController : MonoBehaviour
{
public Rigidbody rb;
public float speed= 100f;
public GameObject gun;
public Transform barrel;
public GameObject bullet;
public Camera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown(KeyCode.A))
{
rb.velocity = Vector3.left * speed;
}
if (Input.GetKeyDown(KeyCode.D))
{
rb.velocity = Vector3.right * speed;
}
ShootBullet();
}
void ShootBullet()
{
if (Input.GetMouseButtonDown(0))
{
GameObject go = Instantiate(bullet, gun.transform.position, gun.transform.rotation);
go.gameObject.GetComponent<Rigidbody>().velocity = transform.forward * 250 * Time.deltaTime;
Destroy(go, 3f);
}
}
Gun Rotation
public class GunRot : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
RotateAroundAxis();
}
void RotateAroundAxis()
{
float x = Input.GetAxis("Mouse X");
transform.Rotate(Vector3.up * x * 5f);
}
}
Comment
Best Answer
Answer by Shrimpey · Jul 12, 2020 at 04:15 PM
go.gameObject.GetComponent<Rigidbody>().velocity = transform.forward * 250 * Time.deltaTime;
You're using transform.forward, my guess is that you want to use gun.transform.forward or go.transform.forward (both should give the same result here).