Hey guys,
I ran into a problem today when checking if a ray hits a collider. I’m using this check to find out if my character is grounded. This is the code I use
void OnCollisionStay () {
float dist = 1f;
Vector3 dir = new Vector3(0,-1,0);
float offset1 = -0.2f;
float offset2 = 0.3f;
Debug.DrawRay(transform.position + transform.right * offset1, dir*dist, Color.red);
Debug.DrawRay(transform.position + transform.right * offset2, dir*dist, Color.red);
if(Physics.Raycast(transform.position + transform.right * offset1,dir,dist) || Physics.Raycast(transform.position + transform.right * offset2,dir,dist)){
grounded = true;
canJump = true;
Debug.Log("grounded");
}
}
As you can see, I’m using two rays. That’s because I need that kind of precision (pixel perfect movement for platformer). And here’s the problem. It works fine, when one ray hits a collider and the other one is close to the collider. But it doesn’t work if one of them get’s too far away from the collider. I’ve attached an image to show both cases (top: works, bottom: no ray hit)
http://www.imagesload.net/img/rays.jpg
Any ideas what could cause this problem?
This is an example of how I use RaycastHit on a collider.
else if (Input.GetMouseButtonDown(0)){
theTouch =Input.mousePosition;
ray = Camera.main.ScreenPointToRay(theTouch);
if (Physics.Raycast(ray, hit)){
if (hit.collider == godCollider){////"godCollider" is a box collder which encompasses screen. It is required as I have pause and wpn btns too.
pressingDown = true;
determineInputMethod();
return;
}
@renman3000
This approach doesn’t work for me. I have a lot of different colliders in my scene and checking them all in the if statement would be wrong.
Not using the hit variable in the method’s signature should do exactly that. Checking for all collisions except with the one which belongs to the player object.
Well I am really unsure of what you are trying to do. Seems interesting. Are you simply casting a ray to check one position or the other?
I use the rays to check if my character is standing on the ground. Each ray is just inside the charater’s collision box. So if OnCollisionStay is true and one of the rays hits the collider of an object my character is grounded and jumping is possible.
I’m using rays for it because I only what to enable jumping when there’s a collider below my character. Otherwise he could also jump when he touches a vertical plane like for example a wall. This would result in wall-jump-glitching in mid air.
EDIT: fixed it.
The ray started below the character’s collider so it started inside the collider of an object when the character was standing on top of it.
Still running into another problem.
I start the ray like this and move it to the right (offset)
Physics.Raycast(transform.position + transform.right * offset1,dir,dist)
But I also want to move the starting point up. How would I do that?
Why not just adjust the vector? Right now you go 1,0,0, why not 1,1,0?