Unity类银河恶魔城学习记录4-1,4-2 Attack Logic,Collider‘s collision excepetion源代码 P54 p55

news2024/9/24 9:23:05
Alex教程每一P的教程原代码加上我自己的理解初步理解写的注释,可供学习Alex教程的人参考
此代码仅为较上一P有所改变的代码
【Unity教程】从0编程制作类银河恶魔城游戏_哔哩哔哩_bilibili

Entity.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Entity : MonoBehaviour
{

    [Header("Collision Info")]
    public Transform attackCheck;//transform类,代表的时物体的位置,用来控制攻击检测的位置
    public float attackCheckRadius;//检测半径
    [SerializeField] protected Transform groundCheck;//transform类,代表的时物体的位置,后面会来定位子组件的位置    
    [SerializeField] protected float groundCheckDistance;
    [SerializeField] protected Transform wallCheck;//transform类,代表的时物体的位置,后面会来定位子组件的位置    
    [SerializeField] protected float wallCheckDistance;
    [SerializeField] protected LayerMask whatIsGround;//LayerMask类,与Raycast配合,https://docs.unity3d.com/cn/current/ScriptReference/Physics.Raycast.html

    #region 定义Unity组件
    public Animator anim { get; private set; }//这样才能配合着拿到自己身上的animator的控制权
    public Rigidbody2D rb { get; private set; }//配合拿到身上的Rigidbody2D组件控制权
    #endregion
    public int facingDir { get; private set; } = 1;
    protected bool facingRight = true;//判断是否朝右

    protected virtual void Awake()
    {
        anim = GetComponentInChildren<Animator>();//拿到自己身上的animator的控制权
        rb = GetComponent<Rigidbody2D>();
    }
    protected virtual void Start()
    {

    }
    protected virtual void Update()
    {

    }
    public virtual void Damage()
    {
        Debug.Log(gameObject.name+"was damaged");
    }
    #region 速度函数Velocity
    public virtual void SetZeroVelocity()
    {
        rb.velocity = new Vector2(0, 0);
    }//设置速度为0函数

    public virtual void SetVelocity(float _xVelocity, float _yVelocity)
    {
        rb.velocity = new Vector2(_xVelocity, _yVelocity);//将rb的velocity属性设置为对应的想要的二维向量。因为2D游戏的速度就是二维向量
        FlipController(_xVelocity);//在其他设置速度的时候调用翻转控制器
    }//控制速度的函数,此函数在其他State中可能会使用,但仅能通过player.SeVelocity调用
    #endregion
    #region 翻转函数Flip
    public virtual void Flip()
    {
        facingDir = facingDir * -1;
        facingRight = !facingRight;
        transform.Rotate(0, 180, 0);//旋转函数,transform不需要额外定义,因为他是自带的
    }//翻转函数

    public virtual void FlipController(float _x)//目前设置x,目的时能在空中时也能转身
    {
        if (_x > 0 && !facingRight)//当速度大于0且没有朝右时,翻转
        {
            Flip();
        }
        else if (_x < 0 && facingRight)
        {
            Flip();
        }
    }
    #endregion
    #region 碰撞函数Collision
    public virtual bool IsGroundDetected()
    {
        return Physics2D.Raycast(groundCheck.position, Vector2.down, groundCheckDistance, whatIsGround);
    }//通过RayCast检测是否挨着地面,https://docs.unity3d.com/cn/current/ScriptReference/Physics2D.Raycast.html
    //xxxxxxxx()   => xxxxxxxx  == xxxxxxxxxx() return xxxxxxxxx;
    public virtual bool IsWallDetected()
    {
        return Physics2D.Raycast(wallCheck.position, Vector2.right * facingDir, wallCheckDistance, whatIsGround);
    }//通过RayCast检测是否挨着地面,https://docs.unity3d.com/cn/current/ScriptReference/Physics2D.Raycast.html
    //xxxxxxxx()   => xxxxxxxx  == xxxxxxxxxx() return xxxxxxxxx;
    protected virtual void OnDrawGizmos()
    {
        Gizmos.DrawLine(groundCheck.position, new Vector3(groundCheck.position.x, groundCheck.position.y - groundCheckDistance));//绘制一条从 from(前面的) 开始到 to(后面的) 的线。
        Gizmos.DrawLine(wallCheck.position, new Vector3(wallCheck.position.x + wallCheckDistance, wallCheck.position.y));//绘制一条从 from(前面的) 开始到 to(后面的) 的线。
        Gizmos.DrawWireSphere(attackCheck.position, attackCheckRadius);//https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Gizmos.DrawWireSphere.html
        //绘制具有中心和半径的线框球体。
    }//画图函数
    #endregion
}
PlayerAnimationTrigger.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerAnimationTriggers : MonoBehaviour
{
    private Player player => GetComponentInParent<Player>();//获得夫组件上的实际存在的Player组件
    private void AnimationTrigger()
    {
        player.AnimationTrigger();
    }
    private void AttackTrigger()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(player.attackCheck.position, player.attackCheckRadius);//创建一个碰撞器组,保存所有圈所碰到的碰撞器
        //https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Physics2D.OverlapCircleAll.html
        foreach(var hit in colliders)//https://blog.csdn.net/m0_52358030/article/details/121722077
        {
            if(hit.GetComponent<Enemy>()!=null)
            {
                hit.GetComponent<Enemy>().Damage();
            }
        }
    }
}
Enemy_SkeletonAnimationTrigger.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy_SkeletonAnimationTriggers : MonoBehaviour
{
    private Enemy_Skeleton enemy => GetComponentInParent<Enemy_Skeleton>();//拿到enemy实体
    private void AnimationTrigger()
    {
        enemy.AnimationFinishTrigger();//调用实体上的函数,使triggerCalled为true;
    }

    private void AttackTrigger()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(enemy.attackCheck.position, enemy.attackCheckRadius);//创建一个碰撞器组,保存所有圈所碰到的碰撞器
        //https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Physics2D.OverlapCircleAll.html
        foreach (var hit in colliders)//https://blog.csdn.net/m0_52358030/article/details/121722077
        {
            if (hit.GetComponent<Player>() != null)
            {
                hit.GetComponent<Player>().Damage();
            }
        }
    }
}
SkeletonBattleState.cs
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
//从ground进来的
public class SkeletonBattleState : EnemyState
{
    private Transform player;//用于给Player定位,好判断怎么跟上他
    private Enemy_Skeleton enemy;
    private int moveDir;
    public SkeletonBattleState(Enemy _enemyBase, EnemyStateMachine _stateMachine, string _animBoolName,Enemy_Skeleton _enemy ) : base(_enemyBase, _stateMachine, _animBoolName)
    {
        enemy = _enemy;
    }

