4.3 2D Line/Ray Cast Hit Layermasks not working

I am attempting to make a custom 2D CharacterController in Unity 4.3 and I am trying to make an IsGrounded function but it’s registering raycasts and linecasts on only the player. Here is my code, simple enough.

using UnityEngine;
using System.Collections;

[RequireComponent (typeof(Rigidbody2D))]

public class CharacterMovement : MonoBehaviour {

	public LayerMask ground;
	
	float PlayerHeight;
	
	void Start () {		
		PlayerHeight = GetComponent<BoxCollider2D>().size.y;	
	}

	// Use this for initialization
	void Update () {

		print (IsGrounded());

	}

	public bool IsGrounded () {
		bool hit = Physics2D.Linecast(Flatten(transform.position), new Vector2(transform.position.x,transform.position.y - (PlayerHeight * -.5f)), 1 << ground.value);
		return hit;
	}

}

As a note, I am using 2DToolkit for my spritework and I removed any code (potentially) irrelevant to the problem.

Have you by chance figured this out? I'm facing the same problem right now. Thanks!

1 Answer

1

I downloaded the demo that unity used to show their new 2D support features to find this issue myself. Here is what I found and it works fine :slight_smile:

private Transform groundCheck;	// A position marking where to check if the player is grounded.
private bool grounded = false; //Whether or not the player is grounded.

void Update()
	{
	// The player is grounded if a linecast to the groundcheck position hits anything on the ground layer.
	grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

}

All you need to do is assign create a Empty GameObject, name it groundcheck(or whatever you see fit). Then make it a child of the player object and place it below the player.

Thank you, It worked for me... I was getting insane x_x

what if its a cube? How will I check all its sides? (IN 2D)