- Home /
Collision detection not working properly with 2D sprites
Hey all,
I'm trying to get collision detection working for sprites (I'm using SM2).
Both sprites have a Box Collider. I have ticked 'Is Trigger' for both of them. I have set X and Y to the width and height of the sprite for both of them, and set Z to 3 just so it has some sort of thickness.
One of the sprites has a rigid body. I unticked 'Use Gravity' and left the other settings as default.
Here is my code in the script that's attached to the object with the rigid body:
public void OnTriggerEnter(Collider c)
{
Debug.Log("Collided!");
}
Now the scenario. The object that doesn't have the rigid body is actually a prefab, I am creating clones of it every few seconds and moving them across the screen. If they hit the other object (the one with the rigid body), I should get a "Collided!" message in the console. It works IF i move the rigid body object (with mouse input) AFTER the clone has spawned and they collide. However, if a clone spawns, moves across the screen and hits the rigid body object, and I have not moved the rigid body object (via mouse input), then there's no "Collided!" message, hence no collision. Any ideas why?
Note: When the collision works, the rigid body object is not moving at the time of collision. It has stopped moving by the time the clone hits it, and collision works. If I then leave the rigid body object in its place, and another clone spawns in the same place as the first clone, moves across the screen and hits the rigid body object, there is no collision.
It also depends on how you move your objects. Try marking is$$anonymous$$inematic.
marking 'is$$anonymous$$inematic' made it worse, it only collides now while the rigid body object is actually moving during the collision.
I logged out the positions of both sprites. The positions are the same in both scenarios (when I move the rigid body object and when i don't move it). Yet, collision works when I move it, and doesn't work when I don't move it. It's as though when I move the object, something with it says 'ok i'm ready to run OnTriggerEnter when I collide with something'. Then as soon as it does collide with something, it never runs OnTriggerEvent anymore, until I move the object again. Like the trigger gets turned off when the trigger runs, then turns back on when I move the object.
Answer by disband85 · Dec 09, 2010 at 05:32 AM
Fixed the problem. I added a rigid body to the other object.
Your answer
Follow this Question
Related Questions
Weapon System with collide detection (Helps with script pls)!!! 0 Answers
Collision Enter one of the objects ? 1 Answer
How to make an object follow along the shape of another? 3 Answers
Fitting 2D collider to a sprite 0 Answers
Particle Collision / Trigger not being reported to On_xx Event 1 Answer