简体   繁体   中英

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

Thanks in advance for any advice/direction!

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 because that is overwritten by the instantiation of the object.

Here is the code I'm currently working with. I also briefly tried using Vector3 to spawn the projectile with the following code, but that didn't work either.

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

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM