I want to shoot a projectile in the direction the gun is facing.
With my current script it only shoots vertically. (I can also make it go horizontally but that's it).
This is my GunController
class:
public Transform guntip;
public GameObject bullet;
float fireRate = 0.5f;
float nextFire = 0f;
void Update ()
{
//playershooting
if (Input.GetAxisRaw("Fire1") > 0)
{
fireRocket();
}
}
void fireRocket()
{
if(Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(bullet, guntip.position, Quaternion.Euler(new Vector3(0, 0, 0)));
}
}
This is my ProjectileController
class:
Rigidbody2D MyRB;
public float rocketSpeed;
void Awake()
{
MyRB = GetComponent();
MyRB.AddForce(new Vector2(0, 1) * rocketSpeed, ForceMode2D.Impulse); // explosive force, change vector 2 for horizontal shooting
}
Answer
Instantiate(bullet, guntip.position, guntip.rotation);
You need to inherit rotation of guntip to make bullets face that way.
To make bullet go towards the direction it's facing, if your 2D setup is top-down:
MyRB.AddForce(transform.up * rocketSpeed, ForceMode2D.Impulse);
If your 2D setup is side-scroller:
MyRB.AddForce(transform.right * rocketSpeed, ForceMode2D.Impulse);
No comments:
Post a Comment