Let's Create - Player Controller in Unity

Download this episode

Download Video

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

Format

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 continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.