using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour {
public Transform cam; // Ссылка на Transform камеры, чтобы получить ее rotation
// Скорость ходьбы и бега
public float walkSpeed=8.0f;
public float runSpeed=20.0f;
// Скорость поворота
public float rotaionSpeed=15.0f;
// Приватные компоненты
private CharacterController controller;
private Animator animator;
// Для SmoothDampAngle
float currentVelocity;
public float speedsmoothTime=0.2f;
public float AnimspeedSmoothTime=0.1f;
float velocityY;
public float gravity=-9.8f;
public float jumpHeight=20.0f;
void Start () {
// Получаем компоненты
controller = GetComponent<CharacterController> ();
animator = GetComponent<Animator> ();
}
void Update () {
// Получаем ввод от пользователя
Vector2 input = new Vector2 (Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"));
// Нормализуем вектор
Vector2 inputDir = input.normalized;
if(Input.GetKeyDown(KeyCode.Space)){
Jump();
}
if (inputDir != Vector2.zero) {
// Вычисляем нужный поворот... тут самая жесть <img src="./images/smilies/2.gif" alt=":(" title="Sad" />
float targetRotation = Mathf.Atan2(inputDir.x,inputDir.y)*Mathf.Rad2Deg+cam.eulerAngles.y;
transform.rotation = Quaternion.AngleAxis(Mathf.SmoothDampAngle(transform.eulerAngles.y,targetRotation,ref currentVelocity,speedsmoothTime),Vector3.up);
// Или можно так
// transform.eulerAngles = Vector3.up*(Mathf.SmoothDampAngle(transform.eulerAngles.y,targetRotation,ref currentVelocity,speedsmoothTime));
// Просто тут тяжело понять, что вращаем относительно оси Y
}
// Булева переменная, считывающая бежит ли персонаж или идёт
bool isRunning = Input.GetKey (KeyCode.LeftShift) && controller.isGrounded;
// Основываясь на переменной, описанной выше, вычисляем скорость
float speed = ((isRunning) ? runSpeed : walkSpeed) * inputDir.magnitude;
Vector3 velocity;
velocity = transform.forward*speed+Vector3.up*velocityY;
velocityY += Time.deltaTime * gravity;
// Вычисляем вектор перемещения
// Двигаем персонажа
controller.Move(velocity*Time.deltaTime);
if (controller.isGrounded) {
velocityY = 0;
}
float currentSpeed = new Vector2 (controller.velocity.x, controller.velocity.z).magnitude;
// Работаем с аниматором
float animationSpeedPercent = ((isRunning)? currentSpeed/runSpeed : currentSpeed/walkSpeed*0.5f);
// Делаем анимацию плавной, иначе слишком дёрганно всё получается
animator.SetFloat("speedPercent",animationSpeedPercent,AnimspeedSmoothTime,Time.deltaTime);
}
void Jump(){
if (controller.isGrounded) {
float jumpVelocity = Mathf.Sqrt (-2 * gravity * jumpHeight);
velocityY = jumpVelocity;
}
}
}