【UnityRPG游戏制作】NPC交互逻辑、动玩法

2024-05-04 05:44

本文主要是介绍【UnityRPG游戏制作】NPC交互逻辑、动玩法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述


👨‍💻个人主页:@元宇宙-秩沅

👨‍💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅!

👨‍💻 本文由 秩沅 原创
👨‍💻 收录于专栏:就业宝典

🅰️推荐专栏

⭐-软件设计师高频考点大全



文章目录

    • 前言
    • 🎶(==二==) NPC逻辑相关
    • (==1==) NPC范围检测
    • (==2==) NPC动画添加
    • (==3==) NPC和玩家的攻击受伤交互(事件中心)
    • (==4==) NPC的受伤特效添加
    • (==5==) NPC的死亡特效添加
    • 🅰️


前言


🎶( NPC逻辑相关



1 NPC范围检测


在这里插入图片描述

在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;//-------------------------------
//-------功能: NPC交互脚本
//-------创建者:         -------
//------------------------------public class NPCContorller : MonoBehaviour
{public PlayerContorller playerCtrl;//范围检测private void OnTriggerEnter(Collider other){playerCtrl.isNearby  = true;}private void OnTriggerExit(Collider other){playerCtrl.isNearby = false;}
}

2 NPC动画添加


在这里插入图片描述
请添加图片描述


3 NPC和玩家的攻击受伤交互(事件中心)


  • EnemyController 敌人
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;//-------------------------------
//-------功能:  敌人控制器
//-------创建者:         -------
//------------------------------public class EnemyController : MonoBehaviour
{public GameObject player;   //对标玩家public Animator animator;   //对标动画机public GameObject enemyNPC; //对标敌人public int hp;              //血量public Image hpSlider;      //血条private int attack = 10;    //敌人的攻击力public float CD_skill ;         //技能冷却时间private void Start(){enemyNPC = transform.GetChild(0).gameObject;animator = enemyNPC.GetComponent<Animator>();SendEvent();  //发送相关事件}private void Update(){CD_skill += Time.deltaTime; //CD一直在累加}/// <summary>/// 发送事件/// </summary>private void SendEvent(){//传递怪兽攻击事件(也是玩家受伤时)EventCenter.GetInstance().AddEventListener(PureNotification.PLAYER_INJURY, (int attack) =>{animator.SetBool("attack",true ); //攻击动画激活     });//传递怪兽受伤事件(玩家攻击时)EventCenter.GetInstance().AddEventListener(PureNotification.PLAYER_ATTRACK, ( ) =>{ animator.SetBool("hurt", true);  //受伤动画激活});//传递怪兽死亡事件EventCenter.GetInstance().AddEventListener(PureNotification.NPC_Died , () =>{      animator.SetBool("died", true);  //死亡动画激活gameObject.SetActive(false);     //给物体失活//暴金币});}//碰撞检测private void OnCollisionStay(Collision collision){if (collision.gameObject.tag == "Player") //检测到如果是玩家的标签{if(CD_skill > 2f)  //攻击动画的冷却时间{Debug.Log("怪物即将攻击");CD_skill = 0;//触发攻击事件EventCenter.GetInstance().EventTrigger(PureNotification.PLAYER_INJURY, Attack());}    }}/// <summary>/// 传递攻击力/// </summary>/// <returns></returns>public  int  Attack(){return attack;}//碰撞检测private void OnCollisionExit(Collision collision){if (collision.gameObject.tag == "Player") //检测到如果是玩家的标签{animator.SetBool("attack", false);       collision.gameObject.GetComponent<PlayerContorller>().animator .SetBool("hurt", false);}}//范围触发检测private void OnTriggerStay(Collider other){if(other.tag == "Player")  //检测到如果是玩家的标签{//让怪物看向玩家transform.LookAt(other.gameObject.transform.position);//并且向其移动transform.Translate(Vector3.forward * 1 * Time.deltaTime);}}}
  • PlayerContorller玩家
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
using static UnityEditor.Experimental.GraphView.GraphView;//-------------------------------
//-------功能: 玩家控制器
//-------创建者:        
//------------------------------public class PlayerContorller : MonoBehaviour
{//-----------------------------------------//---------------成员变量区-----------------//-----------------------------------------public float  speed = 1;         //速度倍量public Rigidbody rigidbody;      //刚体组建的声明public Animator  animator;       //动画控制器声明public GameObject[] playersitem; //角色数组声明public bool isNearby = false;    //人物是否在附近public float CD_skill ;         //技能冷却时间public int curWeaponNum;        //拥有武器数public int attack ;             //攻击力public int defence ;            //防御力//-----------------------------------------//-----------------------------------------void Start(){rigidbody = GetComponent<Rigidbody>();SendEvent();//发送事件给事件中心}void Update(){CD_skill += Time.deltaTime;       //CD一直在累加InputMonitoring();}void FixedUpdate(){Move();}/// <summary>/// 更换角色[数组]/// </summary>/// <param name="value"></param>public void ChangePlayers(int value){for (int i = 0; i < playersitem.Length; i++){if (i == value){animator = playersitem[i].GetComponent<Animator>();playersitem[i].SetActive(true);}else{playersitem[i].SetActive(false);}}}/// <summary>///玩家移动相关/// </summary>private void Move(){//速度大小float horizontal = Input.GetAxis("Horizontal");float vertical = Input.GetAxis("Vertical");if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0){//方向Vector3 dirction = new Vector3(horizontal, 0, vertical);//让角色的看向与移动方向保持一致transform.rotation = Quaternion.LookRotation(dirction);rigidbody.MovePosition(transform.position + dirction * speed * Time.deltaTime);animator.SetBool("walk", true);//加速奔跑if (Input.GetKey(KeyCode.LeftShift) ){animator.SetBool("run", true);animator.SetBool("walk", true);                rigidbody.MovePosition(transform.position + dirction * speed*3 * Time.deltaTime);}else {animator.SetBool("run", false);;animator.SetBool("walk", true);}            }else {animator.SetBool("walk", false);}}/// <summary>/// 键盘监听相关/// </summary>public void InputMonitoring(){//人物角色切换if (Input.GetKeyDown(KeyCode.Alpha1)){ChangePlayers(0);}if (Input.GetKeyDown(KeyCode.Alpha2)){ChangePlayers(1);}if (Input.GetKeyDown(KeyCode.Alpha3)){ChangePlayers(2);}//范围检测弹出和NPC的对话框if (isNearby && Input.GetKeyDown(KeyCode.F)){          //发送通知打开面板GameFacade.Instance.SendNotification(PureNotification.SHOW_PANEL, "NPCTipPanel");}//打开背包面板if ( Input.GetKeyDown(KeyCode.Tab)){//发送通知打开面板GameFacade.Instance.SendNotification(PureNotification.SHOW_PANEL, "BackpackPanel");}//打开角色面板if ( Input.GetKeyDown(KeyCode.C)){//发送通知打开面板GameFacade.Instance.SendNotification(PureNotification.SHOW_PANEL, "RolePanel");}//攻击监听if (Input.GetKeyDown(KeyCode.Space) && CD_skill >= 1.0f) //按下空格键攻击,并且技能恢复冷却{if (curWeaponNum > 0)  //有武器时的技能相关{animator.speed = 2;animator.SetTrigger("Attack2");}else                  //没有武器时的技能相关{animator.speed = 1;animator.SetTrigger("Attack1");}CD_skill = 0;#region//技能开始冷却//    audioSource.clip = Resources.Load<AudioClip>("music/01");//    audioSource.Play();//    cd_Put = 0;//var enemys = GameObject.FindGameObjectsWithTag("enemy");//foreach (GameObject enemy in enemys)//{//    if (enemy != null)//    {//        if (Vector3.Distance(enemy.transform.position, this.transform.position) <= 5)//        {//            enemy.transform.GetComponent<_03EnemyCtrl>().SubSelf(50);//        }//    }//}//var bosses = GameObject.FindGameObjectsWithTag("boss");//foreach (GameObject boss in bosses)//{//    if (boss != null)//    {//        if (Vector3.Distance(boss.transform.position, this.transform.position) <= 5)//        {//            boss.transform.GetComponent<boss>().SubHP();//        }//    }//}#endregion}//if (Input.GetKeyDown(KeyCode.E))//{//    changeWeapon = !changeWeapon;//}//if (Input.GetKeyDown(KeyCode.Q))//{//    AddHP();//    diaPanel.USeHP();//}//if (enemys != null && enemys.transform.childCount <= 0 && key != null)//{//    key.gameObject.SetActive(true);//}}/// <summary>/// 发送事件/// </summary>private void SendEvent(){//传递玩家攻击事件EventCenter.GetInstance().AddEventListener(PureNotification.PLAYER_ATTRACK, () =>{});//传递玩家受伤事件(怪物攻击时)EventCenter.GetInstance().AddEventListener(PureNotification.PLAYER_INJURY , (int attack) =>{animator.SetBool("hurt", true);Debug.Log(attack + "掉血了");                                 });   }
}

4 NPC的受伤特效添加


请添加图片描述

    /// <summary>/// 碰撞检测/// </summary>/// <param name="collision"></param>private void OnCollisionStay(Collision collision){//若碰到敌人,并进行攻击if (collision.gameObject.tag == "enemy" && Input.GetKeyDown(KeyCode.Space)){Debug.Log("造成伤害");enemyController = collision.gameObject.GetComponent<EnemyController>();//触发攻击事件enemyController.animator.SetBool("hurt", true);  //怪物受伤动画激活enemyController.transform.GetChild(2).GetChild(0).GetComponent<ParticleSystem>().Play();enemyController.hp -= attack;//减少血量enemyController. hpSlider.fillAmount = (enemyController.hp / 100.0f);if (enemyController.hp <= 0) //死亡判断{collision.transform.GetChild(0).GetComponent<Animator>() .SetBool("died", true);  //死亡动画激活//播放动画collision.transform.GetChild(2).GetChild(0).GetComponent<ParticleSystem>().Play();collision. gameObject.SetActive(false); //将敌人失活//暴钻石(实例化)Instantiate(Resources.Load<GameObject>("Perfab/Prop/damon"), collision.transform.position , Quaternion.identity);Destroy(collision.gameObject, 3);}}}

5 NPC的死亡特效添加


请添加图片描述

   /// <summary>/// 碰撞检测/// </summary>/// <param name="collision"></param>private void OnCollisionStay(Collision collision){//若碰到敌人,并进行攻击if (collision.gameObject.tag == "enemy" && Input.GetKeyDown(KeyCode.Space)){Debug.Log("造成伤害");enemyController = collision.gameObject.GetComponent<EnemyController>();//触发攻击事件enemyController.animator.SetBool("hurt", true);  //怪物受伤动画激活enemyController.transform.GetChild(2).GetChild(0).GetComponent<ParticleSystem>().Play();enemyController.hp -= attack;//减少血量enemyController. hpSlider.fillAmount = (enemyController.hp / 100.0f);if (enemyController.hp <= 0) //死亡判断{collision.transform.GetChild(0).GetComponent<Animator>() .SetBool("died", true);  //死亡动画激活//播放动画collision.transform.GetChild(2).GetChild(0).GetComponent<ParticleSystem>().Play();collision. gameObject.SetActive(false); //将敌人失活//暴钻石(实例化)Instantiate(Resources.Load<GameObject>("Perfab/Prop/damon"), collision.transform.position , Quaternion.identity);Destroy(collision.gameObject, 3);}}}

🅰️


⭐【Unityc#专题篇】之c#进阶篇】

⭐【Unityc#专题篇】之c#核心篇】

⭐【Unityc#专题篇】之c#基础篇】

⭐【Unity-c#专题篇】之c#入门篇】

【Unityc#专题篇】—进阶章题单实践练习

⭐【Unityc#专题篇】—基础章题单实践练习

【Unityc#专题篇】—核心章题单实践练习


你们的点赞👍 收藏⭐ 留言📝 关注✅是我持续创作,输出优质内容的最大动力!


在这里插入图片描述


这篇关于【UnityRPG游戏制作】NPC交互逻辑、动玩法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/958441

相关文章

Python与Java交互出现乱码的问题解决

《Python与Java交互出现乱码的问题解决》在现代软件开发中,跨语言系统的集成已经成为日常工作的一部分,特别是当Python和Java之间进行交互时,编码问题往往会成为导致数据传输错误、乱码以及难... 目录背景:为什么会出现乱码问题产生的场景解决方案:确保统一的UTF-8编码完整代码示例总结在现代软件

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言

Java逻辑运算符之&&、|| 与&、 |的区别及应用

《Java逻辑运算符之&&、||与&、|的区别及应用》:本文主要介绍Java逻辑运算符之&&、||与&、|的区别及应用的相关资料,分别是&&、||与&、|,并探讨了它们在不同应用场景中... 目录前言一、基本概念与运算符介绍二、短路与与非短路与:&& 与 & 的区别1. &&:短路与(AND)2. &:非短

基于WinForm+Halcon实现图像缩放与交互功能

《基于WinForm+Halcon实现图像缩放与交互功能》本文主要讲述在WinForm中结合Halcon实现图像缩放、平移及实时显示灰度值等交互功能,包括初始化窗口的不同方式,以及通过特定事件添加相应... 目录前言初始化窗口添加图像缩放功能添加图像平移功能添加实时显示灰度值功能示例代码总结最后前言本文将

使用Python制作一个PDF批量加密工具

《使用Python制作一个PDF批量加密工具》PDF批量加密‌是一种保护PDF文件安全性的方法,通过为多个PDF文件设置相同的密码,防止未经授权的用户访问这些文件,下面我们来看看如何使用Python制... 目录1.简介2.运行效果3.相关源码1.简介一个python写的PDF批量加密工具。PDF批量加密

Python开发围棋游戏的实例代码(实现全部功能)

《Python开发围棋游戏的实例代码(实现全部功能)》围棋是一种古老而复杂的策略棋类游戏,起源于中国,已有超过2500年的历史,本文介绍了如何用Python开发一个简单的围棋游戏,实例代码涵盖了游戏的... 目录1. 围棋游戏概述1.1 游戏规则1.2 游戏设计思路2. 环境准备3. 创建棋盘3.1 棋盘类