- Home /
How to move while jumping?
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
I'm using this script to move and jump around. When I jump it doesn't allow me to move a different direction mid-jump. How would I accomplish this?
Comment
Answer by Dragate · Nov 02, 2017 at 07:05 AM
You basically need to move your xz calculations out of the isGounded restriction.
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
Vector3 moveDirection = Vector3.zero;
CharacterController controller;
void Awake(){
controller = GetComponent<CharacterController>();
}
void Update(){
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (controller.isGrounded && Input.GetButton("Jump")){
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
Your answer
Follow this Question
Related Questions
Can't get gravity to work on Character Controller 2 Answers
Can't fix slow jumping for character controller 3D 1 Answer
How do I make a jumping and ledge-grabbing system, similar to TLoZ OOT in unity 3d? 0 Answers
Lunging with Character Controller 0 Answers
Player Control. Roller Ball with Cube Acceleration. 1 Answer