代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveBody : MonoBehaviour
{
// Start is called before the first frame update
public float speed_walk = 10f;//走路速度
public Vector3 move_direction;//人物移动方向
public CharacterController character_control;
public bool isWalk;//用来判断是否在走路
void Start()
{
character_control = this.GetComponent<CharacterController>();//获取CharacterController组件
}
// Update is called once per frame
void Update()
{
move();//前后左右
}
void move()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
move_direction = transform.right * h + transform.forward * v;//移动的方向
//Debug.Log(move_direction * speed_walk * Time.deltaTime);
if(move_direction * speed_walk * Time.deltaTime != Vector3.zero)
{
isWalk = true;
}
else
{
isWalk = false;
}
character_control.Move(move_direction * speed_walk * Time.deltaTime);//移动
}
通过CharacterController组件来控制物体移动,
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
move_direction = transform.right * h + transform.forward * v;//移动的方向
这三行代码用于获取物体移动方向,move_direction是一个三维向量,默认是0向量,物体移动就会变为非零向量。
最后就用character_control.Move(move_direction * speed_walk * Time.deltaTime);来移动物体啦
这种方法可以实现物体爬坡,用WASD操控物体移动即可。
后期教程将逐步完善代码。