    public override void Enter()
    {
        base.Enter();
        
        player = GameObject.Find("Player").transform;//全局找Player位置
    }

    public override void Exit()
    {
        base.Exit();
    }

    public override void Update()
    {
        base.Update();
        //退出此状态的方式
        if(enemy.IsPlayerDetected())
        {
            stateTimer = enemy.battleTime;
            if (enemy.IsPlayerDetected().distance < enemy.attackDistance)//当距离小于攻击距离,变为攻击状态
            {
                if (CanAttack())
                    stateMachine.ChangeState(enemy.attackState);
            }
        }
        else//当没有看见player后,才会根据没有看到的时间来使其退出battle状态
        {
            if(stateTimer < 0||Vector2.Distance(player.transform.position,enemy.transform.position)>7)//根据距离来判断是否结束battle状态
            {
                stateMachine.ChangeState(enemy.idleState);
            }
        }
        

        //下面为移动方向设置
        if(player.position.x > enemy.transform.position.x)//在右,向右移动
        {
            moveDir = 1;
        }
        else if(player.position.x<enemy.transform.position.x)//在左,向左移动
        {
            moveDir = -1;
        }

        if(Vector2.Distance(player.transform.position,enemy.transform.position)>1)
        enemy.SetVelocity(enemy.moveSpeed * moveDir, rb.velocity.y);
        else
        {
            enemy.SetZeroVelocity();
        }//我自己设置了一个敌人接近一定距离就停下来的设置,防止出现敌人乱晃的情况
    }

