Reputation: 43
I'm new in Unity3D and I have a problem with collision detection. I want to return true if i hit the obstacle by raycast and block movement in this direction. It works good when im in front of the obstacle face to face. When i'm changing direction and i'm in front of the obstacle (but with another face direction) then it returns false and i can still move in all directions (it should block "up" movement like you see on first image). Any tips would be greatly appreciated!
Returns true when obstacle is in front of us and we can't move "up"
Returns false when obstacle is in on our left or right
Player is blocked after wrong move
Here is sample of my code:
void Update()
{
Ray myRay = new Ray(transform.position, Vector3.right);
Debug.DrawRay(transform.position, Vector3.right, Color.red);
if (Physics.Raycast(myRay, out hit, 1.5f))
{
if (hit.collider.gameObject.tag == "TerrainObject")
{
Debug.DrawRay(transform.position, Vector3.right, Color.blue);
upHit = true;
}
}
else
upHit = false;
...
}
Upvotes: 4
Views: 1136
Reputation: 20259
As discussed in the comments, you need to increase the starting height of the raycast.
Use Ray myRay = new Ray(transform.position+new Vector3(0f,0.15f,0f), Vector3.right);
to raycast from above the ground a little bit.
Upvotes: 2