任务的逻辑及相关脚本的添加,NPC移动的逻辑改动

This commit is contained in:
huyulong 2024-12-13 17:19:27 +08:00
parent 4451817b92
commit e1942ce8f5
8 changed files with 203 additions and 189 deletions

View File

@ -1,94 +1,77 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public enum TaskStatus
public enum TaskState
{
NotAccepted, // 未接受
InProgress, // 进行中
Completed, // 已完成
Failed // 失败
NotStarted, // 未开始
InProgress, // 进行中
Completed, // 已完成
Failed // 失败
}
public class TaskItem : MonoBehaviour
{
public int taskId;
public string taskName;
public TaskStatus status;
public List<int> triggers; // 存储任务触发条件
public int taskId; // 任务ID
public string taskName; // 任务名称
public TaskState state; // 任务状态
public Text taskTxt; // 任务描述文本
public JSONReader jr;
public List<TaskTarget> Targets = new List<TaskTarget>(); // 任务目标1列表
private JSONReader jsonReader; // JSON 数据读取器
public Text tasktxt;
// Start is called before the first frame update
void Start()
{
}
//构造函数
public TaskItem(int id, string name)
public void SetInfo(int id, JSONReader reader)
{
taskId = id;
taskName = name;
status = TaskStatus.NotAccepted;
triggers = new List<int>();
jsonReader = reader;
LoadTaskData();
}
// 设置任务状态
public void SetStatus(TaskStatus newStatus)
private void LoadTaskData()
{
status = newStatus;
}
Task_ info = jsonReader.GetTaskByID(taskId);
taskName = info.Note;
state = TaskState.NotStarted;
private void OnClickButton()
{
}
//初始化任务的属性
public void SetInfo(int id,JSONReader js)
{
taskId = id;
jr = js;
//// 从JSON加载目标
//foreach (var target in info.Targets)
//{
// Targets.Add(new TaskTarget((TargetType)target.TargetType, target.TargetID, target.Description, target.RequiredProgress));
//}
UpdateTxt();
}
//更新Text
void UpdateTxt()
// 更新任务描述文本
public void UpdateTxt()
{
string progressInfo = "";
foreach (var target in Targets)
{
progressInfo += $"{target.Description}: {target.CurrentProgress}/{target.RequiredProgress}\n";
}
Task_ info = jr.GetTaskByID(taskId);
//Debug.Log(info);
tasktxt.text = info.Note;
taskTxt.text = $"{taskName}\n{progressInfo}";
}
// 添加触发条件
public void AddTrigger(int triggerType, string value)
// 更新任务进度
public void UpdateProgress(TargetType targetType, string targetId, int value)
{
triggers.Add(triggerType);
}
TaskTarget target = Targets.Find(t => t.Type == targetType && t.TargetID == targetId);
if (target != null)
{
target.UpdateProgress(value);
UpdateTxt();
// 任务完成时调用的函数
public void OnTaskCompleted()
{
TaskPanel.instance.RemoveTask(taskId);
}
// Update is called once per frame
void Update()
{
// 检查是否所有目标已完成
if (Targets.TrueForAll(t => t.IsCompleted))
{
state = TaskState.Completed;
TaskPanel.instance.RemoveTask(taskId);
}
}
}
}

View File

