Player controller jump not working correctly
Ok, so the jump was working perfectly, until I got a little more fancy with the functionality.
if (GroundCheck ())
{
velocity.y = 0;
gravity = Physics2D.gravity.y;
if (Input.GetKeyDown (KeyCode.Space))
{
gravity = 0;
velocity.y = jumpForce;
}
}
else
{
gravity += Physics2D.gravity.y * Time.deltaTime;
velocity.y += gravity;
}
After adding lines 3 and 4. it hammers the player back down fast whenever the I hit space and it jumps.
I looked into the problem and it seems that the code inside if GroundCheck is running one frame after the jump.
GroundCheck:
bool GroundCheck () {
for (int r = 0; r < rayCountY; r ++)
{
Vector3 rayPos = new Vector2 (raycastOrigins.left + raycastOrigins.raySpacingY * r, raycastOrigins.bottom);
RaycastHit2D hit = Physics2D.Raycast (rayPos, Vector3.down, skinWidth, collisionMask);
if (hit)
{
return true;
}
}
return false;
}
Basically all the ray origins are (eg left, right) are floats that determine the x position or y position of the bounds min or max of said axis, but within a skin width.
Unfortunately, I planned to get the rest of the code up on the question just in case, but we were in a rush to leave for somewhere in the day and I didn't get a chance. Hopefully the code here is enough.
Edit
I thought when I came back I would be able to fix this issue with the solution I thought I had, but it didnt fix it. New code is below:
if (GroundCheck ())
{
velocity.y = gravity;
if (Input.GetKeyDown (KeyCode.Space))
{
velocity.y = jumpForce;
}
}
else
{
velocity.y += gravity * Time.deltaTime;
}
I really need this to be fixed :( Its like the raycast in ground check is catching the player the frame after the jump and pulling him back down. I have had this problem before but i forget how i dealt with it.
Your answer
Follow this Question
Related Questions
How to jump while gravity is reversed 2 Answers
Rigidbody - How to make it jump and fall down fast ? Help needed. 1 Answer
Problem between Colliders. One is passing through the other. What to do? 0 Answers
Unity 5 Player Control Movement, camera (3rd prs following) jump + gravity 0 Answers
Character not jumping smoothly using CharacterController 0 Answers