It's quite possible I'm missing something obvious (I'm still rather new to this) despite checking the documentation, but I'm at my wit's end with this issue.
I'm attempting to add simple linecast collisions to my 2D movement system that checks if there's a wall on the relevant layer to disallow movement, but I cannot get the distance parameter to function properly. It's responding as if my distance is set to the default MathF.Infinity, despite me feeding a float variable into it.
Furthermore, unity keeps giving me this error after I moved my layermask declaration into the Start function: "The name 'mask' does not exist in the current context." I'm unsure why this is happening.
Here's the relevant code:
float distance = 1f;
void Start()
{
LayerMask mask = LayerMask.GetMask("BlockingLayer");
}
void FixedUpdate()
{
// Move up IF !isMoving and No collision detected.
if (Input.GetKey(KeyCode.W) && !isMoving && Physics2D.Linecast(transform.position, Vector2.up, mask, distance))
StartCoroutine(MovePlayer(Vector2.up));
}
Alright, after working with the helpful people responding, I've updated my code. Unfortunately, my issue seems to have inverted. Rather than detecting collision always, collision does not seem to be detected ever. Here's the new code (Edited to reflect small change):
float maxDistance = 2f;
RaycastHit2D hitU;
void FixedUpdate()
{
hitU = Physics2D.Raycast(transform.position, Vector2.up, LayerMask.GetMask("BlockingLayer"));
// Move up IF !isMoving and No collision detected.
if ((hitU.collider != null && (hitU.distance < maxDistance)))
{
if (Input.GetKey(KeyCode.W) && !isMoving)
{
StartCoroutine(MovePlayer(Vector2.up));
Debug.DrawRay(transform.position, Vector2.up, Color.red);
}
}