Turning and moving characters in unity3d

Time:2021-4-16

On the Internet, there are a lot of character walking control scripts implemented by ray mode, but suppose that they only want to control by keyboard keys. For example, the third person perspective control, in fact, only need a simple angle change. The ideas are as follows:

1. Set the front, right, back and left as 0, 1, 2 and 3 in clockwise direction.

2. Set the initial value of 0, that is, toward the front.

3. By subtracting the previous direction value from the current direction value, multiplying by 90 ° is the steering angle, and then the rotation transformation can be carried out.

using UnityEngine;
using System.Collections;
using System.Linq;
public class move: MonoBehaviour
{
 Private int state; // role state
 Private int oldstate = 0; // state 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; // role status 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 translation vector
 int rotateValue = (currState - State) * 90;
 transform.animation.Play ("walk"); // play the character walking animation
 switch (currState)
 {
 Case 0 //: when the character state is forward, the character moves forward slowly
  transformValue = Vector3.forward * Time.deltaTime * speed;
  break;
 Case 1 //: when the role status is right. The character moves slowly to the right
  transformValue = Vector3.right * Time.deltaTime * speed;
  break;
 Case 2: // when the role status is backward. The character moves back and forth slowly
  transformValue = Vector3.back * Time.deltaTime * speed;
  break;
 Case 3: when the character state is left, the character moves slowly to the left
  transformValue = Vector3.left * Time.deltaTime * speed;
  break;
 }
 transform.Rotate (vector3. Up, rotatevalue); // rotate character
 transform.Translate (transformValue,  Space.World ); // translate characters
 Oldstate = state; // assignment for next calculation
 State = currstate; // assign value to facilitate the next calculation
 }
 
 
}

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.