- Home /
Checking collision direction.
I'm writing this new controller that uses a rigid body as the main character. What I would like to implement into it, is a way to tell if a character is touching a wall and what side of the character side of the character the wall is touching.(meaning right, left, back and front for animators sake) I know character controllers have a method detect collision from different sides but do rigid bodies have one as well? Or will I have to create away to do it with raycast? If so I think I should say I have never worked well with arrays and if you can could you bring up an example. The main problem with this is I really don't know what direction (hahaha puns) I should go with this.
and if you do show any code can it please show it in c#? if not it'll be fine
Answer by virgiliu · May 28, 2015 at 06:00 AM
Create 2 child objects on the character, put them one at the left, one at the right.
Set up a check radius in the controller.
Then on collision enter do a Physics2D.OverlapCircle() and see which one of the points is hitting. http://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html
Play with the radius so that it covers most of the body.
Something like this (didn't test but it should give you a good starting point):
public GameObject leftCheck;
public GameObject rightCheck;
public float directionCheckRadius = 0.4f; // Play with this until you find the right radius
public LayerMask wallLayer; // Set it to whatever you want to check collision against, optional but helps with speed to not check against every layer
void OnCollisionEnter2D(Collision2D other)
{
bool rightHit = Physics2D.OverlapCircle(leftCheck.position, directionCheckRadius, wallLayer);
bool leftHit = Physics2D.OverlapCircle(leftCheck.position, directionCheckRadius, wallLayer);
if(rightHit) Debug.Log("Hit on right");
if(leftHit) Debug.Log("Hit on right");
}
...Or you could do raycasting from each side by setting up a point at the top, middle and bottom of the character for each side so you can detect even if the character is jumping and collision is happening with only their head or feet.
This might also help https://youtu.be/99HFfubBjYg?t=15m27s
does my leftcheck and rightcheck have to be game objects I could i make them transforms cause its giving me an error with them as gameobjects but when I swapped them with transforms to get their positions nothing happened when walked up to the wall.and how would I use this with a 3 dimensional object. I'm using the thirdperson controller
Your answer
Follow this Question
Related Questions
Collision-detection ALWAYS happens 1 Answer
collision detection on child rigidbodies 1 Answer
Getting Turret to Fire on the Correct Top-Down Plane 0 Answers
rigid bodies passing through one another. 1 Answer
How can I apply a force to an object in the opposite direction of the object it's colliding with? 2 Answers