- Home /
I guess the reason this code doesn't work is simply because there is no 2D raycast that returns a bool. So it would have to be re structured completely
Why won't this jump code work?
I've been following this tutorial on making a character controller and I'm trying to get the player to jump but only when it's grounded. Here is the code.
public class WalkingController : Controller
{
//Movement information
Vector3 walkVelocity;
Vector3 previousWalkVeloctiy;
float adjVertVelocity;
float jumpPressTime;
//Setting
public float walkSpeed;
public float jumpSpeed;
public override void ReadInput(InputData data)
{
previousWalkVeloctiy = walkVelocity;
ResetValues();
//set horizontal movement.
if(data.axes[0] != 0f)
{
walkVelocity += Vector3.right * data.axes[0] * walkSpeed;
}
//set jump movement.
if (data.buttons[0] == true)
{
if (jumpPressTime == 0f)
{
if (Grounded())
{
adjVertVelocity = jumpSpeed;
}
}
jumpPressTime += Time.deltaTime;
}
else
{
jumpPressTime = 0f;
}
newInput = true;
}
//method that looks below the player to see if something is there.
bool Grounded()
{
return Physics.Raycast(transform.position, Vector3.down, coll.bounds.extents.y + 0.1f);
}
void ResetValues()
{
walkVelocity = Vector3.zero;
adjVertVelocity = 0f;
}
void LateUpdate()
{
if (!newInput)
{
previousWalkVeloctiy = walkVelocity;
ResetValues();
jumpPressTime = 0f;
}
/*
* FYI:
* Here we set the Vectors to the velocity of the rigidbody. Setting the Y value of
* the new Vector2 Means that the player will fall down normally. If set to 0 it would
* either keep the player from falling or make them fall very slowly.
*/
rb.velocity = new Vector3(walkVelocity.x, rb.velocity.y + adjVertVelocity);
newInput = false;
}
}
The tutorial is more designed for a 3d game, and I put this character controller on a cube just to see what would happen and it worked fine. I'm not sure why it wouldn't work on a 2D sprite as well. I even tried changing the raycast to be a 2D raycast, but that didn't work to well because Raycast2D isn't a bool like Physics.Raycast is. Any explaination would be greatly appreciated! :D
Answer by Rickasheye · Jan 11, 2018 at 02:40 AM
You put the jumpPressTime += Time.deltaTime;
if(Grounded()){ jumpPressTime += Time.deltaTime; adjVertVelocity = jumpSpeed; }
i think
or the adjVertVelocity = jumpSpeed; the jump $$anonymous$$ethod idk if so take the = from it and make it += idk
So I tried this out and the Grounded method isn't even being reached. I have no Idea why it wouldn't be.
you have the jump button then the grounded method inside maybe if you put that outside and put the jump button on the inside you might be alright e.g.
if(Grounded == true){
if(input.getkey(keycode.e){
//jump thing
}
}
Why do you have Grounded as true why not .isGrounded?
I just tried switching them around and that didn't work. I'm pretty sure the issue is with the Physics.raycast in the grounded method. It should be returning true so that the if statement works.