- Home /
Make Ray hit own collider
I've made about 80% of my character controller and i'm tying up loose ends.
PROBLEM:
If moved, the character will continue to move unless a ray hits a wall in front of him. The ray distance is calculated by the collider radius and collider height, and originates from the transform.position and heads in the movement direction.
Moving in an X, Z, and Y position individually (X and Z together) works well, but it's when I merge the X and the Y that the results are kind of bleh.
WHAT I WANT TO ACCOMPLISH:
Send a ray out from the transform.position. From there, I want to somehow (by the will of God) hit the transforms' collider. Then I want to take the hit distance and send out a new ray that will check for any collisions within the current movement direction, and get on with my life.
Any suggestions on how to accomplish the desired behavior?
Additional Information:
It's a capsule collider
I really don't want to use OnCollisionEnter()
Answer by robertbu · Mar 11, 2014 at 01:27 AM
Colliders are one-sided, so you cannot cast outward and hit the collider. What you can do, is pick a point along the ray that is beyond any possibility of being inside your object, and the raycast back at the origin. Note you can use Collider.Raycast() so that you Raycast() will only hit the specified collider. Let's say your raycast starts at the transform.position of your character and goes in the direction 'dir'.
Vector3 pos = transform.position + dir * 10.0f; // Point beyond capsule
Ray ray = new Ray(pos, -dir);
RaycastHit hit;
collider.Raycast(ray, out hit, 10.0f);
Typically the retun value of the Raycast() is checked to make sure it hit something, but in this case I don't see a way for the Raycast to miss. The point on the surface of the collider will be hit.point.
Thanks for the answer!
$$anonymous$$y response- yes, it works.
Because I can't think "outside the capsule," though, I invested some time in getting a different solution. I'll just post my now-old code in the event that anyone in the future
public void Advanced$$anonymous$$ove(Vector3 directionWithSpeed)
{
if (can$$anonymous$$oveX(directionWithSpeed) && can$$anonymous$$oveY(directionWithSpeed) && can$$anonymous$$oveZ(directionWithSpeed))
{
_transform.Translate(directionWithSpeed);
}
}
Basically I break down each Vector3 field and check it against a raycast. If you can go in the X, Y, and Z directions it returns true and... you actually move in those directions.
Thanks again!
Your answer
Follow this Question
Related Questions
Surface with hole and Raycast - Which collider 1 Answer
Particular collider not working properly... 1 Answer
AI Players Movement for Rolling Ball Game 0 Answers
Trouble with Physics.IgnoreCollision 0 Answers
Smooth Movement on Geometry Collission? 0 Answers