Unity学习笔记-角色移动

1.使用transform进行移动

强制移动,直接改变物体的位置,例如:

public float speed = 3;
Vector3 move;

void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        Move(h, 0, v);
    }

 void Move(float x, float y, float z)
    {
        move = new Vector3(x, y, z);
        Vector3 to = transform.position + move;    //要看向的目标点
        transform.LookAt(to);
        transform.position += move * speed * Time.deltaTime;
    }

对于某些碰撞不好处理,比如说怼着墙走会发生抖动。

2.使用RigidBody进行移动

借助刚体组件移动,代码要写在FixedUpdate中,如:

    public float speed = 3;
    Rigidbody rigid;
    Vector3 move;

    void Start()
    {
        rigid = GetComponent<Rigidbody>();
    }

    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        move = new Vector3(h, 0, v);
    }
    private void FixedUpdate()
    {
        Vector3 v = move * speed;
        v.y = rigid.velocity.y;  //对y方向的速度进行保护
        rigid.velocity = v;
        // 让刚体朝向目标
        Quaternion q = Quaternion.LookRotation(move);
        rigid.MoveRotation(q);
    }
3.使用角色控制器控制角色的移动

角色控制器是unity的一个组件,添加了该组件后,不需要再添加Rigidbody和碰撞体,因为它已经包含了相关功能。

Slope Limit: 斜坡角度限制,角度大于该值的斜坡角色就上不去

Step Offset: 台阶高度设置,高于该值的障碍物角色不能直接移动过去

Skin Width: 皮肤宽度,就相当于第二层碰撞盒,该值不能大于下方的碰撞盒的Radius值,否则会卡在某个地方。一般这个值在Radius的5%左右

Center Radius Height: 设置碰撞盒的中心位置、半径、高度

脚本如下:

    CharacterController cc;
    public float speed = 3;
    Vector3 move;
 
    void Start()
    {
        cc = GetComponent<CharacterController>();
    }

    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        Move(h, 0, v);
    }

    void Move(float x, float y, float z)
    {
        move = new Vector3(x, 0, z);
        Vector3 m = move * speed * Time.deltaTime;
        //朝向移动方向
        transform.LookAt(transform.position + move);
        //通过cc去移动
        cc.Move(m);
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值