unity-game-engineprojectile

shooting projectile in the same direction the player faces


so i want to shoot a prefab projectile in the same direction the player faces. i keep looking for different ways to add velocity or force but it never "goes"

i have a weapon position thats supposed to make the projectile go in the direction of the position but it doesn't work

public class ShootProjectile : MonoBehaviour
{
    public Transform weaponPoint;
    public GameObject projectilePrefab;
    public float projectileSpeed = 100f;

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

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            Shoot();
        }


    }

    private void Shoot()
    {
        GameObject projectile = Instantiate(projectilePrefab, weaponPoint.position, Quaternion.identity);
        Rigidbody2D projectileRb = projectile.GetComponent<Rigidbody2D>();

        projectileRb.velocity = new Vector2 (0f, 2f);
    }

}

Solution

  • Quaternion.identity means always face toward the unrotated direction.

    Use Quaternion.LookAt(transform.forward) and it will go in the direction the current game object is facing.