【Unity基础】RigidBody 、CharacterController控制角色移动

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);
    }
}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值