Controller

mail@pastecode.io avatar
unknown
csharp
a year ago
3.0 kB
1
Indexable
Never
using UnityEngine;
using System.Collections;


[RequireComponent(typeof(Rigidbody))]

public class PlayerControl : MonoBehaviour {

	[Header("Скорость:")]
	public float speed = 4f;
	public float acceleration = 10f;
	public float RunSpeed = 3f;
			
	[Header("Поворот:")]
	public Transform bodyTransform; 
	public float smooth = 3;
	public bool useSmooth;

	[Header("Скрипт контроля камеры")]
	public Transform cameraParent;
	
	private Vector3 direction;
	private Rigidbody body;
	public Animator _anim;
	private float vertical;
    private float horizontal;
	Vector3 camForward;
	Vector3 move;
	Vector3 moveInput;
	Transform Cam;

	float forwardAmount;
	float turnAmount;

	void Awake()
	{
		body = GetComponent<Rigidbody>();
		body.freezeRotation = true;
		_anim = GetComponent<Animator>();
		
		Cam = Camera.main.transform;
		
	}
	
	void FixedUpdate()
	{
		vertical = Input.GetAxis("Vertical");
        horizontal = Input.GetAxis("Horizontal");

		if(Cam != null)
		{
			camForward = Vector3.Scale(Cam.up, new Vector3(1,0,1)).normalized;
			move = vertical * camForward + horizontal * Cam.right;
		}
		else 
		{
			move = vertical * Vector3.forward + horizontal * Vector3.right;
		}

		if (move.magnitude > 1)
		{
			move.Normalize();
		}

		Move(move);

		body.AddForce(direction.normalized * acceleration * body.mass * speed);
		if(Mathf.Abs(body.velocity.x) > speed)
		{
			body.velocity = new Vector3(Mathf.Sign(body.velocity.x) * speed, body.velocity.y, body.velocity.z);
		}
		if(Mathf.Abs(body.velocity.z) > speed)
		{
			body.velocity = new Vector3(body.velocity.x, body.velocity.y, Mathf.Sign(body.velocity.z) * speed);
		}

		Rotation();
		
	}
	void Move(Vector3 move)
	{
		if(move.magnitude > 1)
		{
			move.Normalize();
		}

		this.moveInput = move;

		ConvertMoveInput();
		UpdateAnimator();
	}

	void ConvertMoveInput()
	{
		Vector3 localMove = transform.InverseTransformDirection(moveInput);
		forwardAmount = localMove.z;
		turnAmount = localMove.x;
	}

	void UpdateAnimator()
	{
		_anim.SetFloat("Forward", forwardAmount, 0.1f, Time.deltaTime);
		_anim.SetFloat("Turn", turnAmount, 0.1f, Time.deltaTime);
	}
	void Rotation() 
	{
		Vector3 lookPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.y)) - body.position;
		lookPos.y = 0; 

		if(useSmooth)
		{
			Quaternion playerRotation = Quaternion.LookRotation(lookPos);
			bodyTransform.rotation = Quaternion.Lerp(bodyTransform.rotation, playerRotation, smooth * Time.fixedDeltaTime);	
		}
		else
		{
			bodyTransform.rotation = Quaternion.LookRotation(lookPos);
		}
	}

	void Update()
	{
		float h = Input.GetAxis("Horizontal");
		float v = Input.GetAxis("Vertical");
		
		
		direction = new Vector3(h, 0, v);
		direction = cameraParent.TransformDirection(direction);
		direction = new Vector3(direction.x, 0, direction.z);
    }
}