@ -346,7 +346,24 @@ public class test : MonoBehaviour
wEBScriptListener.SendMessageByte(sendData);
}
public void CreateNpcHandler()
{
NpcCreateRequest data = new NpcCreateRequest();
data.RoomId = "168888";
data.SceneId = "9003";
data.TemplateId = 2;
WSMessage msg = new WSMessage();
msg.Module = "move";
msg.ServiceName = "CreateNpcHandler";
msg.Data = ByteString.CopyFrom(ProtoBufffer.Serialize(data));
byte[] sendData = ProtoBufffer.Serialize(msg);
WSMessage deinfo = ProtoBufffer.DeSerialize<WSMessage>(sendData);
NpcCreateRequest login = ProtoBufffer.DeSerialize<NpcCreateRequest>(deinfo.Data.ToByteArray());
Debug.Log("==========ÏûϢת·¢º¯Êýµ÷ÓÃ");
//BroadcastFrameMsg.FramesFieldNumber
wEBScriptListener.SendMessageByte(sendData);
}
// Start is called before the first frame update
@ -492,7 +509,7 @@ public class test : MonoBehaviour
TaskInfoResponse taskInfoResponse = userJoinResponse.TaskResponse;
if (long.Parse(taskInfoResponse.ToUserId) == userJoinResponse.UserId)//当这个任务是当前玩家的任务时显示任务
{
TaskPanel.instance.SetInfo(int.Parse(taskInfoResponse.TaskId));
//TaskPanel.instance.SetInfo(int.Parse(taskInfoResponse.TaskId));
}
}
@ -533,13 +550,11 @@ public class test : MonoBehaviour
Vector3 position = new Vector3(x, y, z);
NPCController.instance.InitNPC(position, npcData);
}
if(npcData.Type == 2)//npc移动
{
Vector3 v = new Vector3(-float.Parse(npcData.X.ToString()), float.Parse(npcData.Y.ToString()), float.Parse(npcData.Z.ToString()));
foreach(var item in NPCController.instance.npcsList)
foreach(RecuseNpc item in NPCController.instance.npcsList)
{
if(npcData.UserId == item.npcId)
{

View File

@ -8,155 +8,94 @@ using System.Threading.Tasks;
public class TaskPanel : Base
{
public static TaskPanel instance;
public List<int> taskIds = new List<int>();
public Transform contentTrans; // 任务列表容器
public GameObject taskPrefab; // 任务项预制体
public JSONReader JSONReader; // JSON 数据读取类
public Transform contentTrans;
public RectTransform buttonRect; // 按钮 RectTransform
public Button hideBtn; // 隐藏按钮
public GameObject taskPrefab;
private bool isHidden = false; // 是否隐藏状态
public float moveDuration = 0.5f;
public float hidePositionX = 125f;
public float showPositionX = -198f;
public JSONReader JSONReader;
private List<TaskItem> taskItems = new List<TaskItem>(); // 当前显示的任务列表
public Dictionary<int, Language> taskDic = new Dictionary<int, Language>();
public RectTransform buttonRect; // 你的按钮 RectTransform
public Button hideBtn;
private bool isHidden = false; // 用来判断按钮是否已经隐藏
public float moveDuration = 0.5f; // 动画持续时间
public float hidePositionX = 125f; // 隐藏到右边的 X 坐标值,具体值根据屏幕大小调整
public float showPositionX = -198f; // 显示时按钮的 X 坐标值
public List<Button> buttons; // 所有的任务
public Color selectedColor = new Color(0.5f, 0.5f, 1f, 1f); // 紫色
public Color defaultColor = Color.white; // 白色
// Start is called before the first frame update
void Start()
{
instance = this;
hideBtn.onClick.AddListener(OnClickHideButton);
}
//将任务栏收起或显示
// 将任务栏收起或显示
public void OnClickHideButton()
{
// 如果按钮已隐藏,点击后显示
if (isHidden)
{
// 恢复按钮到原位置
buttonRect.DOAnchorPosX(showPositionX, moveDuration).SetEase(Ease.InOutCubic);
hideBtn.transform.Rotate(0, 0, 180f);
isHidden = false; // 更新状态为未隐藏
isHidden = false;
}
else
{
// 隐藏按钮
buttonRect.DOAnchorPosX(hidePositionX, moveDuration).SetEase(Ease.InOutCubic);
hideBtn.transform.Rotate(0, 0, 180f);
isHidden = true; // 更新状态为隐藏
isHidden = true;
}
}
//实例化任务
public async void InitTask()
// 初始化任务列表
public async void InitTask(List<int> taskIds)
{
await DestroyTaskAsync();
for(int i = 0; i < taskIds.Count;i++)
await ClearTaskItems();
foreach (int id in taskIds)
{
GameObject go = GameObject.Instantiate(taskPrefab, contentTrans);
go.transform.name = "Task_" + i;
TaskItem item = go.GetComponent<TaskItem>();
item.SetInfo(taskIds[i], JSONReader);
Button button = go.GetComponent<Button>();
button.onClick.AddListener(() => OnButtonClicked(button));
buttons.Add(button);
AddTask(id);
}
}
// 当点击任务时触发选中
void OnButtonClicked(Button clickedButton)
// 添加新任务
public void AddTask(int taskId)
{
// 遍历所有按钮并重置颜色
foreach (Button button in buttons)
GameObject go = Instantiate(taskPrefab, contentTrans);
TaskItem taskItem = go.GetComponent<TaskItem>();
taskItem.SetInfo(taskId, JSONReader);
taskItems.Add(taskItem);
}
// 更新任务UI
public void UpdateTaskUI(TaskItem taskItem)
{
// 查找对应的UI项更新进度或状态
TaskItem item = taskItems.Find(t => t.taskId == taskItem.taskId);
if (item != null)
{
Image buttonImage = button.GetComponent<Image>();
if (button == clickedButton)
{
// 设置被点击按钮的颜色为紫色
buttonImage.color = selectedColor;
}
else
{
// 重置其他按钮为白色
buttonImage.color = defaultColor;
}
item.UpdateTxt();
}
}
public async Task DestroyTaskAsync()
// 移除任务
public void RemoveTask(int taskId)
{
DeleteAllChildObjects();
await Task.Delay(10);
TaskItem taskItem = taskItems.Find(t => t.taskId == taskId);
if (taskItem != null)
{
taskItems.Remove(taskItem);
Destroy(taskItem.gameObject);
}
}
//这里是在加入新任务时需要更新显示前的删除
public void DeleteAllChildObjects()
// 清空任务
public async Task ClearTaskItems()
{
// 遍历所有子物体并删除
foreach (Transform child in contentTrans)
{
Destroy(child.gameObject);
}
//清除按钮
buttons.Clear();
}
public void SetInfo(int id)
{
taskIds.Add(id);
InitTask();
}
public void RemoveTask(int taskId)
{
// 通过 taskId 找到对应的任务按钮并移除
Button taskButton = buttons.Find(button => button.name == "Task_" + taskId);
if (taskButton != null)
{
buttons.Remove(taskButton);
Destroy(taskButton.gameObject); // 删除该任务按钮
// 如果任务完成后有其他特定处理,比如从任务 ID 列表中移除任务,也可以在这里做
taskIds.Remove(taskId);
}
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.J))
{
SetInfo(11001);
}
taskItems.Clear();
await Task.Delay(10);
}
}

View File

@ -21186,6 +21186,17 @@ Transform:
m_CorrespondingSourceObject: {fileID: 422818, guid: 1dda2c9777184f647a8b212110daac24, type: 3}
m_PrefabInstance: {fileID: 1491834350}
m_PrefabAsset: {fileID: 0}
--- !u!114 &1493242969 stripped
MonoBehaviour:
m_CorrespondingSourceObject: {fileID: 410985242629440749, guid: 9263a339010a182478c1a809e3f8ddf1, type: 3}
m_PrefabInstance: {fileID: 410985242984056442}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3}
m_Name:
m_EditorClassIdentifier:
--- !u!64 &1498852880
MeshCollider:
m_ObjectHideFlags: 0
@ -27387,6 +27398,10 @@ PrefabInstance:
propertyPath: target
value:
objectReference: {fileID: 1469954942}
- target: {fileID: 5519024520137767209, guid: 4bc999dc543a61148a0ba3bb1dd45a4d, type: 3}
propertyPath: recusebtn
value:
objectReference: {fileID: 1493242969}
- target: {fileID: 8479287258615548071, guid: 4bc999dc543a61148a0ba3bb1dd45a4d, type: 3}
propertyPath: m_RootOrder
value: 4

