Advertisement
Guest User

CharacterMotor

a guest
Feb 16th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. [System.Serializable]
  6. public class CharacterMotor : MonoBehaviour
  7. {
  8.     public struct State
  9.     {
  10.         public Vector3 position;
  11.         public Vector3 localPosition;
  12.         public Vector3 velocity;
  13.         public bool isGrounded;
  14.     }
  15.  
  16.     CharacterController characterController;
  17.  
  18.     [Header("Movement")]
  19.     [SerializeField]
  20.     private float runSpeed;
  21.  
  22.     State _state;
  23.  
  24.     [SerializeField]
  25.     LayerMask layerMask;
  26.  
  27.     Vector3 sphere
  28.     {
  29.         get
  30.         {
  31.             Vector3 p;
  32.  
  33.             p = transform.position;
  34.             p.y += characterController.radius;
  35.             p.y -= (0.08f * 2);
  36.  
  37.             return p;
  38.         }
  39.     }
  40.  
  41.     private void Awake()
  42.     {
  43.         characterController = GetComponent<CharacterController>();
  44.  
  45.         _state = new State();
  46.         _state.position = transform.localPosition;
  47.     }  
  48.  
  49.     public void SetState(Vector3 position, Vector3 localPosition, Vector3 velocity, bool isGrounded)
  50.     {
  51.         _state.localPosition = localPosition;
  52.         _state.position = position;
  53.         _state.velocity = velocity;
  54.         _state.isGrounded = isGrounded;
  55.  
  56.         transform.position = _state.position;
  57.     }
  58.  
  59.     private void Move(Vector3 velocity)
  60.     {
  61.         bool isGrounded = false;
  62.  
  63.         isGrounded = isGrounded || characterController.Move(velocity * BoltNetwork.FrameDeltaTime) == CollisionFlags.Below;
  64.         isGrounded = isGrounded || characterController.isGrounded;
  65.         isGrounded = isGrounded || Physics.CheckSphere(sphere, characterController.radius, layerMask);
  66.  
  67.         _state.isGrounded = isGrounded;
  68.         _state.position = transform.localPosition;
  69.     }
  70.  
  71.     public State Move(float horizontal, float vertical)
  72.     {
  73.         Vector3 moveDir = new Vector3(horizontal, 0, vertical) * runSpeed;
  74.  
  75.         if(_state.isGrounded)
  76.         {
  77.             Move(moveDir);
  78.         }
  79.        
  80.         Move(_state.velocity);
  81.  
  82.         _state.position = transform.position;
  83.         _state.localPosition = transform.localPosition;
  84.  
  85.         return _state;
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement