写一段unity2D自动自动寻路的代码
时间: 2023-12-01 22:39:54 浏览: 130
当然可以!以下是一个简单的Unity 2D自动寻路的代码示例:
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoPathfinding : MonoBehaviour
{
public Transform target; // 目标位置
private Rigidbody2D rb;
private Vector2 movement;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
// 计算寻路方向
Vector2 direction = (target.position - transform.position).normalized;
movement = direction;
// 移动角色
rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
}
}
```
在上述代码中,我们使用了`Rigidbody2D`组件来控制角色的移动。`target`变量代表角色要寻找的目标位置。在`Update`方法中,我们计算了角色与目标位置之间的方向,并将其归一化,然后将其赋值给`movement`变量。最后,我们使用`Rigidbody2D`的`MovePosition`方法来移动角色。这样,角色就会自动朝着目标位置寻路。
请注意,这只是一个简单的示例代码,你可以根据实际需求进行修改和扩展。希望对你有所帮助!
阅读全文
相关推荐















