RigidBody
首先要给角色添加刚体和碰撞器:
注意刚体下面的Contrains选项里面选择冻结刚体的旋转 不然对人物施加力的时候会摔倒
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerRig : MonoBehaviour
{
Rigidbody rig;
Animator animator;
public float speed = 5.0f;
public AudioClip clipFoot;
void Start()
{
rig = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(h, 0, v);
Vector3 dirWorld = Camera.main.transform.TransformDirection(dir);
dirWorld.y = 0;
dirWorld.Normalize();
transform.LookAt(dirWorld + transform.position);
//定义一个速度: 由单位向量*一个固定值
Vector3 curVel = dirWorld * speed;
// 由于 dirWorld 向量的y轴方向没有大小, 所以要把物体y轴上的速度加到curVel的y轴上
curVel.y = rig.velocity.y;
// 最后把这个向量赋值给刚体速度, 这个curVel的x z 轴速度是由按键输入赋值, y轴大小是物体的重力
rig.velocity = curVel;
animator.SetFloat("Speed", dirWorld.magnitude);
}
void playFootSound()
{
AudioSource.PlayClipAtPoint(clipFoot, transform.position);
}
}
CharacterController
添加组件 CharacterController
设置Center属性和Radius 这是碰撞器大小
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerCC : MonoBehaviour
{
Animator animator;
CharacterController cc;
float speed = 3.0f;
Vector3 speedDown;
public AudioClip clipFoot;
void Start()
{
animator = GetComponent<Animator>();
cc = GetComponent<CharacterController>();
}
void Update()
{
if (!cc.isGrounded)
{
speedDown.y += Physics.gravity.y * Time.deltaTime;
}
else
{
speedDown.y = 0;
}
cc.Move(speedDown * Time.deltaTime);
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(h, 0, v);
Vector3 dirWorld = Camera.main.transform.TransformDirection(dir);
dirWorld.y = 0;
animator.SetFloat("Speed", dirWorld.magnitude);
transform.LookAt(transform.position + dirWorld);
cc.Move(dirWorld * speed * Time.deltaTime);
}
void playFootSound()
{
AudioSource.PlayClipAtPoint(clipFoot, transform.position);
}
}