Let's Create - Player Controller in Unity

Sign in to queue

Description

Full source project:  https://github.com/jasonrwalters/Unity_PlayerController

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public bool debugOn;
    public float speed;

    private Rigidbody rigid;
    private Vector3 inputMove;
    private float turnY;

    // Use this for initialization
    void Start()
    {
        // reference components
        rigid = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        // runs input functions
        PlayerInput();

        // draw debug ray
        DrawDebugRays(debugOn);
    }

    void FixedUpdate()
    {
        // runs movement functions
        Movement();
    }

    void PlayerInput()
    {
        // fetch input and send to vector3
        float moveX = Input.GetAxis("Horizontal") * (speed/2);
        float moveZ = Input.GetAxis("Vertical") * speed;
        inputMove = new Vector3(moveX, 0.0f, moveZ);
    }

    void Movement()
    {
        // add our input to rigidbody's forward facing velocity
        rigid.velocity = transform.forward * inputMove.z;

        // rotate player based on input
        turnY += inputMove.x;
        rigid.rotation = Quaternion.Euler(0.0f, turnY, 0.0f);
    }

    void DrawDebugRays(bool active)
    {
        if (active)
        {
            // draws debug ray so we can test forward direction
            Vector3 forward = transform.TransformDirection(Vector3.forward) * 5;
            Debug.DrawRay(transform.position, forward, Color.green);
        }
    }
}

 

Embed

Download

Download this episode

The Discussion

Add Your 2 Cents