As a first step towards learning about how animation works in unity I began a project and started writing a very simple player controller in C#. Currently, the player can move forwards, backwards, left, right and diagonally between all directions.
Script:
Here is my basic player controller script written in C# :
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControl : MonoBehaviour { //public varibles public float MoveSpeed = 5F; Rigidbody body; // Use this for initialization void Start () { //get ridgid body body = gameObject.GetComponent<Rigidbody>(); } // Update is called once per frame void Update () { //reset velocity to zero body.velocity = Vector3.zero; if (Input.GetAxis("Horizontal") != 0) { body.velocity += Vector3.right * MoveSpeed * Input.GetAxis("Horizontal"); print("horizontal input recived"); } if (Input.GetAxis("Vertical") != 0) { body.velocity += Vector3.forward * MoveSpeed * Input.GetAxis("Vertical"); print("vertical input recived"); } } }
One of the first things that is useful to know is what public variables are. They are variables that are set with the keyword public in front of them which allows for them to be edited in the editor. This is useful because it allows for iteration without having to go into the script and change the values there. In the case of my script I have one called MoveSpeed which is a float I use to determine how fast I want the player to move. Having this available in editor makes it much easier to fine tune.
In the start function which is called once when the game object is created. In the case of the player character it is called at the start of the game. I get the ridged body of the player so I can manipulate it. I get it here so it only gets grabbed once.
Update is called on every frame and it is here that I check for input to determine how to move the player. One of the things I learn was that in order for the player to move in multiple directions I need to use the += operator to change the velocity so that it would be accumulative. This does necessitate resetting to zero at the start of update or setting a max value of the velocity or the player will accelerate on every frame.
Link to project on github: https://github.com/irisra1/Player-Controller
No comments:
Post a Comment