Reputation: 9
I'm new to unity and trying to make a character that can move, jump, etc. However, the jump isn't quite working correctly. The height of the jump seems to change every time, as well as the character falling very slowly after jumping. I can't figure out why it is doing this. My code is as shown below:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerMovement : MonoBehaviour
{
private CharacterController characterController;
[SerializeField]
float movementSpeed = 5.0f;
[SerializeField]
float jumpHeight = 10.0f;
float gravity = -9.81f;
Vector3 relativeMovementInput;
Vector3 relativeMovement;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
handleRotation();
handleMovementInput();
handleGravity();
handleJump();
characterController.Move(relativeMovement * Time.deltaTime);
}
void handleGravity()
{
if (characterController.isGrounded && relativeMovementInput.y < 0)
{
relativeMovement.y = -0.01f;
}
relativeMovement.y += gravity * Time.deltaTime;
}
void handleMovementInput()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 relativeVerticalInput = transform.forward * verticalInput;
Vector3 relativeHoriztonalInput = transform.right * horizontalInput;
relativeMovementInput = relativeHoriztonalInput + relativeVerticalInput;
relativeMovement.x = relativeMovementInput.x * movementSpeed;
relativeMovement.z = relativeMovementInput.z * movementSpeed;
}
void handleJump()
{
bool isJumpPressed = Input.GetButton("Jump");
bool canJump = characterController.isGrounded;
if (isJumpPressed && canJump)
{
relativeMovement.y += jumpHeight;
}
}
void handleRotation()
{
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X"));
}
}`
Upvotes: 0
Views: 152
Reputation: 735
It could be better if you use a Rigidbody2D
component instead of trying to simulate gravity and other physic stuff.
Here is an example:
public float jumpForce = 10.0f;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
handleJump();
}
void handleJump()
{
if (Input.GetButtonDown("Jump") && characterController.isGrounded)
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
NOTE: Remember to add a Rigidbody2D
component at the same object where this script is attached to it. Also don't use the handleGravity() method if you are approaching this solution.
Upvotes: 0
Reputation: 46
I recomend you to add a rigid body component to your player, it will do all the gravity part. Then you only have to use addforce to make the player jump
Upvotes: 1