【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#专题篇】—核心章题单实践练习


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


在这里插入图片描述


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

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

git学习指南

文章目录 一.版本控制1.认识版本控制2.版本控制功能3.集中式版本控制4.分布式版本控制 二.Git的环境安装搭建1.Git的安装2.Git配置分类3.Git配置选项 三.Git初始化本地仓库1. git init/git clone-获取Git仓库2. 本地仓库文件的划分3. git status-检测文件的状态4. git add-文件…

[XYCTF新生赛]-PWN:fmt解析(scanf格式化字符串漏洞,任意地址写)

查看保护 查看ida 这里没什么好说的 完整exp&#xff1a; from pwn import* context(log_leveldebug) #pprocess(./fmt) premote(gz.imxbt.cn,20975) backdoor0x4012BEp.recvuntil(bgift: ) printf_addrint(p.recv(14),16) print(hex(printf_addr)) libcELF(./libc-2.31.so) …

java 学习二

java字面量 java变量 注意事项 十进制转二进制 计算机中表示数据的最小单元 java中的数据类型 java中的类型转换 表达式的自动类型转换 强制类型转换

大气官网(1):家居家电,海量案例来袭。

设计一款大气的家居家电官网&#xff0c;可以考虑以下几个方面&#xff1a; 色彩选择&#xff1a;选择适合家居家电风格的色彩搭配。可以选择温暖的中性色调&#xff0c;如米白色、灰色和棕色&#xff0c;以增加页面的大气感和舒适感。图片展示&#xff1a;使用高质量的图片展…

一加12/11/10/Ace2/Ace3手机上锁回锁BL无限重启黑屏9008模式救砖

一加12/11/10/Ace2/Ace3手机官方都支持解锁BL&#xff0c;搞机的用户也比较多&#xff0c;相对于其他品牌来说&#xff0c;并没有做出限制&#xff0c;这也可能是搞机党最后的救命稻草。而厌倦了root搞机的用户&#xff0c;就习惯性回锁BL&#xff0c;希望彻底变回官方原来的样…

Redis__三大日志

文章目录 &#x1f60a; 作者&#xff1a;Lion J &#x1f496; 主页&#xff1a; https://blog.csdn.net/weixin_69252724 &#x1f389; 主题&#xff1a;Redis__三大日志 ⏱️ 创作时间&#xff1a;2024年04月30日 ———————————————— 对于MySQL来说, 有…

39 死锁

目录 1.死锁 2.线程同步 3.条件变量 4.案例 死锁 概念 死锁是指在一组进程中的各个进程均占有不会释放的资源&#xff0c;但因互相申请被其他进程所占用不会释放的资源而处于的一种永久等待状态 四个必要条件 互斥条件&#xff1a;一个资源每次只能被一个执行流使用 请求…

LeetCode题练习与总结:柱状图中最大的矩形--84

一、题目描述 给定 n 个非负整数&#xff0c;用来表示柱状图中各个柱子的高度。每个柱子彼此相邻&#xff0c;且宽度为 1 。 求在该柱状图中&#xff0c;能够勾勒出来的矩形的最大面积。 示例 1: 输入&#xff1a;heights [2,1,5,6,2,3] 输出&#xff1a;10 解释&#xff1a…

硬盘选购指南

转载请注明出处&#xff01; author karrysmile date 2024年5月3日19:10:52 结论 先给用途分类和价格表 前置知识 没有不好的品牌&#xff0c;只有不好的系列。不用认准哪个品牌就不好&#xff0c;认准口碑好&#xff0c;稳定性好的系列买。&#xff08;杂牌别买&#xff0…

82、动态规划-杨辉三角

思路&#xff1a; 本题其实很容易看出来&#xff0c;首尾都是1&#xff0c;然后第2个元素就是上一行的第一个元素和第二个元素之和。依次类推。可以得出结论&#xff1a;dp[i][j]dp[i-1][j-1]dp[i-1][j],当然要去掉首尾元素。代码如下&#xff1a; public static List<List&…

