- Home /
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!
Answer by Chaos119 · Nov 30, 2013 at 03:43 PM
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 :)
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
Your answer
Follow this Question
Related Questions
issues with jumping and linecast2d and raycast2d 0 Answers
Raycast Physics2D not working as expected 1 Answer
Linecast, rotate end point relative to objects rotation 1 Answer
Getting a Raycast rope to follow its object 0 Answers
onGround raycasts return onGround is true while colliding with platform sides 0 Answers