shooting projectile in the same direction the player faces

41 views Asked by At

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);
    }

}
2

There are 2 answers

0
Jason Hughes On BEST ANSWER

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.

0
Daqs On

weaponPoint.right is used as the direction to shoot. This assumes weaponPoint's right direction is the direction the player is facing.

.normalized ensures the direction vector has a length of 1.

projectileSpeed is used to control how fast the projectile moves.

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

    // 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>();

        // Assuming the weaponPoint right direction is the facing direction.
        Vector2 shootDirection = weaponPoint.right; 

        projectileRb.velocity = shootDirection.normalized * projectileSpeed;
    }
}