0
\$\begingroup\$

I have 2 characters in my 2D game, I would like that if both of them are on the same Y axis, and there is no collider/object between them, for an animation to happen. I can't figure out how to check for the last one though... Thanks for the help!

EDIT :

Hello, I have used MrCranky's code and it seemingly looks like it should work, but I am having a problem with the syntax I think. Physics.Raycast((x,y) of the 1st player, new Vector3 (1,0,0), distance between them -2) So this code, if there is nothing between the player and the other character, it should give me a false. And it worked, but the problem is, even after I added an object between them, it stayed on false through every update, could you assist me with what am I doing wrong please?

\$\endgroup\$
3
\$\begingroup\$

The brute force solution would be to iterate over all objects which might be in between the two characters and test them each individually (GameObject.FindObjectsOfType is probably your friend here).

However a much simpler and cheaper solution would be to do a ray-cast from one character's position to the other. If any results are returned they'll be in the way of the two characters. Bear in mind that will draw a thin ray from the local origins of the characters though, if you need partial collisions (e.g. a collider just off to one side of that ray but which the character would hit if they tried to move towards the other character) then you'd need a sweep test (moving the character's collision volume along the path towards the other character) of some sort. You might be able to get away with 5 raytests instead - one in the centre and one for each corner of the character's AABB.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Hello, I have used this command and it seemingly looks like it should work, but I am having a problem with the syntax I think. Physics.Raycast((x,y) of the 1st player, new Vector3 (1,0,0), distance between them -2) So this code, if there is nothing between the player and the other character, it should give me a false. And it worked, but the problem is, even after I added an object between them, it stayed on false through every update, could you assist me with what am I doing wrong please? \$\endgroup\$ – Zee Mar 6 '15 at 22:17
  • \$\begingroup\$ There are a few things that might be tripping you up. First is the object in between the players has to have a physics collider of some sort (box, sphere, etc.). Second is that you need to make sure the ray is pointing the way you think (use Debug.DrawRay to check). Third is to make sure the layer mask isn't excluding the object you expect to hit (omit the parameter to search all layers). \$\endgroup\$ – MrCranky Mar 8 '15 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.