0
\$\begingroup\$

I'm very new to C# and Unity, and have been working on a projectile based weapon, and for the most part it's been working well. However, although the bullet fires facing the direction it's being shot horizontally, when shot up or down, the bullet is still parallel to the ground when shot. Any help would be appreciated, thanks!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerWeapon : MonoBehaviour
{
public GameObject bulletPrefab;

public Transform BulletSpawn;

public float bulletSpeed = 30;

public float lifeTime = 3;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Fire();
    }
}

private void Fire()
{
    GameObject bullet = Instantiate(bulletPrefab);

    Physics.IgnoreCollision(bullet.GetComponent<Collider>(),
        BulletSpawn.parent.GetComponent<Collider>());

    bullet.transform.position = BulletSpawn.position;

    Vector3 rotation = bullet.transform.rotation.eulerAngles;

    bullet.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);

    bullet.GetComponent<Rigidbody>().AddForce(BulletSpawn.forward * bulletSpeed, ForceMode.Impulse);

    StartCoroutine(DestroyBulletAfterTime(bullet, lifeTime));
    }

private IEnumerator DestroyBulletAfterTime(GameObject bullet, float delay)
{
    yield return new WaitForSeconds(delay);

    Destroy(bullet);
}
}
\$\endgroup\$
0
\$\begingroup\$

Two things:

  1. Don't futz with Euler angles, just face the direction you want to shoot.

    bullet.transform.forward = BulletSpawn.forward;

    This is equivalent to:

    bullet.transform.rotation = Quaternion.LookRotation(BulletSpawn.forward);

    Though with this form you, can also provide a second argument to control the twist rotation of the bullet around its forward axis.

  2. If bulletSpeed is a speed, ie. it's a distance travelled per second, then use it to calculate a velocity, not an impulse. This way you get exactly the speed you asked for, and you don't have to mentally convert your m/s numbers to N*s in the Inspector:

    bullet.GetComponent<Rigidbody>().AddForce(BulletSpawn.forward * bulletSpeed, ForceMode.VelocityChange);

    Or, more concisely, if this is the only influence acting on the bullet at launch:

    bullet.GetComponent<Rigidbody>().velocity = BulletSpawn.forward * bulletSpeed;

\$\endgroup\$
  • \$\begingroup\$ Great, thanks so much! \$\endgroup\$ – connorwgardner May 25 at 21:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.