Character Controller Unity – Movimiento Relativo a Camara

Character Controller Unity – Movimiento Relativo a Camara

Seguimos con nuestro tutorial para aprender a usar el Character Controller y mover a tu personaje en Unity 3D 2018!!
En este video aprenderemos a mover a nuestro jugador con respecto a la direccion de la camara y al mismo tiempo ajustaremos el input para evitar incrementos en la velocidad al movernos en diagonal.

Script PlayerController:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

        public float horizontalMove;
        public float verticalMove;
        private Vector3 playerInput;      

        public CharacterController player;

        public float playerSpeed;
        private Vector3 movePlayer; 

        public Camera mainCamera;       
        private Vector3 camForward;     
        private Vector3 camRight;    

	// Use this for initialization
	void Start () {
        player = GetComponent<CharacterController>();
	}
	
	// Update is called once per frame
	void Update () {

        horizontalMove = Input.GetAxis("Horizontal");
        verticalMove = Input.GetAxis("Vertical");            

        playerInput = new Vector3(horizontalMove, 0, verticalMove);     
        playerInput = Vector3.ClampMagnitude(playerInput, 1);           

        CamDirection();                                                 

        movePlayer = playerInput.x * camRight + playerInput.z * camForward;     

        player.transform.LookAt(player.transform.position + movePlayer);        
        
        player.Move(movePlayer * playerSpeed * Time.deltaTime);  
   
        Debug.Log(player.velocity.magnitude);       
    }

    //Funcion para determinar la direccion a la que mira la camara.  
    public void CamDirection()
    {
        camForward = mainCamera.transform.forward;
        camRight = mainCamera.transform.right;

        camForward.y = 0;
        camRight.y = 0;

        camForward = camForward.normalized;
        camRight = camRight.normalized;
    }
}

No te pierdas esta serie de tutoriales en los que aprenderemos juntos a utilizar el motor Unity 3D y crearemos nuestros propios videojuegos!

Deja un comentario