用两个碰撞体,场景编辑的时候记得第二个trigger collider的触发边界,与第一个要分开。
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
collision.gameObject.transform.SetParent(transform);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
collision.gameObject.transform.SetParent(null);
}
}
public class WaypointFollower : MonoBehaviour
{
[SerializeField] private GameObject[] waypoints;
private int currentWaypointIndex = 0;
[SerializeField] private float speed = 2f;
// Update is called once per frame
void Update()
{
if (Vector2.Distance(waypoints[currentWaypointIndex].transform.position, transform.position) < .1f)
{
currentWaypointIndex++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
transform.position = Vector2.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, Time.deltaTime * speed);
}
}