    private bool CanAttack()
    {
        if(Time.time > enemy.lastTimeAttacked + enemy.attackCooldown)
        {
            enemy.lastTimeAttacked = Time.time;
            return true;
        }
        
        return false;
    }
}

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

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

相关文章

C/C++ - 容器vector

目录 容器特性 构造函数 默认构造函数 填充构造函数 范围构造函数 拷贝构造函数 内存布局 大小函数 size() 函数 capacity() 函数 empty() 函数 resize() 函数 增加函数 push_back(const T& value) emplace_back(Args&&... args) push_back和empla…

linux(redhat)重置root密码

首先将root密码改成几乎不可能记住的密码 [rootexample ~]# echo fheowafuflaeijifehowf|passwd --stdin root Changing password for user root. passwd: all authentication tokens updated successfully.重启系统&#xff0c;进入救援模式 出现此页面&#xff0c;按e键 lin…

一个简单的2024龙年倒计时页面html源码

预览如下 复制粘贴下面的代码&#xff0c;另存为html文件即可打开&#xff0c;文字链接都可以更改&#xff1a; <!doctype html> <html> <head> <meta charset"utf-8"> <title>2024新年倒计时</title> <style>::-webki…

Linux操作系统基础(二):Linux操作系统概述

文章目录 Linux操作系统概述 一、Linux起源 二、Linux 的含义 三、Linux发行版 Linux操作系统概述 一、Linux起源 Linux创始人——林纳斯 托瓦兹 Linux 诞生于1991年&#xff0c;作者上大学期间实现的 Linux的特点&#xff1a;开源、免费、拥有最为庞大的源码贡献者 …

Mac安装Homebrew+MySQL+Redis+Nginx+Tomcat等

Mac安装HomebrewMySQLRedisNginxTomcat等 文章目录 Mac安装HomebrewMySQLRedisNginxTomcat等一、Mac安装Mysql 8①&#xff1a;下载②&#xff1a;安装③&#xff1a;配置环境变量④&#xff1a;外部连接测试 二、Mac安装Redis和可视化工具①&#xff1a;安装Redis01&#xff1…

STL常用容器—set容器

STL常用容器—set容器 1. set容器相关概念2. 初始化容器3. set容器插入和删除4. set容器大小和交换5. set容器的查找和统计6. set、multiset、unordered_set三者的区别7. pair对组的创建8. set容器的排序 参考博文&#xff1a;STL常用容器——set容器的使用 1. set容器相关概念…

SpringSecurity+OAuth2权限管理实战

Spring Security快速入门 官方文档&#xff1a; Spring Security :: Spring Security 功能&#xff1a; 身份认证&#xff08;authentication&#xff09; 授权&#xff08;authorization&#xff09; 防御常见攻击&#xff08;protection against common attacks&#xff…

Filter 实现过滤符合条件的请求并落库

其他系列文章导航 Java基础合集数据结构与算法合集 设计模式合集 多线程合集 分布式合集 ES合集 文章目录 其他系列文章导航 文章目录 前言 一、配置过滤器类 二、定义数据表、实体类、Mapper 2.1 DDL 2.2 实体类 2.3 Mapper 三、创建一个过滤器 四、实现 Nacos 配置…

C语言第二十一弹---指针(五)

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】 转移表 1、转移表 总结 1、转移表 函数指针数组的用途&#xff1a;转移表 举例&#xff1a;计算器的⼀般实现&#xff1a; 假设我们需要做一个能够进行加减…

JavaScript 弹窗(Popup Windows)

&#x1f9d1;‍&#x1f393; 个人主页&#xff1a;《爱蹦跶的大A阿》 &#x1f525;当前正在更新专栏&#xff1a;《VUE》 、《JavaScript保姆级教程》、《krpano》、《krpano中文文档》 ​ ​ ✨ 前言 在互联网时代&#xff0c;弹窗是一种常见的交互方式。它可以用于显示…

C语言笔试题之二进制求和

