Advertisement
AnomalousUnderdog

Unity: CharacterController mid-air movement

Apr 22nd, 2012
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.93 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Mover : MonoBehaviour
  5. {
  6.     public float speed = 6.0F;
  7.     public float jumpSpeed = 8.0F;
  8.     public float gravity = 20.0F;
  9.     private Vector3 moveDirection = Vector3.zero;
  10.     private CharacterController controller;
  11.  
  12.     void Start()
  13.     {
  14.         controller = GetComponent<CharacterController>();
  15.     }
  16.  
  17.     void Update()
  18.     {
  19.         moveDirection = new Vector3(Input.GetAxis("Horizontal"), moveDirection.y, Input.GetAxis("Vertical")); // make sure the old value of moveDirection.y won't get lost
  20.         moveDirection = transform.TransformDirection(moveDirection);
  21.        
  22.         // don't apply speed to moveDirection.y. apply it only to x and z
  23.         moveDirection.x *= speed;
  24.         moveDirection.z *= speed;
  25.        
  26.         if (controller.isGrounded && Input.GetButton("Jump"))
  27.         {
  28.             moveDirection.y = jumpSpeed;
  29.         }
  30.        
  31.         moveDirection.y -= gravity * Time.deltaTime;
  32.         controller.Move(moveDirection * Time.deltaTime);
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement