Question by
JimRan · Oct 21, 2018 at 12:32 AM ·
c#movementcharactercontroller
How can I adapt this character controller movement script to allow movement in mid air?
I'm struggling to figure this one out. I'm trying to use the example code on the CharacterController.Move API page as a movement system for my player. I only have one issue with it, where the move direction updating is behind the .isGrounded() check, meaning if you are in the air you cannot move your character.
I was trying to move the two lines associated with moveDirection outside of the if statement, however then jumping does not work properly anymore.
If someone could help me find a (relatively) simple modification to this code to allow the player to be able to strafe in air, that'd be great.
Thanks.
The code in question, incase unable to visit the API page:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
CharacterController characterController;
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
if (characterController.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection *= speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
}
}
Comment