I can't get RayCast to report the collider I want.

Hi,

I am making a game, where I want to check right before the ball collides with the last object in the level.

Here is the code I have so far:

void Update()
        {    
			if (GameManager.instance.GetCurrentLevelRLNumb() % 5 == 0 && isLastObstacle  && shouldSlowDown)
			{
				Obstacle obs = GameManager.instance.LastObstacle ;
				
				string name = obs ._gameObject.name;
				Vector2 obs Pos = obs ._transform.position;

				Debug.Log("<color=yellow>Name is: </color>" + name + "<color=green>position is: </color>" + obsPos.ToString());

				Vector2 ballPos = ball.transform.position;
				Vector2 direction = (obsPos - ballPos);//.normalized;

				RaycastHit2D hit = Physics2D.Raycast(ballPos, direction);
				Debug.DrawRay(ballPos, direction, Color.green);

				if(hit.transform != null && !hit.transform.name.Equals("Ball"))
				{
					Debug.Log(hit.transform.name);
				}
				
			}
        }

The thing is, when I debug log the Name and Position of the last Obstacle, it really is the last in game.

I even took screenshot, with the Debug.DrawRay showed in scene view, how it collides with the last obstacle:

81535-scshot.png

Things I want to note:

The lastObstacle is trigger, but I double checked if ‘Queries hit triggers’ is checked, both in Physics and Physics2D.

I also checked that Z position is same for ball and obstacle.

I am very grateful for any direction you give me,

Ok I solved it without raycast.

I used Vector3.Distance to see if the ball is close enough to the obstacle.

Far simplier and easier to change later :slight_smile: