image.png
用兩個(gè)碰撞體衅码,場(chǎng)景編輯的時(shí)候記得第二個(gè)trigger collider的觸發(fā)邊界拯刁,與第一個(gè)要分開(kāi)。
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);
}
}