在初始化中,可以用GameObject.Find找到flag物体。
然后用LookAt可以使得本物品的z轴方向朝向flag物体。
在update中,就可以不断的移动本物体,并且判断本物体和flag物体的距离,若距离大于0.2,则继续移动本物体,若距离小于等于0.2,那么则停止移动。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Remove : MonoBehaviour
{
void Start()
{
GameObject flag = GameObject.Find("flag");
this.transform.LookAt(flag.transform);
}
void Update()
{
GameObject flag = GameObject.Find("flag");
Vector3 p1 = this.transform.position;
Vector3 p2 = flag.transform.position;
Vector3 p0 = p2 - p1;
float d = p0.magnitude;
if (d > 0.2)
{
float speed = 3;
float distance = speed * Time.deltaTime;
this.transform.Translate(0, 0, distance,Space.Self);
}
}
}