0

Hello I was trying to do movement script in Unity. Also I wanted to add jump, but everytime when I jump it moves up for like 0.025 on Y direction and stops the player in air*(if I am on 0 and I jump it moves on 0.02545 then 0.0543 etc...)* and I can spam Space to move player up. I added gravity but it looks it doesn't work.. I don't know how to fix it. I hope someone can help me with my problem...

Here is the function what I am using...

Vector3 moveDirection = Vector3.zero; public float walkingSpeed = 10.0f; public bool canJump = true; public float jumpSpeed = 8.0f; public float gravity = 10.0f; CharacterController characterController; void Movement() { Vector3 forward = transform.TransformDirection(Vector3.forward); Vector3 right = transform.TransformDirection(Vector3.right); float moveX = walkingSpeed * Input.GetAxis("Vertical"); float moveY = walkingSpeed * Input.GetAxis("Horizontal"); float MovementY = moveDirection.y; moveDirection = (forward * moveX) + (right * moveY); if (Input.GetButtonDown("Jump") && canJump) { moveDirection.y = jumpSpeed; } moveDirection.y -= gravity * Time.deltaTime; characterController.Move(moveDirection * Time.deltaTime); } 

1 Answer 1

1

Because you are resetting moveDirection every frame (when you call moveDirection = (forward * moveX) + (right * moveY) you aren't letting the gravity accumulate. You should instead save the vertical speed separately and add it every frame.

Something like the following:

Vector3 moveDirection = Vector3.zero; public float walkingSpeed = 10.0f; public bool canJump = true; public float jumpSpeed = 8.0f; public float gravity = 10.0f; CharacterController characterController; private float verticalSpeed; void Movement() { float moveX = walkingSpeed * Input.GetAxis("Vertical"); float moveY = walkingSpeed * Input.GetAxis("Horizontal"); verticalSpeed -= gravity * Time.deltaTime; if (Input.GetButtonDown("Jump") && canJump) { verticalSpeed = jumpSpeed; } characterController.Move((moveX * transform.forward + moveY * transform.right + verticalSpeed * transform.up) * Time.deltaTime); } 

transform.forward is equivalent to transform.TransformDirection(Vector3.forward)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.