- Home /
My Player can't jump - coding
Hey There,
So my code works fine for the movement and the gravity, but when I added the jump code line, when I press it in game it comes up with the error the transform.positionWithLocalOffset is not valid
Here is the coding I'm using, does anyone have any idea how to fix this?
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float gravity = 9f;
public float jumpHeight = 3f;
Vector3 velocity;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
float directionY;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;
// Update is called once per frame
void Update()
{
//movement
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("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);
}
//Jump
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
//gravity
velocity.y -= gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
//ground check
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
}
}
Any help would be greatly appreciated,
Thanks in advance.
Answer by myzzie · Nov 17, 2020 at 01:10 PM
At line 47, you're trying to get the square root of a negative value. Negative squares aren't real numbers. Make sure you take the sqrt of 0 or higher values.
Ofcourse, such a simple thing aha.
Thank you, truly.
You've saved me a lot of time and a headache!
Your answer
Follow this Question
Related Questions
[C#] Jump on slopes 1 Answer
Jump with Character Controller 1 Answer
Jump and move (CharacterController.velocity) C# 0 Answers
Making a bubble level (not a game but work tool) 1 Answer
Why won't my character jump,How do I make my character jump? 2 Answers