There are many character walking control scripts on the Internet that are implemented through the ray method, but if you only want to control the scripts by pressing the keyboard, such as third-person perspective control, in fact, you only need to perform a simple angle change. The idea is as follows:
1. Set the front, right, back, and left values to 0, 1, and 2, respectively, clockwise.
2. Set the initial state value 0, that is, toward the front.
3. Subtract the previous direction value from the current direction value, multiply it by 90 ° to the steering angle, and then perform rotation and transformation.
Using UnityEngine; using System. collections; using System. linq; public class move: MonoBehaviour {private int State; // role State private int oldState = 0; // The status of the previous role private int UP = 0; // role status forward private int RIGHT = 1; // role status RIGHT private int DOWN = 2; // role status backward private int LEFT = 3; // The role status changes to left public float speed = 8; void Start () {} void Update () {if (Input. getKey ("w") {setState (UP);} else if (Input. getKey ("s") {setState (DOWN);} if (Input. getKey ("a") {setState (LEFT);} else if (Input. getKey ("d") {setState (RIGHT) ;}} void setState (int currState) {Vector3 transformValue = new Vector3 (); // define the translation vector int rotateValue = (currState-State) * 90; transform. animation. play ("walk"); // Play the role walk animation switch (currState) {case 0: // when the role status is forward, the role continues to move slowly transformValue = Vector3.forward * Time. deltaTime * speed; break; case 1: // when the role is in the right state, the role continues to move slowly to the right transformValue = Vector3.right * Time. deltaTime * speed; break; case 2: // when the role status is backward, the role continues to slowly move transformValue = Vector3.back * Time. deltaTime * speed; break; case 3: // when the role status is left, the role continues to move slowly to the left transformValue = Vector3.left * Time. deltaTime * speed; break;} transform. rotate (Vector3.up, rotateValue); // Rotate the role transform. translate (transformValue, Space. world); // translation role oldState = State; // assign a value to facilitate the next calculation of State = currState; // assign a value for the next calculation }}