4
votes

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;
    ...
}
1
Can you confirm that the transform.position is the same between your two examples?Ruzihm
Yes, its the same. On 2nd example i just moved player first left and then right to go back (i always change rotation when the player is changing movement direction. For better example check movement in the game „Crossy road”).Gleuq
In the 2nd part, can you confirm if the ray does hit something with a tag that isn't TerrainObject?Ruzihm
I'm wondering if it's a really strange rounding error and it's too low to collide with the TerrainObject. Try Ray myRay = new Ray(transform.position+new Vector3(0f,0.02f,0f), Vector3.right); to raycast from above the ground a little bit.Ruzihm
Wow thanks, thats solved my problem! i forgot that my TerrainObjects are +0.15f on y-axis! Thank You very much! :)Gleuq

1 Answers

2
votes

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.