实例要求&#xff1a; 给定2个二进制字符串 a 和 b &#xff0c;以二进制字符串的形式返回它们的和&#xff1b; 案例展示&#xff1a; 实例分析&#xff1a; 1、利用strlen函数分别求出二进制字符串 a 和 b的长度&#xff1b;2、结果字符串长度为较长输入字符串加1&#xf…

数据结构入门(1)数据结构介绍

目录 前言 1. 什么是数据结构&#xff1f; 2.什么是算法&#xff1f; 3.数据结构和算法的重要性 前言 本文将开始介绍计算机里的数据结构。 数据结构是指数据对象中元素之间的关系&#xff0c;以及对这些关系的操作。数据结构可以分为线性结构和非线性结构。 线性结构是…

力扣面试题 05.06. 整数转换(位运算)

Problem: 面试题 05.06. 整数转换 文章目录 题目描述思路及解法复杂度Code 题目描述 思路及解法 1.通过将两个数进行异或操作求出两个数中不同的位(不同的位异或后为二进制1); 2.统计异或后不同的位的个数(即异或后二进制为1的个数) 复杂度 时间复杂度: O ( 1 ) O(1) O(1) 空间…

C++:STL - vector

C&#xff1a;STL - vector 构造函数修改操作push_backpop_backerase 访问操作emptyoperatror[]backfront 容量操作sizecapacityresizereserve C的vector是一种可变长度的动态数组&#xff0c;被广泛用于C编程中。它是标准模板库&#xff08;STL&#xff09;中的容器之一&#…

2024年 复习 HTML5+CSS3+移动web 笔记 之CSS遍 第6天

6.1 定位-相对和绝对和固定 6.2 相对和绝对和固定 6.3 堆叠顺序z-index 6.4 定位总结 6.5 CSS精灵 基本使用 6.6 案例 CSS精灵 京东服务 6.7 字体图标-下载和使用 6.8 字体图标-上传 6.9 垂直对齐方式vertical-align 6.10 过渡属性 6.11 修饰属性-透明度与光标类型 6.12 综合案…

react将选中文本自动滑动到容器可视区域内

// 自动滚动到可视区域内useEffect(() > {const target ref;const wrapper wrapperRef?.current;if (target && wrapperRef) {const rect target.getBoundingClientRect();const wrapperRect wrapper.getBoundingClientRect();const isVisible rect.bottom &l…

npm 上传一个自己的应用(4) 更新自己上传到NPM中的工具版本 并进行内容修改

前面 npm 上传一个自己的应用(2) 创建一个JavaScript函数 并发布到NPM 我们讲了将自己写的一个函数发送到npm上 那么 如果我们想到更好的方案 希望对这个方法进行修改呢&#xff1f; 比如 我们这里加一个方法 首先 我们还是要登录npm npm login然后 根据要求填写 Username 用…

Sping Cloud Hystrix 参数配置、简单使用、DashBoard

Sping Cloud Hystrix 文章目录 Sping Cloud Hystrix一、Hystrix 服务降级二、Hystrix使用示例三、OpenFeign Hystrix四、Hystrix参数HystrixCommand.Setter核心参数Command PropertiesFallback降级配置Circuit Breaker 熔断器配置Metrix 健康统计配置Request Context 相关参数C…

【Spring源码解读!底层原理进阶】【上】探寻Spring内部:BeanFactory和ApplicationContext实现原理揭秘✨

&#x1f389;&#x1f389;欢迎光临&#x1f389;&#x1f389; &#x1f3c5;我是苏泽&#xff0c;一位对技术充满热情的探索者和分享者。&#x1f680;&#x1f680; &#x1f31f;特别推荐给大家我的最新专栏《Spring 狂野之旅&#xff1a;底层原理高级进阶》 &#x1f680…

【图形图像的C++ 实现 01/20】 2D 和 3D 贝塞尔曲线

目录 一、说明二、贝塞尔曲线特征三、模拟四、全部代码如下 一、说明 以下文章介绍了用 C 计算和绘制的贝塞尔曲线&#xff08;2D 和 3D&#xff09;。    贝塞尔曲线具有出色的数学能力来计算路径&#xff08;从起点到目的地点的曲线&#xff09;。曲线的形状由“控制点”决…