使用方法:
挂载到需要移动到物体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
//定义单例,使外部可访问
public static Move instance { get; set; }
//目标位置
public Vector3 destination;
//是否移动
public bool movingstatus=false;
//等待时间
public float waittime = 0f;
//计时器
public float timer = 0;
//移动时长
public float duration = 0.1f;
//最大误差
public Vector3 deviation;
private Vector3 velocity = Vector3.zero;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
if(movingstatus==true)
{
//计时
timer += Time.deltaTime;
//误差
deviation = destination - gameObject.transform.position;
//超过时间即停止
if (timer > (waittime + duration)&& Mathf.Abs(deviation.x)<0.01 && Mathf.Abs(deviation.y)< 0.01 && Mathf.Abs(deviation.z) < 0.01)
{
//位置校正
gameObject.transform.position = destination;
//初始化
timer = 0;
movingstatus=false;
}
else
{
gameObject.transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, duration);
}
}
}
}
其他脚本调用
tile.GetComponent<Move>().destination = position;
tile.GetComponent<Move>().movingstatus = true;
注意事项:
只有在激活状态下脚本才能生效,未激活的物体上挂载的脚本是不工作的,若不注意将引发严重的bug