72 lines
1.7 KiB
C#
72 lines
1.7 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class Snailmove : MonoBehaviour
|
|
{
|
|
private float moveTimer = 0f; // 定时器
|
|
private float moveSpeed = 10f; // 移动速度
|
|
public Vector3 moveDirection; // 当前移动方向
|
|
public Animator animator; // Animator引用
|
|
|
|
private bool isMoving = false; // 是否在移动
|
|
public long id;
|
|
public Image Image;
|
|
|
|
private void Start()
|
|
{
|
|
|
|
moveDirection=Vector3.right;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
// 每秒更新定时器
|
|
moveTimer += Time.deltaTime;
|
|
|
|
// 每3秒改变一次方向
|
|
if (moveTimer >= 10f)
|
|
{
|
|
ChangeDirection();
|
|
moveTimer = 0f;
|
|
}
|
|
|
|
// 移动物体
|
|
transform.Translate(moveDirection * moveSpeed * Time.deltaTime);
|
|
if (transform.localPosition.x <= -600 || transform.localPosition.x >= 600)
|
|
{
|
|
transform.localPosition = new Vector3(0, transform.localPosition.y, transform.localPosition.z);
|
|
}
|
|
|
|
}
|
|
|
|
// 随机改变移动方向
|
|
private void ChangeDirection()
|
|
{
|
|
|
|
int randomDirection = Random.Range(0, 3);
|
|
if (randomDirection <= 1)
|
|
{
|
|
moveDirection = Vector3.right;
|
|
Image.transform.rotation = Quaternion.Euler(0, 0, 0);
|
|
animator.SetBool("move",true);
|
|
}
|
|
if(randomDirection <= 2&& randomDirection > 1)
|
|
{
|
|
moveDirection = Vector3.left;
|
|
Image.transform.rotation = Quaternion.Euler(0, 180, 0);
|
|
animator.SetBool("move", true);
|
|
}
|
|
else
|
|
{
|
|
moveDirection = Vector3.zero;
|
|
animator.SetBool("move", false);
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|