【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如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

使用python制作一款文件粉碎工具

《使用python制作一款文件粉碎工具》这篇文章主要为大家详细介绍了如何使用python制作一款文件粉碎工具,能够有效粉碎密码文件和机密Excel表格等,感兴趣的小伙伴可以了解一下... 文件粉碎工具:适用于粉碎密码文件和机密的escel表格等等,主要作用就是防止 别人用数据恢复大师把你刚删除的机密的文件恢

mybatisplus的逻辑删除过程

《mybatisplus的逻辑删除过程》:本文主要介绍mybatisplus的逻辑删除过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录myBATisplus的逻辑删除1、在配置文件中添加逻辑删除的字段2、在实体类上加上@TableLogic3、业务层正常删除即

Python38个游戏开发库整理汇总

《Python38个游戏开发库整理汇总》文章介绍了多种Python游戏开发库,涵盖2D/3D游戏开发、多人游戏框架及视觉小说引擎,适合不同需求的开发者入门,强调跨平台支持与易用性,并鼓励读者交流反馈以... 目录PyGameCocos2dPySoyPyOgrepygletPanda3DBlenderFife

游戏闪退弹窗提示找不到storm.dll文件怎么办? Stormdll文件损坏修复技巧

《游戏闪退弹窗提示找不到storm.dll文件怎么办?Stormdll文件损坏修复技巧》DLL文件丢失或损坏会导致软件无法正常运行,例如我们在电脑上运行软件或游戏时会得到以下提示:storm.dll... 很多玩家在打开游戏时,突然弹出“找不到storm.dll文件”的提示框,随后游戏直接闪退,这通常是由于

MySQL逻辑删除与唯一索引冲突解决方案

《MySQL逻辑删除与唯一索引冲突解决方案》本文探讨MySQL逻辑删除与唯一索引冲突问题,提出四种解决方案:复合索引+时间戳、修改唯一字段、历史表、业务层校验,推荐方案1和方案3,适用于不同场景,感兴... 目录问题背景问题复现解决方案解决方案1.复合唯一索引 + 时间戳删除字段解决方案2:删除后修改唯一字

springboot项目打jar制作成镜像并指定配置文件位置方式

《springboot项目打jar制作成镜像并指定配置文件位置方式》:本文主要介绍springboot项目打jar制作成镜像并指定配置文件位置方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录一、上传jar到服务器二、编写dockerfile三、新建对应配置文件所存放的数据卷目录四、将配置文

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

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

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

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

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