AtCoder Beginner Contest 351 C题

C - Merge the balls Time Limit: 2 sec / Memory Limit: 1024 MB Score 250 points Problem Statement You have an empty sequence and &#x1d441;N balls. The size of the &#x1d456;i-th ball (1≤&#x1d456;≤&#x1d441;) is ​2^A[i] You will perform…

内网安全-代理Socks协议路由不出网后渗透通讯CS-MSF控制上线简单总结

我这里只记录原理&#xff0c;具体操作看文章后半段或者这篇文章内网渗透—代理Socks协议、路由不出网、后渗透通讯、CS-MSF控制上线_内网渗透 代理-CSDN博客 注意这里是解决后渗透通讯问题&#xff0c;之后怎么提权&#xff0c;控制后面再说 背景 只有win7有网&#xff0c;其…

Day01-zabbix监控详解

Day01-zabbix监控详解 一、什么是监控&#xff0c;为什么需要监控1.1 监控概述1.2 监控课程大纲 二、Linux的那些独孤九剑级别的命令五、监控的现代时六、Zabbix监控架构6.1 生命周期6.2 Zabbix监控架构 七、Zabbix 6.x Centos7 生产快速实践指南7.1 主机规划1&#xff09; 推荐…

23- ESP32 红外遥控 (RMT)

ESP32 IDF库中的RMT驱动 RMT&#xff08;Remote Control Module&#xff09;驱动是ESP-IDF库中的一个重要组成部分&#xff0c;它主要用于处理远程控制编码和解码。 红外遥控器介绍 一、红外遥控技术介绍 红外遥控是一种无线、非接触控制技术&#xff0c;具有抗干扰能力强&…

ASP.NET网络在线考试系统

摘 要 随着计算机技术的发展和互联网时代的到来&#xff0c;人们已经进入了信息时代&#xff0c;也有人称为数字化时代。数在数字化的网络环境下&#xff0c;学生希望得到个性化的满足&#xff0c;根据自己的情况进行学习&#xff0c;同时也希望能够得到科学的评价&#xff0c…

【深度学习】第一门课 神经网络和深度学习 Week 3 浅层神经网络

&#x1f680;Write In Front&#x1f680; &#x1f4dd;个人主页&#xff1a;令夏二十三 &#x1f381;欢迎各位→点赞&#x1f44d; 收藏⭐️ 留言&#x1f4dd; &#x1f4e3;系列专栏&#xff1a;深度学习 &#x1f4ac;总结&#xff1a;希望你看完之后&#xff0c;能对…

Kelpa-小型服务器开发框架分享

分享我的服务器开发框架--Kelpa&#xff1a; 这是一个由现代C编写的小型、学习性质的服务器框架&#xff0c;包含压缩&#xff0c;序列化&#xff0c;IO调度&#xff0c;Socket封装&#xff0c;文件配置&#xff0c;日志库等多个完整自研模块&#xff1a; 项目目前仍处于开发阶…

QT:输入类控件的使用

LineEdit 录入个人信息 #include "widget.h" #include "ui_widget.h" #include <QDebug> #include <QString>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);// 初始化输入框ui->lineEdit…

文本嵌入的隐私风险:从嵌入向量重建原始文本的探索

随着大型语言模型&#xff08;LLMs&#xff09;的广泛应用&#xff0c;文本嵌入技术在语义相似性编码、搜索、聚类和分类等方面发挥着重要作用。然而&#xff0c;文本嵌入所蕴含的隐私风险尚未得到充分探讨。研究提出了一种控制生成的方法&#xff0c;通过迭代修正和重新嵌入文…

嵌入式硬件中PCB走线与过孔的电流承载能力分析

简介 使用FR4敷铜板PCBA上各个器件之间的电气连接是通过其各层敷着的铜箔走线和过孔来实现的。 由于不同产品、不同模块电流大小不同,为实现各个功能,设计人员需要知道所设计的走线和过孔能否承载相应的电流,以实现产品的功能,防止过流时产品烧毁。 文中介绍设计和测试FR4敷…