Unity使用OffMesh-Link时匹配动画动作

正常Unity的OffmeshLink是嗖的一下传送过去,如果要想在这里用自己的动画动作跳跃过去的方法如下,主要是知道Unity的一些相关API的使用方法。

下面是一些重要的API或数据结构:

_navAgent.autoTraverseOffMeshLink = false; //in Start(),设置不要自动进行Offmeh的传送
_navAgent.currentOffMeshLinkData; //the link data - this contains start and end points, etc
_navAgent.CompleteOffMeshLink(); //Tell unity we have traversed the link (do this when you've moved the transform to the end point)
_navAgent.Resume(); //Resume normal navmesh behaviour

代码示例如下:

using UnityEngine;

[RequireComponent(typeof(NavMeshAgent))]
public class NavMeshAnimator : MonoBehaviour
{
    
    
    private NavMeshAgent _navAgent;
    private bool _traversingLink;
    private OffMeshLinkData _currLink;

    void Start()
    {
    
    
        // Cache the nav agent and tell unity we will handle link traversal
        _navAgent = GetComponent<NavMeshAgent>();
        _navAgent.autoTraverseOffMeshLink = false;
    }

    void Update()
    {
    
    
        //don't do anything if the navagent is disabled
        if (!_navAgent.enabled) return;

        if (_navAgent.isOnOffMeshLink)
        {
    
    
            if (!_traversingLink)
            {
    
    
                //This is done only once. The animation's progress will determine link traversal.
                animation.CrossFade("Jump", 0.1f, PlayMode.StopAll);
                //cache current link
                _currLink = _navAgent.currentOffMeshLinkData;
                //start traversing
                _traversingLink = true;
            }

            //lerp from link start to link end in time to animation
            var tlerp = animation["Jump"].normalizedTime;
            //straight line from startlink to endlink
            var newPos = Vector3.Lerp(_currLink.startPos, _currLink.endPos, tlerp);
            //add the 'hop'
            newPos.y += 2f * Mathf.Sin(Mathf.PI * tlerp);
            //Update transform position
            transform.position = newPos;

            // when the animation is stopped, we've reached the other side. Don't use looping animations with this control setup
            if (!animation.isPlaying)
            {
    
    
                //make sure the player is right on the end link
                transform.position = _currLink.endPos;
                //internal logic reset
                _traversingLink = false;
                //Tell unity we have traversed the link
                _navAgent.CompleteOffMeshLink();
                //Resume normal navmesh behaviour
                _navAgent.Resume();
            }
        }
        else
        {
    
    
            //...update walk/idle animations appropriately ...etc

猜你喜欢

转载自blog.csdn.net/alexhu2010q/article/details/108143675