记录Unity3D中的几种角色控制方式

1.使用Transform直接控制

public int speed;
Vector3 input;
void Update()
{
  //使用一个input向量接收按键的输入
  input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
  Move();
}

void Move()
{
    //将input单位化,防止斜方向上速度过快
    input = input.normalized;
    transform.position += input * speed * Time.deltaTime;

    //令角色前方和移动方向一致
    //magnitude 返回向量长度
    if(input.magnitude > 0.1f)
    {
        transform.forward = input;
    }
}

2.使用RigidBody控制

//获取刚体已经进行设定
void Start()
{
    rigid = GetComponent<Rigidbody>();
    //刚体的设定
    rigid.drag = 5;
    rigid.mass = 30;
    rigid.constraints = RigidbodyConstraints.None |
    RigidbodyConstraints.FreezeRotationX |
    RigidbodyConstraints.FreezeRotationY |
    RigidbodyConstraints.FreezeRotationZ;
}

//首先获得两个方向的值,
//h -1 to 1  v -1 to 1
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//合成一个move向量,代表实际移动的方向
Vector3 move = v * Vector3.forward + h * Vector3.right;
//单位化,防止斜方向上速度过快
if (move.magnitude > 1f)
    move.Normalize();
//将move从世界空间转到player的本地空间
move = transform.InverseTransformDirection(move);
//将move投影在地板的2D平面上 与爬坡有关,暂时无用
//move = Vector3.ProjectOnPlane(move, groundNormal);
//这三个值与动画效果有关
turnAmount = Mathf.Atan2(move.x, move.z);
rightAmount = move.x;
forwardAmount = move.z;

//实际的移动
transform.Rotate(0, turnAmount * angularSpeed * Time.deltaTime, 0);
velocity = transform.forward * forwardAmount * speed;
//关键
rigid.MovePosition(rigid.position + velocity * Time.fixedDeltaTime);

3.使用Character Controller组件

首先给要操纵的物体加上Character Controller组件

//PlayerCharacter.cs
Vector3 velocity;
void Start()
{
    //获取组件
    CC = GetComponent<CharacterController>();
}

void Update()
{
    //根据速度实现具体的移动
     //velocity是最终移动的方向
    //使用CC.move()进行移动
    CC.Move(velocity * Time.deltaTime);
    //跳起来 Physics.gravity.y 是负数 到达地面就为0了捏
    velocity.y += CC.isGrounded ? 0 : Physics.gravity.y * 10 * Time.deltaTime;
}
//获得移动向量
public void Move(float InputX, float InputZ)
{
    if(InputX != 0 || InputZ != 0)
    {
        Turn(Vector3.right * InputX + Vector3.forward * InputZ, TurnSpeed);
    }
    velocity.x = InputX * Speed;
    velocity.z = InputZ * Speed;
}
//转身
public void Turn(Vector3 dir, float turnSpeed)
{
    //一个平滑的旋转 
    Quaternion q = Quaternion.LookRotation(dir);
    Quaternion slerp = Quaternion.Slerp(transform.rotation, q, turnSpeed * Time.deltaTime);
    transform.rotation = slerp;
}
//跳跃
public void Jump()
{
  if (CC.isGrounded)
  {
      velocity.y = JumpSpeed;
  }
}


//PlyaerController.cs
void Start()
{
    player = GetComponent<PlayerCharacter>();
}

void Update()
{
    float InputX = Input.GetAxis("Horizontal");
    float InputZ = Input.GetAxis("Vertical");
    //转身和加入x速度
    player.Move(InputX,InputZ);
    if (Input.GetKeyDown(KeyCode.Space))
    {
        //加入y速度
        player.Jump();
    }
}
原文地址:https://www.cnblogs.com/linqd/p/somemethodtocontrollplayer.html