I. Introduction
Today I share a simple character movement script, mainly using colliders and rigid body components. The code is simple and easy to understand, and it has strong reusability and scalability. Let's take a look with me.
Second, the effect chart
Third, the code
using UnityEngine;
public class RunTest1 : MonoBehaviour
{
public float forwardSpeed; //前进的速度
public float backwardSpeed; //后退的速度
public float rotateSpeed; //旋转速度
private Vector3 velocity;
void FixedUpdate()
{
//获取到横轴 前后 的输入 也就是键盘W 和S的输入
float h = Input.GetAxis("Horizontal");
//获取到纵轴 左右 的输入 也就是键盘A 和D的输入
float v = Input.GetAxis("Vertical");
//从上下键的输入,获取到Z轴的输入量
velocity = new Vector3(0, 0, v);
//将世界坐标转化为本地坐标
velocity = transform.TransformDirection(velocity);
//判断是前进还是后退
if (v > 0.1)
{
velocity *= forwardSpeed;
}
else
{
velocity *= backwardSpeed;
}
//移动自身坐标
transform.localPosition += velocity * Time.fixedDeltaTime;
//旋转角度
transform.Rotate(0, h * rotateSpeed, 0);
}
}
Fourth, the implementation steps
1. First, we design the scene first
. Create a new Plane in the scene, set the width and length
2. Create a new Capsule, assuming this is the protagonist
Add a rigid body component, lock the rotation of XYZ
3. Set the camera follower to
be directly set as a child object of Capsule , Simple and rough, and then set the position rotation angle
4. Write RunTest.cs script
using UnityEngine;
public class RunTest1 : MonoBehaviour
{
public float forwardSpeed; //前进的速度
public float backwardSpeed; //后退的速度
public float rotateSpeed; //旋转速度
private Vector3 velocity;
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
velocity = new Vector3(0, 0, v);
velocity = transform.TransformDirection(velocity);
if (v > 0.1)
{
velocity *= forwardSpeed;
}
else
{
velocity *= backwardSpeed;
}
transform.localPosition += velocity * Time.fixedDeltaTime;
transform.Rotate(0, h * rotateSpeed, 0);
}
}
5. Assign the script to the Capsule object
Set the parameters
5. Run to
start a happy play