View File

@ -0,0 +1,45 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum TargetType
{
KillEnemy, // 击杀敌人
ReachArea, // 到达区域
CollectItem, // 收集物品
InteractNPC // 与NPC互动
}
public class TaskTarget:MonoBehaviour
{
public TargetType Type { get; private set; } // 目标类型
public string TargetID { get; private set; } // 目标ID
public string Description { get; private set; } // 目标描述
public int CurrentProgress { get; private set; } // 当前进度
public int RequiredProgress { get; private set; } // 目标完成所需进度
public bool IsCompleted => CurrentProgress >= RequiredProgress; // 是否完成
public TaskTarget(TargetType type, string targetId, string description, int requiredProgress)
{
Type = type;
TargetID = targetId;
Description = description;
RequiredProgress = requiredProgress;
CurrentProgress = 0;
}
// 更新目标进度
public void UpdateProgress(int amount)
{
if (IsCompleted) return;
CurrentProgress += amount;
Console.WriteLine($"目标 {Description} 进度: {CurrentProgress}/{RequiredProgress}");
if (IsCompleted)
{
Console.WriteLine($"目标 {Description} 已完成");
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 52ac3e3a7633b8345bd5ff5ac681d602
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -22,6 +22,7 @@ public class TestButton : MonoBehaviour
public void JoinRoom()
{
test.JoinRoom();
test.CreateNpcHandler();
joinroomBtn.gameObject.SetActive(false);
}

View File

@ -13,13 +13,15 @@ public enum Npcstate
public class RecuseNpc : MonoBehaviour
{
private NavMeshAgent navMeshAgent;//navmesh组件
public string npcId;
public static RecuseNpc instance;
private Button recusebtn;
public Button recusebtn;
private bool statebool = false;
@ -32,13 +34,13 @@ public class RecuseNpc : MonoBehaviour
public Vector3 currentTarget;
// <EFBFBD>洢Ŀ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>List
// 存目的地的list
public List<Vector3> targetPoints = new List<Vector3>();
private void Awake()
{
instance = this;
recusebtn = GameObject.Find("Canvas/Recuse").GetComponent<Button>();
//recusebtn = GameObject.Find("Canvas/Recuse").GetComponent<Button>();
anim = this.GetComponent<Animator>();
navMeshAgent = GetComponent<NavMeshAgent>();
@ -51,7 +53,7 @@ public class RecuseNpc : MonoBehaviour
}
private void OnTriggerEnter(Collider other)//ͨ<><CDA8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>õ<EFBFBD><C3B5><EFBFBD>Ӧ<EFBFBD>ľ<EFBFBD>Ԯ<EFBFBD><D4AE><EFBFBD><EFBFBD>Ա<EFBFBD><D4B1>ǩ<EFBFBD><C7A9><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD>ֳ<EFBFBD>UI
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
recusebtn.gameObject.SetActive(true);
@ -69,34 +71,41 @@ public class RecuseNpc : MonoBehaviour
npcId = id;
}
//<EFBFBD><EFBFBD><EFBFBD><EFBFBD>NPC<EFBFBD><EFBFBD>״̬
public void Setnpcstate()//<2F><><EFBFBD><EFBFBD><EFBFBD>Ԯ<EFBFBD><D4AE>ťִ<C5A5><D6B4><EFBFBD><EFBFBD><EAB6AF><EFBFBD><EFBFBD>԰<EFBFBD>ť<EFBFBD><C5A5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//npc状态
public void Setnpcstate()
{
movebool = true;
nstate = Npcstate.run;
nstate = Npcstate.idle;
recusebtn.gameObject.SetActive(false);
Debug.Log("Setnpcstate<74><65><EFBFBD><EFBFBD>");
Debug.Log( npcId + "被救");
}
//<EFBFBD><EFBFBD><EFBFBD><EFBFBD>NPC<EFBFBD><EFBFBD>Ŀ<EFBFBD><EFBFBD><EFBFBD>
//添加npc的目的地到list中
public void SetNpcDes(Vector3 tar)
{
//target.position = tar;
targetPoints.Add(tar); // <20><>Ŀ<EFBFBD><C4BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ӵ<EFBFBD><D3B5>б<EFBFBD><D0B1><EFBFBD>
targetPoints.Add(tar);
}
private void Update()
{
if (targetPoints.Count > 0) // 确保列表中有目标点
{
currentTarget = targetPoints[0]; // 获取当前的目标点
nstate = Npcstate.run;
movebool = true;
// 判断是否到达目标点
if (movebool && navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance)
{
Debug.Log("到达目标点");
// 设置NPC状态
nstate = Npcstate.idle;
movebool = false;
// 达到目标后,从列表中移除该目标点
if (targetPoints.Count > 1)
{
@ -106,10 +115,6 @@ public class RecuseNpc : MonoBehaviour
{
targetPoints.Clear(); // 清空列表
}
// 设置NPC状态
nstate = Npcstate.idle;
movebool = false;
}
}