Unity2019.4.31f1 物体动画切换与移动

控制小鸡每隔一定时间就随机执行一个动作,该动作在三个动作中随机选择:摆头,吃东西,行走。其中行走会随机选择一个方向,进行旋转并前进一段时间。

ChickenController.cs:

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

public class ChickenController : MonoBehaviour
{
    public float minChangeTime = 10f;
    public float maxChangeTime = 20f;
    public float walkSpeed = 0.5f;
    public float walkTime = 3f;
    public float turnSpeed = 2f;

    bool isGenerated = false;
    float timer = 0f;
    float changeTime = 0;
    Animator animator;
    string triggerName = "";
    string[] triggerNames = { "Eat", "Turn Head", "IsWalking" };
    System.Random r;
    new Rigidbody rigidbody;
    Vector3 initialPos;
    bool isWalking = false;
    Vector3 targetDirection;
    Quaternion rotation = Quaternion.identity;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
        r = new System.Random();
        rigidbody = GetComponent<Rigidbody>();
        initialPos = rigidbody.position;
        targetDirection = transform.forward;
    }

    void FixedUpdate()
    {
        if (isWalking)
        {
            Walk();
            return;
        }

        if (!isGenerated)
        {
            isGenerated = true;
            changeTime = Random.Range(minChangeTime, maxChangeTime);
            int triggerIndex = r.Next(0, triggerNames.Length);
            triggerName = triggerNames[triggerIndex];
        }

        timer += Time.deltaTime;
        if (timer >= changeTime)
        {
            if (triggerName == "IsWalking")
            {
                isWalking = true;
                animator.SetBool(triggerName, true);
                targetDirection = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f));
                targetDirection.Normalize();
            }
            else
            {
                animator.SetTrigger(triggerName);
            }

            timer = 0;
            isGenerated = false;
        }
    }

    void Walk()
    {
        if (timer > walkTime)
        {
            isWalking = false;
            animator.SetBool(triggerName, false);
            timer = 0;
            return;
        }

        Vector3 pos = rigidbody.position;
        pos += transform.forward * walkSpeed * Time.deltaTime;

        Vector3 desiredForward = Vector3.RotateTowards(transform.forward,
            targetDirection, turnSpeed * Time.deltaTime, 0f);
        rotation = Quaternion.LookRotation(desiredForward);

        rigidbody.MovePosition(pos);
        rigidbody.MoveRotation(rotation);

        timer += Time.deltaTime;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值