Physics2D Raycast not working?
I'm not sure why the following code isn't working... I set the jumpForce to 2 units, and the groundCheckLength to 0.03f. My objects are very tiny, 0.08x0.08 unity units, because I'm using pixel art that hasn't been scaled. I suspect the small sizes could be causing me trouble, or maybe I'm misusing the raycast function?
void Update () {
if (Input.GetKeyDown(KeyCode.W) && Grounded())
{
Jump();
}
}
private bool Grounded ()
{
return Physics2D.Raycast(tf.position, Vector2.down, groundCheckLength, LayerMask.NameToLayer("Ground"));
}
private void Jump ()
{
rb.velocity = new Vector3(0, jumpForce, 0);
}
Hi @jsm209
Your Grounded method returns Physics2D.Raycast result. If you check the documentation, it says it's a static method, that returns a RaycastHit2D object. So your Grounded returns a true for RaycastHit2D object existing, not if RaycastHit2D contains a hit to your floor.
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html https://docs.unity3d.com/ScriptReference/RaycastHit2D.html https://docs.unity3d.com/ScriptReference/RaycastHit2D-point.html
You should check for hit.collider != null ins$$anonymous$$d. I think this question has been asked earlier.
Did little bit of googling: here's one older thread discussing the same issue: https://answers.unity.com/questions/1019309/raycast2d-only-returns-true.html
Your answer
Follow this Question
Related Questions
Pre-solve Collision 0 Answers
RaycastHit2D ground detection 1 Answer
Platforming character is jumping higher while walking 0 Answers
Always Grounded When Jumping 2 Answers
Had to turn off gravity scale, but now player goes through walls 0 Answers