Huy guise, I’m in the process of teaching myself Unity (2D), and I have a bit of a problem…
I only have two script files, all attached to the player gameobject sprite thing. One of them is a left and right movement script, and the other one allows jumping. The jump script is the problematic one:
public class Jump : MonoBehaviour
{
public bool YN = false;
public float jmppwr = 10f;
void Update()
{
RaycastHit2D ground = Physics2D.Raycast(transform.position, -Vector2.up, 1);
if (ground != null)
{
YN = true;
}
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Space) && YN)
{
rigidbody2D.AddForce(new Vector2(0f, jmppwr));
YN = false;
}
}
}
The issue is that bool YN is always true (even when there’s no ground collision object underneath), hence allowing the player to jump mid-air and stuff.
Anyone know what the problem is?
One problem is that you never set ground to false. Once YN is set to true, it stays true even if the ground is no longer there. It only get set to false after a jump is started. A quick fix using your current structure would be:
if (ground != null)
{
YN = true;
}
else {
YN = false;
}
But that is equivalent to:
YN = (ground != null);
Well, it appears that Physics2D.Raycast() does not work the way they indicate in the reference or there is something else going on that I don't understand. I ran a test with your code, and I got the same behavior that you did. I can give you a work around: if (ground == null || ground.collider == null) YN = false; else YN = true; You may be able to just do: YN = ground.collider != null; But I'm reluctant to go with this since a null 'ground' would produce an access violation.
Well, it appears that Physics2D.Raycast() does not work the way they indicate in the reference or there is something else going on that I don't understand. I ran a test with your code, and I got the same behavior that you did. I can give you a work around: if (ground == null || ground.collider == null) YN = false; else YN = true; You may be able to just do: YN = ground.collider != null; But I'm reluctant to go with this since a null 'ground' would produce an access violation.
– robertbu