先把制作好动画帧表格导出来,我的是32*32像素的,按下面两张图把参数修改一下,并且裁剪出四张图来,把第一张图作为一个游戏对象
再准备好一个EnemyBlueBug的C#脚本,我们就来编写代码,设计好随机移动,以及能移动的范围。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBlueBug : Enemy
{
public float moveSpeed;
public float startTime;
public float waitTime;
public Transform leftPos;
public Transform rightPos;
public Transform movePos;
public void Start()
{
base.Start();
waitTime = startTime;
movePos.position = GetRandomPos();
}
// Update is called once per frame
public void Update()
{
base.Update();
transform.position = Vector2.MoveTowards
(transform.position, movePos.position, moveSpeed * Time.deltaTime);
if(Vector2.Distance(transform.position, movePos.position) < 0.05f)
if (waitTime <= 0)
{
movePos.position = GetRandomPos();
}
else
{
waitTime -= Time.deltaTime;
}
}
Vector2 GetRandomPos()
{
Vector2 randomPosition = new Vector2(Random.Range(leftPos.position.x, rightPos.position.x),
Random.Range(leftPos.position.y, rightPos.position.y));
return randomPosition;
}
}
注意此处的Move Pos是必须要填写的,可以先给一个空对象然后Reset一下,反正游戏开始的第一帧就会赋予它一个随机的坐标。速度和等待时间要根据实际来填写
然而运动到到达的位置它不会翻转,这个问题我水一篇文章,下一篇再讲好吧。
介绍一下 随机的方法: Vector2 randomPosition = new Vector2(Random.Range(leftPos.position.x, rightPos.position.x),
Random.Range(leftPos.position.y, rightPos.position.y));
定点移动: Vector2.MoveTowards
(transform.position, movePos.position, moveSpeed * Time.deltaTime);、
计时器:if (waitTime <= 0)
{
}
else
{
waitTime -= Time.deltaTime;
}