- Home /
C# code to check whether two objects are touching
My friend and I are both making a 2d game with c# ,but we can't figure out how to make an if statement to check whether two objects are touching so can anyone tell me the code needed to check if a player is touch the goal for example.
Answer by Daniil-Manokhin · Feb 04, 2020 at 07:21 PM
To check whether the player is touching a specific object:
Go to your goal object
In the inspector window go to tags
Make a tag, for example "goal"
Add this code to your player object (make sure the player or goal has a RigidBody):
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Goal")
// Do stuff
}
Hope this helped!
Thanks so much.
By any chance do you know how to make the player get launched up. (As if it was on a bounce pad)?
If you have an attached Rigidbody, you can do something like: GetComponent<Rigidbody2D>().AddForce(transform.up, * <Launch strength>, Force2D$$anonymous$$ode.Impulse)
(haven't tested, but it should work)
Sorry, I don’t have unity open at the moment to give you an answer which I can test but you can try the code here:
https://answers.unity.com/questions/1216376/help-2d-launch-an-object-in-a-particular-direction.html
Hope it works, let me know!
Thanks for this!
I thought I'd point out that my IDE actually gives me a heads up that comparing tags with "==" is inefficient, and that there's a builtin method that is much faster for doing just that.
void OnTriggerEnter(Collider other)
{
if (other.transform.CompareTag("Goal"))
// Do stuff
}
Your answer
Follow this Question
Related Questions
2dToolkit and Physics2D.OverlapCircle 2 Answers
Inconsistent 2D collision detection since 5.2.3 1 Answer
Deactivate Key. 2 Answers
How do i make a player or move around any side of a platform 2 Answers