2D collision not being detected?
I have my player moving through the map with this:
transform.Translate(xSpeed, ySpeed, 0);
I have added a rigidbody2d with 0 gravity and a box collider to the player. I then added a cube and spread it out across the track, and added a box collider to this and tagged it as "enemy", and the player passes through this as they travel through the map. I have tried this:
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.CompareTag("enemy"))
{
Debug.Log("Hello");
}
}
As well as:
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.CompareTag("enemy"))
{
Destroy (gameObject);
}
}
However nothing happens with either of these. Any ideas would be appreciated. Thanks
Answer by tanoshimi · Oct 04, 2015 at 09:37 PM
Firstly, if you're using 2D physics you need a BoxCollider2D component, not a BoxCollider.
Secondly, don't move the object with transform.Translate. This will "teleport" the object and not respect physics collisions. Use Rigidbody2D.MovePosition instead - http://docs.unity3d.com/ScriptReference/Rigidbody2D.MovePosition.html
Thirdly, when debugging collision problems, always use Debug.Log to check that the tag of the thing you're colliding with really is "enemy" and not, say, "Enemy"...
On that page though it says not recommended for moving large distances... $$anonymous$$y player is constantly moving across the map so should this still be used?
Your answer
Follow this Question
Related Questions
Having a couple of problems regarding 2D Movement. 1 Answer
Unity jump from one canvas scene to another scene with canvas 2 Answers
Disable load new level until all enemies are dead 2 Answers
I'm working with the corgi-engine/inventory engine and need help with a script. 1 Answer
Masking based on angles 0 Answers