写一个Unity 2D 寻路算法( 平台 跳跃)
时间: 2023-06-11 14:08:03 浏览: 208
以下是一个简单的Unity 2D寻路算法示例,用于平台跳跃游戏:
1. 创建一个空物体作为寻路管理器,将以下脚本附加到该物体上:
```csharp
using UnityEngine;
using System.Collections.Generic;
public class PathfindingManager : MonoBehaviour {
private List<Vector2> path = new List<Vector2>();
public List<Vector2> FindPath(Vector2 start, Vector2 target) {
// 使用A星算法来查找路径
// ...
return path;
}
}
```
2. 创建一个角色并附加以下脚本:
```csharp
using UnityEngine;
using System.Collections.Generic;
public class CharacterController2D : MonoBehaviour {
public float speed = 5.0f;
public float jumpForce = 500.0f;
private Rigidbody2D rigidBody;
private bool isGrounded = false;
private PathfindingManager pathfindingManager;
private List<Vector2> currentPath;
private int currentPathIndex = 0;
void Start() {
rigidBody = GetComponent<Rigidbody2D>();
pathfindingManager = FindObjectOfType<PathfindingManager>();
}
void Update() {
// 移动
float horizontal = Input.GetAxis("Horizontal");
rigidBody.velocity = new Vector2(horizontal * speed, rigidBody.velocity.y);
// 跳跃
if (Input.GetKeyDown(KeyCode.Space) && isGrounded) {
rigidBody.AddForce(new Vector2(0, jumpForce));
isGrounded = false;
}
// 跟随路径
if (currentPath != null && currentPathIndex < currentPath.Count) {
Vector2 target = currentPath[currentPathIndex];
float distance = Vector2.Distance(transform.position, target);
if (distance < 0.1f) {
currentPathIndex++;
} else {
Vector2 direction = target - (Vector2)transform.position;
rigidBody.velocity = new Vector2(direction.normalized.x * speed, rigidBody.velocity.y);
}
}
}
void OnCollisionEnter2D(Collision2D other) {
// 判断是否着陆
if (other.gameObject.layer == LayerMask.NameToLayer("Ground")) {
isGrounded = true;
}
}
void OnTriggerEnter2D(Collider2D other) {
// 当角色进入触发器时,重新计算路径
if (other.gameObject.layer == LayerMask.NameToLayer("PathfindingTarget")) {
Vector2 target = other.gameObject.transform.position;
currentPath = pathfindingManager.FindPath(transform.position, target);
currentPathIndex = 0;
}
}
}
```
3. 创建一个地图,包括地面和路径目标。地面需要标记为“Ground”层,路径目标需要标记为“PathfindingTarget”层。
现在,当角色进入路径目标的触发器时,路径将被重新计算,并且角色将沿着路径移动。注意,这只是一个简单的示例,你需要根据你的游戏逻辑和地图设计进行修改和扩展。
阅读全文