-
-
Notifications
You must be signed in to change notification settings - Fork 32
Home
- Why do my asteroids not pass through the boundaries?
- Why can my player ship pass through the boundaries?
- Why does nothing happen when a bullet hits an asteroid?
If your asteroids are unable to pass through the boundaries, then this most likely means the two are objects are colliding, but we actually want collision to be disabled between these objects. To do this, we set the game objects to be on different physics layers so we can turn off collision between the two layers in the physics settings.
The asteroids should have their layer set to "Asteroid" and the boundaries should be set to "Boundary". Make sure to set this on the prefabs if you have them so it applies to all instances of the game object. After doing this, we can go to Edit > Project Settings > Physics 2D
and uncheck collision between Asteroid/Boundary
in the collision matrix.
If your player ship is able to pass through the boundaries, this implies no collision is being detected between those objects, but we want collision to be enabled. There could be a couple different reasons for this.
Collision can be enabled/disabled for different layers by changing the collision matrix found in Edit > Project Settings > Physics 2D
. The player ship should have its layer set to "Player" and the boundaries should be set to "Boundary". Make sure the checkbox for Player/Boundary
collision is enabled in the collision matrix. It should already be enabled by default.
Another possible cause could be that either the boundaries or the player ship's collider has the "Is Trigger" property checked on. Any object that is set to be a trigger will detect collisions with other objects but won't affect the actual physics simulation. We want the objects in this game to not be triggers.
If you are still having problem with collision, make sure your player ship has a Rigidbody2D
component attached to it. For collision to work between any two objects, at least one of them must be a rigidbody.
In the Asteroid.cs
script, the code is checking when the asteroid collides with a bullet by comparing the tag of the incoming object. If nothing is happening when a bullet collides with an asteroid, it might be that you have forgotten to set the tag of your bullet prefab to "Bullet", or there could simply be a mistake in the name or spelling.
It is also possible that you are comparing the name of the incoming game object rather than the tag, gameObject.name
vs gameObject.tag
. It's generally a better practice to use tags over names.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
//...
}
}
Alternatively, your objects might be missing a Rigidbody2D
component, without which collisions will not occur. Lastly, make sure the collider components do not have the "Is Trigger" property checked on.