Unity-AI(Sprite随机运动)

因为我们在制作界面时大多数都是有固定的移动的路线,但是有的时候需要做一些不规则的运动,这时我们希望越智能越好,那么这里我借鉴一下别人的博客来进行一些更细节的说明。

首先我们先将图片的Texture Type改为Sprite,然后创建一个RawImage,将图片挂上去,实现的效果如下:

我对代码进行了详细的注释:

using UnityEngine;
using System.Collections;
public class AIRandMove : MonoBehaviour
{
    float stopTime;//暂停时间
    float moveTime;//移动时间
    float vel_x, vel_y, vel_z;//速度
    /// <summary>
    /// 最大、最小飞行界限
    /// </summary>
    float maxPos_x = 500;
    float maxPos_y = 300;
    float minPos_x = -500;
    float minPos_y = -300;   
    float timeCounter1;//移动的计时器
    float timeCounter2;//暂停的计时器
    void Start()
    {
        Change();
    }
    // Update is called once per frame
    void Update()
    {
        timeCounter1 += Time.deltaTime;
        //如果移动的计时器小于移动时间,则进行移动,否则暂停计时器累加,当暂停计时器大于暂停时间时,重置
        if (timeCounter1 < moveTime)
        {
            transform.Translate(vel_x, vel_y, 0, Space.Self);
        }
        else
        {
            timeCounter2 += Time.deltaTime;
            if (timeCounter2 > stopTime)
            {
                Change();
                timeCounter1 = 0;
                timeCounter2 = 0;
            }
        }
        Check();
    }
    //对参数赋值
    void Change()
    {
        stopTime = Random.Range(1, 5);
        moveTime = Random.Range(1, 20);
        vel_x = Random.Range(1, 10);
        vel_y = Random.Range(1, 10);
    }
    //判断是否达到边界,达到边界则将速度改为负的
    void Check()
    {
        //如果到达预设的界限位置值,调换速度方向并让它当前的坐标位置等于这个临界边的位置值
        if (transform.localPosition.x > maxPos_x)
        {
            vel_x = -vel_x;
            transform.localPosition = new Vector3(maxPos_x, transform.localPosition.y, 0);
        }
        if (transform.localPosition.x < minPos_x)
        {
            vel_x = -vel_x;
            transform.localPosition = new Vector3(minPos_x, transform.localPosition.y, 0);
        }
        if (transform.localPosition.y > maxPos_y)
        {
            vel_y = -vel_y;
            transform.localPosition = new Vector3(transform.localPosition.x, maxPos_y, 0);
        }
        if (transform.localPosition.y < minPos_y)
        {
            vel_y = -vel_y;
            transform.localPosition = new Vector3(transform.localPosition.x, minPos_y, 0);
        }
    }


}

原创:http://blog.csdn.net/zhangxiao13627093203/article/details/47444623

猜你喜欢

转载自blog.csdn.net/caojianhua1993/article/details/52705860