Raycast collisions being detected along a non-existent curve(?)
I have written a brief amount of code for debugging purposes to show visually when the player is on solid ground or not. The code can be seen here:
private void UpdateCastValues()
{
//Casting
Ray2DBegin = ((Vector2)transform.position);
Ray2DEnd = ((Vector2)this.gameObject.transform.position + (Vector2.down * 0.75f));
}
private bool IsPlayerGrounded()
{
try
{
if (CheckHit().collider.tag == "ground")
return true;
else
return false;
}
catch
{
return false;
}
}
private RaycastHit2D CheckHit()
{
hit = Physics2D.Raycast(Ray2DBegin, Ray2DEnd);
return hit;
}
private void OnDrawGizmos()
{
if (IsPlayerGrounded())
Gizmos.color = Color.green;
else
Gizmos.color = Color.red;
Gizmos.DrawLine(Ray2DBegin, Ray2DEnd);
}
Here we can see the player, which has a square collision box. Below the player is a Tilemap with a TilemapCollider2D component.
As you can see in the above image, when the player moves to the left, the gizmo turns red, indicating that there is no "ground" collision below the player, however, the player remains moving horizontally across the ground, as the relationship between the player's collision detection and the ground registers as a perfectly straight line.
The reason for this is because the collision for the Tilemap below is registering along a curve. I will show this in the picture below.
If you will excuse the shoddy drawing, by moving the player around and checking when the gizmo goes from red to green, I have identified a curvature being detected basically where I have drawn. It it goes from below, to higher up, and then below the tilemap.
This makes no sense to me. This is a first game for me so any help is appreciated.
Answer by xxmariofer · Mar 07, 2019 at 09:11 AM
hello your problem is understanding the raycast. the ray2d end is the direction, not a position where the raycast ends, so you dont need to multiply * 0.75 (since is just a direction not a length) and dont have to add the player position. override the raycast line with this
hit = Physics2D.Raycast(Ray2DBegin, Vector2.down, 0.75f);//you need to pass the lenbgth of the ray as argument
also good job explaining your issue and giving all the debug information, and the code structure, was easy to understand :)