unity实现简单的动物随机移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimalStatus : MonoBehaviour
{
    Animator anim;
    //初始位置
    float InitialPosition;
    //目标位置
    float TargetPosition;

    //每次转速
    int sky = -300;

    //上次移动是否完成
    bool StateMotion = true;
    //上次旋转是否完成
    bool AngleMotion = true;

    //是否休息
    bool WhetherRest = false;

    //行走速度
    public float MoveSpeed = 3.0f;
    //奔跑速度
    public float RunSpeed = 6.0f;

    //确定移动次数
    int Distance;
    //确定移动状态:1/走 0/跑
    int c = 1;


    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent();

        //获取物体的初始位置
        InitialPosition = transform.localPosition.z;
    }

    // Update is called once per frame
    void Update()
    {
        //确定转头方向
        int d = Random.Range(0, 2);

        float Statu = c == 1 ? MoveSpeed : RunSpeed;
        if (StateMotion)
        {
            Distance = Random.Range(20, 30);
            StateMotion = false;
        }

        //生成随机数(0-15);确定旋转次数。
        int RotateAngle = Random.Range(0, 15);
        if (!WhetherRest)
        {
            if (AngleMotion)
            {
                if (d == 1)
                {
                    sky = -sky;
                }
                AngleMotion = false;
                for (int i = 0; i < RotateAngle; i++)
                {
                    transform.Rotate(0, sky * Time.deltaTime, 0, Space.Self);
                }

            }

            if ((Distance--) != 0)
            {
                if (c == 1)
                {
                    StopAnimation();
                    anim.SetBool("ToWalk", true);
                }
                else
                {
                    StopAnimation();
                    anim.SetBool("ToRun", true);
                }

                transform.Translate(0, 0, Statu * Time.deltaTime, Space.Self);
            }
            else
            {
                StateMotion = true;
                AngleMotion = true;
                c = Random.Range(0, 2);

            }
        }
        else
        {
            StopAnimation();
            anim.SetBool("ToRest", true);
        }
    }
    /// 
    /// 停止之前的动画行为
    /// 
    void StopAnimation()
    {
        anim.SetBool("ToRun", false);
        anim.SetBool("ToWalk", false);
        anim.SetBool("ToRest", false);
    }
}

你可能感兴趣的:(unity,游戏引擎)