- Home /
specifying objects onCollisionEnter?
i have a quick question which will be super easy to answer. im currently making a infinate runner type game for a class project and i need some help with collsions. the game is setup as a 2d platform where a character is running (or made to look like there running with a scrolling texture) through a infinite tunnel, the player has to avoid obstacles similar to flappy birds using jumps. The script i'm using at the moment is setup so that when the player collieds with obstacles the game will reload.
the issue: the issue is that the code ive used apples to all collsions so when the player hits the ground platform the game reloads
what i want to happen: i want the character to be able to run on a platform and die when he hits the a specific obstacle.
so im think i need to specify a gameobject to collide with?
any help would be great :D thanks heaps
this is my current code:
// Update is called once per frame
void Update ()
{
// Jump
if (Input.GetKeyUp("space"))
{
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce(jumpForce);
}
// Die by being off screen
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Die();
}
}
// Die by collision
void OnCollisionEnter2D(Collision2D other)
{
Die();
}
void Die()
{
Application.LoadLevel(Application.loadedLevel);
}
}
Answer by rgowen · May 17, 2014 at 05:35 AM
The onCollisionEnter()
function gets passed a Collision2D
object, with which you can find out what GameObject
it is hitting:
// Die by collision
void OnCollisionEnter2D(Collision2D other)
{
if(other.collider.gameObject == deadlyGameObject)
{
Die();
}
}
You might need to tweak the evaluation in the if
statement, but that's the principle.
Typically you have a group of items you want to be deadly. Ins$$anonymous$$d of checking against a specific game object, you check the tag. So line 4 of @$$anonymous$$wen's code would be:
if (other.collider.tag == "Deadly")
https://docs.unity3d.com/Documentation/Components/class-Tag$$anonymous$$anager.html
Your answer
![](https://koobas.hobune.stream/wayback/20220613145224im_/https://answers.unity.com/themes/thub/images/avi.jpg)