Home > Mobile >  How can I reference the Z axis on a 2D object to spawn a projectile behind the player in the scene?
How can I reference the Z axis on a 2D object to spawn a projectile behind the player in the scene?

Time:11-04

I've written a Shoot function that works pretty well, but I'd like the projectile object to spawn behind the player object in the scene. I've tried setting the prefab of the projectile to -1 on the z axis which didn't seem to work. I suspect it's because that is overwritten by the instantiation of the object. I also briefly tried using Vector3 to spawn the projectile with the following code, but that didn't work either.

Here is my code.

Vector3 spawn = new Vector3(0, 0.5f, -1)
rb.position   spawn

Projectile script:

    public class Projectile : MonoBehaviour
{
    Rigidbody2D rb;
    
    Vector2 launch = new Vector2(0, 1);

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (transform.position.magnitude > 1000.0f)
        {
            Destroy(gameObject);
        }
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        Destroy(gameObject);
    }

    public void Shoot(float force)
    {
        rb.AddForce(launch * force);
    }
}

Shoot function from player script:

void Shoot()
{
    GameObject projectileObject = Instantiate(projectilePrefab, rb.position   Vector2.up * 0.5f, Quaternion.identity);
    Projectile projectile = projectileObject.GetComponent<Projectile>();
    projectile.Shoot(300);

}

CodePudding user response:

If projectile and player are both 2d and you only want the projectile to be rendered behind the player, it should be in a different sorting layer or it should have a lower sortingOrder than the player's renderer.

See here for more info.

  • Related