- Home /
Can't jump in C#
Hello, I have a problem with my character movement script in C#. I can walk, run, the gravity works great, but I can't jump. Here is the code :`using UnityEngine; using System.Collections;
[RequireComponent(typeof(CharacterController))]
[System.Serializable] public class Move { public bool enabled = true; public float walkSpeed = 5.0f; public float runSpeed = 10.0f; public KeyCode runKey = KeyCode.LeftShift; }
[System.Serializable] public class Jump { public bool enabled = true; public float height = 5.0f; public KeyCode jumpKey = KeyCode.Space; }
[System.Serializable] public class Gravity { public bool enabled = true; public float gravityForce = 5.0f; }
public class Controller : MonoBehaviour { public CharacterController characterController;
private float horizontalAxis;
private float verticalAxis;
public Move move;
public Jump jump;
public Gravity gravity;
void Update()
{
horizontalAxis = Input.GetAxis("Horizontal");
verticalAxis = Input.GetAxis("Vertical");
if(characterController.isGrounded)
{
Move(move.enabled, move.walkSpeed, move.runSpeed, move.runKey);
Jump(jump.enabled, jump.height, jump.jumpKey);
}
Gravity(gravity.enabled, gravity.gravityForce);
}
public void Move(bool enabled, float walkSpeed, float runSpeed, KeyCode runKey)
{
Vector3 moveDirection = new Vector3();
float speed = 0;
if(enabled == true)
{
moveDirection = new Vector3(horizontalAxis, 0, verticalAxis);
if(Input.GetKey(runKey))
{
speed = runSpeed;
}
if(!Input.GetKey(runKey))
{
speed = walkSpeed;
}
moveDirection *= speed;
moveDirection = transform.TransformDirection(moveDirection);
characterController.Move(moveDirection * Time.deltaTime);
}
}
public void Jump(bool enabled, float jumpHeight, KeyCode jumpKey)
{
Vector3 moveDirection = new Vector3();
if (enabled == true)
{
if(Input.GetKey(jumpKey))
{
moveDirection.y = jumpHeight;
}
characterController.Move(moveDirection * Time.deltaTime);
}
}
public void Gravity(bool enabled, float gravityForce)
{
Vector3 moveDirection = new Vector3();
if(enabled == true)
{
moveDirection.y -= gravityForce;
characterController.Move(moveDirection * Time.deltaTime);
}
}
}`
Answer by thadstedman · Nov 23, 2020 at 03:06 PM
Try this video and you don't need any of the player base stuff or the animation stuff that's only for animations And at the top you don't need the using code monkey.Utill or Using V_animation system You only need to watch like the first four minutes or so as well. Here's the link:https: //www.youtube.com/watch?v=ptvK4Fp5vRY&feature=emb_logo
Well on YouTube you can look up code monkey jumping tutorial Unity and that Should be it