unity开发知识点小结04

混合动画

在动画器控制器中创建从新混合树,也就是创建混合动画
在这里插入图片描述
然后进入混合动画,选择混合类型为1D(表示传递参数只有一个),并且为此混合状态添加两个动画,并且设定混合状态参数为何值得时候启用相应动画,笔者这里使用的例子是用0表示走路,1表示跑步,中间值表示两个状态叠加

在这里插入图片描述

IK实现身体某个部位朝固定方向旋转

如头部,手部等确定位置

首先我们要将创建的目标物体也就是人物需要看向的物体设置为人物的目标物体

在这里插入图片描述
同时我们要在动画器设置器里面将被图层的IK处理开启
在这里插入图片描述
接下来便是为人物编写脚本实现人物运动的同时可以可以实现人物头部朝固定位置移动,或者看向固定位置

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class peopleRun : MonoBehaviour
{
    
    
    private Animator animator;
    public Transform target;
    void Start()
    {
    
    
        animator = GetComponent<Animator>();
        
    }

    
    void Update()
    {
    
    
        //获取水平轴
        float horizontal = Input.GetAxis("Horizontal");
        //获取垂直轴
        float veritial = Input.GetAxis("Vertical");
        //创建方向向量
        Vector3 dir = new Vector3(horizontal,0,veritial);
        //当用户按下方向按键
        if (dir != Vector3.zero)
        {
    
    
            //更改人物朝向
            transform.rotation = Quaternion.LookRotation(dir);
            //播放移动动画
            animator.SetBool("run", true);
            //实现人物移动
            transform.Translate(Vector3.forward * 2 * Time.deltaTime);
        }
        else {
    
    
            //松开方向键恢复静止动画
            animator.SetBool("run",false);
        }
    }
    //实现人物部位指向固定位置
    private void OnAnimatorIK(int layerIndex)
    {
    
    
        //设置头部IK
        animator.SetLookAtWeight(1) ;
        //让角色实现头部旋转
        animator.SetLookAtPosition(target.position);
        //设置右手Ik权重
        animator.SetIKPositionWeight(AvatarIKGoal.RightHand,1);
        //旋转权重
        animator.SetIKRotationWeight(AvatarIKGoal.RightHand,1);
        //设置手臂指向方向
        animator.SetIKPosition(AvatarIKGoal.RightHand,target.position);
        //设置手臂旋转方向
        animator.SetIKRotation(AvatarIKGoal.RightHand,target.rotation);
    }
}

物体移动实现自动导航,自主选择可运行路线

首先我们创建一个有障碍物的地图,并且对地图进行烘焙,观察地图区域可运行范围
将障碍物物体全部设为Navigation Static
在这里插入图片描述
进入导航对地图进行烘焙
在这里插入图片描述
地图上会显示玩家可以走的区域
在这里插入图片描述
创建玩家实体,并且为玩家添加Nav Mesh Agent组件,并且为物体编写导航移动脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class NavigationTest : MonoBehaviour
{
    
    
    private NavMeshAgent agent;
    void Start()
    {
    
    
        //获取代理组件
        agent = GetComponent<NavMeshAgent>();
    }
    void Update()
    {
    
    
        //如果按下鼠标
        if (Input.GetMouseButtonDown(0)) {
    
    
            //获取点击位置
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            //判断射线是否碰到物体
            if (Physics.Raycast(ray,out hit)) {
    
     
                //点击的位置
                Vector3 point = hit.point;
                //设置该位置为导航目标点
                agent.SetDestination(point);    
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_48627750/article/details/129398034
今日推荐