4

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;
    ...
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
Gleuq
  • 43
  • 3
  • Can you confirm that the `transform.position` is the same between your two examples? – Ruzihm Nov 28 '18 at 22:01
  • 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 Nov 28 '18 at 22:14
  • In the 2nd part, can you confirm if the ray *does* hit something with a tag that *isn't* `TerrainObject`? – Ruzihm Nov 28 '18 at 22:18
  • At the moment ray only hit TerrainObject. I noticed that when player is the same rotation like on 2nd example and im changing rotation by 180 degree - for a moment ray hits TerrainObject. I dont understand Why Vektor3.right detects obstacle only when the player is in front of it. It should hit independently of rotation? – Gleuq Nov 28 '18 at 22:30
  • 1
    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 Nov 28 '18 at 22:41
  • 1
    Wow thanks, thats solved my problem! i forgot that my TerrainObjects are +0.15f on y-axis! Thank You very much! :) – Gleuq Nov 29 '18 at 00:04

1 Answers1

2

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.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48