当 NPC 向左或向右走时,如何使动画匹配?

Posted

技术标签:

【中文标题】当 NPC 向左或向右走时,如何使动画匹配?【英文标题】:How can I make the animation match when the NPC walks left or right? 【发布时间】:2022-01-01 13:50:57 【问题描述】:

我有一些 NPC 在一个范围内随机走动,但是当我无法确定它们是向左还是向右走时,动画看起来不对。

我有一个名为“Decrease”的函数,当对象行走时,它会在终端内发出警告,减少或增加其位置,但该函数无法正常工作

所以...

NPC向左或向右走时如何使动画匹配?

这是我的 NPC 配置:

这是我的代码:

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

public class NPCController : MonoBehaviour

    private float waitTime;
    private Animator _animator;
    private SpriteRenderer _renderer;

    public Transform moveSpot;
    private bool _facingRight = true;
    public float lastXVal;
    public float speed;
    public float startWaitTime;
    public float minX;
    public float maxX;
    public float minY;
    public float maxY;

    void Awake()
    
        _animator = GetComponent<Animator>();
        _renderer = GetComponent<SpriteRenderer>();
    

    void Start()
    
        waitTime = startWaitTime;
        moveSpot.position = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY));
    

    void Update()
    
        transform.position = Vector2.MoveTowards(transform.position, moveSpot.position, speed * Time.deltaTime);

        if (Vector2.Distance(transform.position, moveSpot.position) < 0.2f)
        
            //Change animation state
            if (waitTime <= 0)
            
                _animator.SetBool("Walk", true);
                moveSpot.position = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY));
                waitTime = startWaitTime;
            
            else
            
                _animator.SetBool("Walk", false);
                _animator.SetBool("Idle", true);
                waitTime -= Time.deltaTime;
            
        
    

    public void Decrease()
    
        if (transform.hasChanged)
        
            if (transform.position.x < lastXVal)
            
                //Update lastXVal
                lastXVal = transform.position.x;
                Debug.Log("Decreased!");
            

            else if (transform.position.x > lastXVal)
            
                //Update lastXVal
                lastXVal = transform.position.x;
                Debug.Log("Increased");
            

            transform.hasChanged = false;
        
    


【问题讨论】:

【参考方案1】:

您可以使用点积来计算行进方向。

Vector2 moveDirection = (moveSpot.position - transform.position).normalized;
float dotValue = Vector2.Dot(Vector2.right, moveDirection)

// if dotValue is 1 then you are moving right and if dotValue is -1 you are moving left

【讨论】:

这工作得很好,但是有必要使用开关执行例程并转换旋转,非常感谢

以上是关于当 NPC 向左或向右走时,如何使动画匹配?的主要内容,如果未能解决你的问题,请参考以下文章

在 UITableViewCell 中的任意位置向左或向右滑动以删除没有删除按钮的单元格?

如何在 Android 中检测向左或向右滑动?

UITableViewCell 如何检测用户向左或向右滑动?

MotionLayout 左右滑动动画问题

如何将每个 JPanel 向左或向右对齐到主 JPanel

用 UIView 像书一样翻页?