- Home /
Check if the player is on the ground. Unity4.3 (2D)
I'm checking the new 2D features in Unity 4.3 edition. So they changed some components to work now with 2D environment. I'm using Physics2D.Linecast
to check if player is on the ground. But everywhere my char stay on ground, even if it's jumping. My ground is marked as ground to get correct layer to compare char vector with the ground's one.
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
"grounded" is a bool to check if player is on the ground;
"transform" refers player's transform;
"groundCheck" is an emptyObject put into player to mark ground directions.
Since I'm using the new resources, probably raycast or "old" components to handle 3D environments can't help me there.
Thanks in advance and sorry about my english.
Here is an article I found which explains how to use Physics.OverlapCircle to check if object is grounded. $$anonymous$$aybe it might help someone who is struggling to get this
Answer by diegzumillo · Nov 28, 2013 at 04:37 AM
You need to use Vector2 as arguments for the Physics2D.Linecast. I made the same mistake when migrating to 2D physics :P Something like
var MyPos : Vector2 = Vector2(transform.position.x, transform.position.y);
var GroundCheckPos : Vector2 = Vector2(groundCheck.position.x, groundCheck.position.y);
Physics2D.Linecast(MyPos , GroundCheckPos , 1 << LayerMask.NameToLayer("Ground"));
Thanks so much, diegzumillo. I've changed the code and worked now.
Vector2 playerPos = new Vector2(transform.position.x, transform.position.y);
Vector2 groundPos = new Vector2(groundCheck.position.x, groundCheck.position.y);
grounded = Physics2D.Linecast(playerPos, groundPos, 1 << Layer$$anonymous$$ask.NameToLayer("Ground"));
I've copied the base code from an official example of 2D Platform game and the weird behavior is there the game works as well, I needed to change based from your snippet code to make $$anonymous$$e running. Thanks
Excuse me, but what is the use of 1 << in 1 << Layer$$anonymous$$ask.NameToLayer("Ground")
? Any explanation would be appreciated.
the << is a bit shifting operator. The layer$$anonymous$$ask is just an integer, but the way the different layers are handled are in binary. So the layermask might look like 1010110 but the integer it's stored as will be "86"
Hi $$anonymous$$ernelSys, read the manual on layers to learn about combining layers, here's the link: http://docs.unity3d.com/Documentation/Components/Layers.html
Your answer
Follow this Question
Related Questions
Setting Velocity of Rigidbody to Mouse Speed 1 Answer
Simple Topdown Movement Problem 1 Answer
My game frozzes when I use a while to check if there's colision 2 Answers
How to create a ground/terrain/floor that won't respond to gravity or objects falling on it? 1 Answer
Problem with rotated colliders 0 Answers