unity简单实现怪物的左右移动功能

时间:2024-10-29 20:15:41
  • [Header("怪物移动速度")]
  • public float speed;
  • [Header("等待时间")]
  • public float waitTime;
  • [Header("移动物体")]
  • public Transform[] movePos;
  • private int i = 0;
  • private bool movingRight = true;
  • private float wait;
  • // Start is called before the first frame update
  • void Start()
  • {
  • wait = waitTime;
  • }
  • // Update is called once per frame
  • void Update()
  • {
  • = Vector2.MoveTowards(, movePos[i].position, speed * Time.deltaTime);
  • //判断物体的位置是否接近边界的地方
  • if (Vector2.Distance(,movePos[i].position)<0.1f)
  • {
  • //如果到达位置,就进行下一个位置的移动
  • if (waitTime > 0)
  • {
  • waitTime -= Time.deltaTime;
  • }
  • else
  • {
  • if (movingRight)
  • {
  • = new Vector3(0, -180, 0);
  • movingRight = false;
  • }
  • else
  • {
  • = new Vector3(0, 0, 0);
  • movingRight = true;
  • }
  • if (i == 0)
  • {
  • i = 1;
  • }
  • else
  • {
  • i = 0;
  • }
  • waitTime = wait;
  • }
  • }
  • }