Let's Create - Player Controller in Unity

Download this episode

Download Video


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

        // draw debug ray

    void FixedUpdate()
        // runs movement functions

    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);




Available formats for this video:

Actual format may change based on video formats available and browser capability.

    The Discussion

    Comments closed

    Comments have been closed since this content was published more than 30 days ago, but if you'd like to send us feedback you can Contact Us.