Question by
NonSmallJohn · Feb 10 at 02:38 AM ·
c#jumpinggrounded
Player no longer jumping
Hi,
I'm working on my first project and I set up a Third Person Movement script which was working very well, but I seemed to have broken something.
I can no longer Jump even though the debug log shows that I'm grounded and jump is pressed down. The character controller does show a velocity change in the Y direction, but the character is stuck to the ground. The Y position moves in the up position by a barely noticeable amount, as if the character is stuck.
I can only get it to work if I set isGrounded to NOTisGrounded:
If I set "if (Input.GetButtonDown("Jump") && !isGrounded)", it works. However once the groundDistance is reached the velocity changes to my default -2.
Hope someone can help, this is driving me nuts! Cheers
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 2f;
public float turnSmoothTime = 0.1f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
float turnSmoothVelocity;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded)
{
Debug.Log("Is Grounded");
}
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
if (Input.GetButtonDown("Jump") && isGrounded)
{
Debug.Log("Is Jumping");
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Comment