NewBieProgrammer
NewBieProgrammer

Reputation: 17

Player don't shoot projectiles when he is in movement

When I shoot and the player is standing still, the projectiles works fine, but when I'm moving or jumping forward, the projectiles does not work.

I think it's happening because of my bullet code. Im beginner in Unity, so I think there's something wrong with the code.

void Update()
{
    transform.Translate(Vector3.right * speed * Time.deltaTime);
}

private void OnTriggerEnter2D(Collider2D other)
{
    Destroy(gameObject);
}

Upvotes: 1

Views: 61

Answers (1)

Fredrik
Fredrik

Reputation: 5108

I'm pretty sure I know why you're getting this issue but I'll take some time to show you how you could debug this in the future.

So you're saying "projectiles don't work" which doesn't really mean anything but I'll assume it means "They don't spawn".

This can be because of two reasons:

  1. Something is preventing them from spawning
  2. They're deleted immediately

In our case it's probably number 2. When you're moving forward the player instantly collides with its own projectile, which makes it disappear.

To make sure this is the case, you can check which object causes the delete by editing your collision code:

private void OnTriggerEnter2D(Collider2D other)
{
    Debug.Log(other.name);
    Destroy(gameObject);
}

It's probably player, so you don't want the player to collide with its own bullets. You can solve this in 2 ways:

  1. When checking for collision, put the Destroy in a conditional statement such as: if (other.tag != "Player")
  2. Add layer to the bullet and prevent that layer from colliding with the player's layer.
  3. Exclude collisions between the bullet and player in the Start() method with Physics.IgnoreCollision(MyCollider, PlayerCollider); (Or Physics2D, if 2D)

For the sake of simplicity/solving your issue, let's go with number 1; edit your collision code to be conditional:

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag != "Player") 
    {
        Destroy(gameObject);
    }
}

and then go to the player object and create a new Layer called "Player", and assign it to the player object.

Upvotes: 1

Related Questions