Reputation: 17
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
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:
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:
if (other.tag != "Player")
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