import { _decorator, Component, Node, Vec2, Vec3, RigidBody2D, Collider2D, Contact2DType, IPhysics2DContact, find, Prefab, instantiate, UITransform, resources, sp, JsonAsset, Sprite, SpriteFrame, math } from 'cc'; import { BulletCount, BulletSpawnInfo } from './BulletEffects/BulletCount'; import { BulletTrajectory } from './BulletEffects/BulletTrajectory'; import { BulletHitEffect, HitResult } from './BulletEffects/BulletHitEffect'; import { BulletLifecycle } from './BulletEffects/BulletLifecycle'; import { BulletTrailController } from './BulletTrailController'; import { ConfigManager, WeaponConfig, BulletCountConfig, BulletTrajectoryConfig, HitEffectConfig, BulletLifecycleConfig } from '../Core/ConfigManager'; import EventBus,{ GameEvents } from '../Core/EventBus'; import { PersistentSkillManager } from '../FourUI/SkillSystem/PersistentSkillManager'; import { SkillManager } from './SkillSelection/SkillManager'; import { SaveDataManager } from '../LevelSystem/SaveDataManager'; import { WeaponInfo } from './BlockSelection/WeaponInfo'; import { BlockInfo } from './BlockSelection/BlockInfo'; const { ccclass, property } = _decorator; /** * WeaponBullet - 重构后的统一子弹控制器 * * 整合四个子模块: * 1. BulletCount - 子弹数量控制 * 2. BulletTrajectory - 弹道控制 * 3. BulletHitEffect - 命中效果(可叠加) * 4. BulletLifecycle - 生命周期控制 * * 从weapons.json读取配置并分发给各模块 */ export interface BulletInitData { weaponId: string; // 武器ID,用于查找配置 firePosition: Vec3; // 发射位置 direction?: Vec3; // 发射方向(可选) autoTarget?: boolean; // 是否自动瞄准 weaponConfig?: WeaponConfig; // 直接传入的武器配置(优先级更高) weaponInfo?: WeaponInfo; // WeaponInfo组件实例(用于冷却管理等) blockInfo?: BlockInfo; // BlockInfo组件实例(用于获取稀有度等级) } @ccclass('WeaponBullet') export class WeaponBullet extends Component { /* ========= 全局开关:是否允许生成子弹 ========= */ private static shootingEnabled: boolean = true; public static setShootingEnabled(enable: boolean) { WeaponBullet.shootingEnabled = enable; } // 子弹组件 private bulletTrajectory: BulletTrajectory = null; private bulletHitEffect: BulletHitEffect = null; private bulletLifecycle: BulletLifecycle = null; private bulletTrailController: BulletTrailController = null; // 武器配置和状态 private weaponConfig: WeaponConfig = null; private weaponId: string = null; // 存储武器ID用于获取升级数据 private weaponInfo: WeaponInfo = null; // WeaponInfo组件实例 private blockInfo: BlockInfo = null; // BlockInfo组件实例 private isInitialized: boolean = false; // === 静态武器配置缓存 === private static weaponsData: any = null; // === 自动旋转相关 === private readonly _rotationSpeedDeg: number = 720; // 每秒旋转 720° (度) private readonly _rotationSpeedRad: number = 720 * Math.PI / 180; // 转换为弧度,用于物理角速度 /** * 加载武器配置数据 */ public static loadWeaponsData(): Promise { return new Promise((resolve, reject) => { if (WeaponBullet.weaponsData) { resolve(); return; } resources.load('data/weapons', JsonAsset, (err, jsonAsset: JsonAsset) => { if (err) { reject(err); return; } WeaponBullet.weaponsData = jsonAsset.json; resolve(); }); }); } /** * 根据武器ID获取配置 */ public static getWeaponConfig(weaponId: string): WeaponConfig | null { if (!WeaponBullet.weaponsData) { return null; } const weapons = WeaponBullet.weaponsData.weapons; const weapon = weapons.find((w: any) => w.id === weaponId); if (!weapon) { return null; } return weapon as WeaponConfig; } /** * 创建多发子弹 */ public static createBullets(initData: BulletInitData, bulletPrefab: Node): Node[] { // 关卡备战或其他情况下可关闭生成 if (!WeaponBullet.shootingEnabled) return []; // 触发子弹创建请求事件 const eventBus = EventBus.getInstance(); eventBus.emit(GameEvents.BULLET_CREATE_REQUEST, { weaponId: initData.weaponId, position: initData.firePosition }); // 通过事件系统检查是否可以发射子弹 let canFire = true; eventBus.emit(GameEvents.BALL_FIRE_BULLET, { canFire: (result: boolean) => { canFire = result; } }); if (!canFire) { return []; } // 获取武器配置 const originalConfig = initData.weaponConfig || WeaponBullet.getWeaponConfig(initData.weaponId); if (!originalConfig) { return []; } // === 应用多重射击技能 === const config = BulletCount.applyMultiShotSkill(originalConfig); // === 计算基础发射方向 === let direction: Vec3; if (initData.direction) { direction = initData.direction.clone(); } else if (initData.autoTarget) { // 通过事件系统获取最近敌人 let nearestEnemy: Node = null; eventBus.emit(GameEvents.ENEMY_GET_NEAREST, { position: initData.firePosition, callback: (enemy: Node) => { nearestEnemy = enemy; } }); if (nearestEnemy) { direction = nearestEnemy.worldPosition.clone().subtract(initData.firePosition).normalize(); } // 如果没有敌人或计算失败,则回退为随机方向 if (!direction) { const angleRand = Math.random() * Math.PI * 2; direction = new Vec3(Math.cos(angleRand), Math.sin(angleRand), 0); } } else { direction = new Vec3(1, 0, 0); } const spawnInfos = BulletCount.calculateBulletSpawns( config.bulletConfig.count, initData.firePosition, direction ); const bullets: Node[] = []; // 为每个子弹创建实例 for (const spawnInfo of spawnInfos) { const createBullet = () => { try { const bullet = instantiate(bulletPrefab); const weaponBullet = bullet.getComponent(WeaponBullet) || bullet.addComponent(WeaponBullet); // 初始化子弹 weaponBullet.init({ ...initData, firePosition: spawnInfo.position, direction: spawnInfo.direction, weaponConfig: config }); return bullet; } catch (error) { console.error(`[WeaponBullet] 子弹创建失败:`, error); return null; } }; // 处理延迟发射 - 对于burst模式,所有子弹都应该被创建并返回 if (spawnInfo.delay > 0) { // 延迟发射:先创建子弹,然后延迟激活 const bullet = createBullet(); if (bullet) { // 先禁用子弹,延迟后再激活 bullet.active = false; bullets.push(bullet); setTimeout(() => { if (bullet && bullet.isValid) { bullet.active = true; //console.log(`[WeaponBullet] 延迟子弹激活 - 延迟: ${spawnInfo.delay}ms`); } }, spawnInfo.delay); } } else { const bullet = createBullet(); if (bullet) { bullets.push(bullet); } } } return bullets; } /** * 初始化子弹 */ public init(initData: BulletInitData) { // 通过事件系统检查游戏是否暂停,暂停时不初始化子弹 let bulletFireEnabled = true; EventBus.getInstance().emit(GameEvents.BALL_FIRE_BULLET, { canFire: (result: boolean) => { bulletFireEnabled = result; } }); if (!bulletFireEnabled) { // 立即销毁自己 this.node.destroy(); return; } // 验证初始化数据 if (!WeaponBullet.validateInitData(initData)) { console.error('WeaponBullet.init: 初始化数据无效'); this.node.destroy(); return; } // 存储武器ID、WeaponInfo和BlockInfo this.weaponId = initData.weaponId; this.weaponInfo = initData.weaponInfo || null; this.blockInfo = initData.blockInfo || null; // 获取武器配置 this.weaponConfig = initData.weaponConfig || WeaponBullet.getWeaponConfig(initData.weaponId); if (!this.weaponConfig) { console.error(`WeaponBullet.init: 无法找到武器配置 ${initData.weaponId}`); this.node.destroy(); return; } // 应用技能加成计算运行时数值 this.calculateRuntimeStats(); // 使用世界坐标设置位置 this.setPositionInGameArea(initData.firePosition); // 初始化各个组件 this.initializeComponents(initData); // 设置子弹外观 this.setupBulletSprite(); // 设置子弹效果节点激活状态 this.setupBulletEffectNodes(); // 设置碰撞监听 this.setupCollisionListener(); this.isInitialized = true; } /** * 在GameArea中设置位置 */ private setPositionInGameArea(worldPos: Vec3) { const gameArea = find('Canvas/GameLevelUI/GameArea'); if (gameArea) { const gameAreaTransform = gameArea.getComponent(UITransform); if (gameAreaTransform) { const localPos = gameAreaTransform.convertToNodeSpaceAR(worldPos); this.node.position = localPos; } } } /** * 初始化各个组件 */ private initializeComponents(initData: BulletInitData) { const config = this.weaponConfig.bulletConfig; // 确保物理组件存在 this.setupPhysics(); // 设置物理角速度,实现持续旋转 this.applyAutoRotation(); // 初始化弹道组件 this.bulletTrajectory = this.getComponent(BulletTrajectory) || this.addComponent(BulletTrajectory); const trajCfg: BulletTrajectoryConfig = { ...config.trajectory, speed: this.weaponConfig.stats.bulletSpeed }; // 计算方向 const direction = initData.direction || this.calculateDirection(initData.autoTarget); // === 根据发射方向调整容器朝向(仅首次,后续不再旋转) === if (direction) { // 角度 = atan2(y,x),转成度数 const deg = math.toDegree(Math.atan2(direction.y, direction.x)); this.node.angle = deg; } this.bulletTrajectory.init( trajCfg, direction, initData.firePosition ); // --- 额外偏移 --- // 若子弹在生成时与发射方块碰撞(位置重叠), 会立刻触发碰撞事件导致被销毁。 // 因此在初始化完弹道后, 将子弹沿发射方向平移一小段距离(默认 30 像素左右)。 const dir = direction.clone().normalize(); const spawnOffset = 30; // 可根据子弹半径或方块大小调整 if (!Number.isNaN(dir.x) && !Number.isNaN(dir.y)) { const newLocalPos = this.node.position.clone().add(new Vec3(dir.x * spawnOffset, dir.y * spawnOffset, 0)); this.node.setPosition(newLocalPos); } // 初始化命中效果组件 this.bulletHitEffect = this.getComponent(BulletHitEffect) || this.addComponent(BulletHitEffect); this.bulletHitEffect.init(config.hitEffects); // 传递默认特效路径 if (this.bulletHitEffect && config.visual) { (this.bulletHitEffect as any).setDefaultEffects?.(config.visual.hitEffect, config.visual.trailEffect, (config.visual as any).burnEffect); } // 初始化生命周期组件 this.bulletLifecycle = this.getComponent(BulletLifecycle) || this.addComponent(BulletLifecycle); // 为回旋镖类型的武器设置maxRange,如果配置中没有设置的话 const lifecycleConfig = { ...config.lifecycle }; if (lifecycleConfig.type === 'return_trip' && !lifecycleConfig.maxRange && this.weaponConfig.stats.range) { lifecycleConfig.maxRange = this.weaponConfig.stats.range; } this.bulletLifecycle.init(lifecycleConfig, initData.firePosition); // 设置碰撞监听 this.setupCollisionListener(); this.isInitialized = true; } /** * 设置物理组件 */ private setupPhysics() { const rigidBody = this.getComponent(RigidBody2D); if (rigidBody) { rigidBody.enabledContactListener = true; rigidBody.gravityScale = 0; // 由弹道组件控制重力 rigidBody.linearDamping = 0; rigidBody.angularDamping = 0; rigidBody.allowSleep = false; // 如果节点包含子节点 'Pellet',表示这是带容器的子弹;锁定容器旋转 if (this.node.getChildByName('Pellet')) { rigidBody.fixedRotation = true; } } const collider = this.getComponent(Collider2D); if (collider) { collider.sensor = false; collider.on(Contact2DType.BEGIN_CONTACT, this.onHit, this); } } /** * 计算子弹方向 */ private calculateDirection(autoTarget: boolean = false): Vec3 { if (!autoTarget) { // 随机方向 const angle = Math.random() * Math.PI * 2; return new Vec3(Math.cos(angle), Math.sin(angle), 0); } // 寻找最近敌人(使用静态工具函数) const nearestEnemy = WeaponBullet.findNearestEnemyGlobal(this.node.worldPosition); if (nearestEnemy) { const direction = nearestEnemy.worldPosition.clone() .subtract(this.node.worldPosition) .normalize(); return direction; } // 若没有敌人则随机方向发射 const angle = Math.random() * Math.PI * 2; return new Vec3(Math.cos(angle), Math.sin(angle), 0); } /** * 设置碰撞监听 */ private setupCollisionListener() { // 碰撞监听已在setupPhysics中设置 } /** * 碰撞处理 */ private onHit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) { if (!this.isInitialized) return; const otherNode = otherCollider.node; // Ignore collisions with other bullets (prevent friendly-fire between shotgun pellets) if (otherNode.getComponent(WeaponBullet)) { return; // Skip further processing if the collider is another bullet } // 检查是否命中敌人并触发事件 let enemyRootNode: Node = null; // 检查是否碰撞到EnemySprite子节点 if (otherNode.name === 'EnemySprite' && otherNode.parent) { // 如果碰撞到EnemySprite,获取其父节点(敌人根节点) const parentNode = otherNode.parent; if (parentNode.getComponent('EnemyInstance')) { enemyRootNode = parentNode; } } // 兼容旧的敌人检测逻辑(直接碰撞到敌人根节点) else if (otherNode.name.toLowerCase().includes('enemy') || otherNode.name.toLowerCase().includes('敌人') || otherNode.getComponent('EnemyInstance')) { enemyRootNode = otherNode; } if (enemyRootNode) { // 计算是否暴击 const isCritical = Math.random() < this.getCritChance(); const finalDamage = isCritical ? this.getFinalCritDamage() : this.getFinalDamage(); // 触发子弹命中敌人事件 EventBus.getInstance().emit(GameEvents.BULLET_HIT_ENEMY, { enemyNode: enemyRootNode, damage: finalDamage, isCritical: isCritical, source: `WeaponBullet-${this.weaponConfig?.id || 'unknown'}` }); } // 获取碰撞世界坐标 let contactWorldPos: Vec3 = null; if (contact && (contact as any).getWorldManifold) { const wm = (contact as any).getWorldManifold(); if (wm && wm.points && wm.points.length > 0) { contactWorldPos = new Vec3(wm.points[0].x, wm.points[0].y, 0); } } if (!contactWorldPos) { contactWorldPos = otherNode.worldPosition.clone(); } // 处理命中效果 const hitResult: HitResult = this.bulletHitEffect.processHit(otherNode, contactWorldPos); // 通知生命周期组件发生命中(可能影响内部计数或阶段) if (this.bulletLifecycle) { this.bulletLifecycle.onHit(otherNode); } // 不直接销毁,交由 BulletLifecycle 自行处理 // 生命周期和命中效果自行决定是否销毁;此处不再直接销毁,由 BulletLifecycle.update() 完成 if (hitResult.shouldRicochet) { // 执行弹射逻辑:BulletHitEffect已经在processHit中处理了弹射方向改变 // 这里不需要额外操作,弹射方向已经通过calculateRicochetDirection更新 } else if (hitResult.shouldContinue) { // 这里需要实现子弹继续飞行的逻辑 } } /** * 为子弹设置持续旋转(通过刚体角速度,避免被物理系统覆盖) */ private applyAutoRotation() { // 若存在子节点 Pellet,则只旋转 Pellet,容器保持角度不变 const pelletNode = this.node.getChildByName('Pellet'); if (pelletNode) { this.schedule((dt: number) => { pelletNode.angle += this._rotationSpeedDeg * dt; }, 0); return; } const rigidBody = this.getComponent(RigidBody2D); if (rigidBody) { rigidBody.angularVelocity = this._rotationSpeedRad; // 弧度/秒 rigidBody.angularDamping = 0; // 无角阻尼,保持恒定旋转 } else { // 如果没有刚体,退化为在 update 中手动旋转 this.schedule((dt: number) => { this.node.angle += this._rotationSpeedDeg * dt; }, 0); } } /** * 获取武器配置 */ public getWeaponConfig(): WeaponConfig { return this.weaponConfig; } /** * 获取WeaponInfo组件实例 */ public getWeaponInfo(): WeaponInfo | null { return this.weaponInfo; } /** * 获取子弹状态信息 */ public getBulletStatus() { return { isInitialized: this.isInitialized, weaponName: this.weaponConfig?.name, trajectoryState: this.bulletTrajectory?.getState(), lifecycleState: this.bulletLifecycle?.getState(), hitStats: this.bulletHitEffect?.getHitStats() }; } /** * 强制销毁子弹 */ public forceDestroy() { if (this.bulletLifecycle) { this.bulletLifecycle.forceDestroy(); } } /** * 清理所有活跃的子弹 - 游戏重置时使用 */ public static clearAllBullets() { console.log('[WeaponBullet] 开始清理所有活跃子弹'); // 查找GameArea节点,子弹都添加在这里 const gameArea = find('Canvas/GameLevelUI/GameArea'); if (!gameArea) { console.log('[WeaponBullet] 未找到GameArea节点'); return; } let bulletCount = 0; const bulletsToDestroy: Node[] = []; // 遍历GameArea的所有子节点,查找WeaponBullet组件 for (const child of gameArea.children) { if (child && child.isValid) { const weaponBullet = child.getComponent(WeaponBullet); if (weaponBullet) { bulletsToDestroy.push(child); bulletCount++; } } } // 销毁所有找到的子弹 for (const bullet of bulletsToDestroy) { if (bullet && bullet.isValid) { bullet.destroy(); } } console.log(`[WeaponBullet] 清理完成,共销毁 ${bulletCount} 个子弹`); } /** * 验证初始化数据 */ public static validateInitData(initData: BulletInitData): boolean { if (!initData) return false; if (!initData.weaponId && !initData.weaponConfig) return false; if (!initData.firePosition) return false; return true; } onDestroy() { // 清理事件监听 const collider = this.getComponent(Collider2D); if (collider) { collider.off(Contact2DType.BEGIN_CONTACT, this.onHit, this); } // 清理拖尾控制器 if (this.bulletTrailController) { this.bulletTrailController.resetTrail(); this.bulletTrailController = null; } } /** * 设置子弹的SpriteFrame,使其与方块武器 (WeaponBlock/B1/Weapon) 节点上的SpriteFrame 一致 */ private setupBulletSprite() { // 先尝试获取当前节点上的 Sprite 组件,若不存在则在子节点中查找 const sprite: Sprite | null = this.getComponent(Sprite) || this.node.getComponentInChildren(Sprite); if (!sprite) { console.log("未找到Sprite组件"); // 子弹预制体可能没有Sprite组件,直接返回 return; } // 使用武器配置中的bulletConfig.visual.bulletImages字段获取子弹图像路径 const bulletImagePath = this.weaponConfig?.bulletConfig?.visual?.bulletImages; if (!bulletImagePath) { console.log("未找到子弹图像配置 (bulletConfig.visual.bulletImages)"); return; } const framePath = `${bulletImagePath}/spriteFrame`; resources.load(framePath, SpriteFrame, (err, spriteFrame) => { if (err) { console.error(`加载子弹SpriteFrame失败: ${err}`); return; } console.log("设置子弹外观"); // Add comprehensive null safety checks before setting spriteFrame if (sprite && sprite.isValid && this.node && this.node.isValid && spriteFrame && spriteFrame.isValid) { sprite.spriteFrame = spriteFrame; console.log("设置子弹SpriteFrame成功"); // === 子弹大小控制:保持prefab预设的大小 === sprite.node.setScale(sprite.node.scale.x * 0.45, sprite.node.scale.y * 0.45, sprite.node.scale.z); } } ); } /** * 设置子弹效果节点激活状态 */ private setupBulletEffectNodes() { // 尖胡萝卜特殊处理:使用Spine动画而不是拖尾效果 const isSharpCarrot = this.weaponId === 'sharp_carrot'; // 查找Spine节点 const spineNode = this.node.getChildByName('Spine'); if (spineNode) { spineNode.active = isSharpCarrot; } // 查找TrailEffect节点 const trailEffectNode = this.node.getChildByName('TrailEffect'); if (trailEffectNode) { trailEffectNode.active = !isSharpCarrot; // 为拖尾效果设置白色颜色 if (!isSharpCarrot) { const trailController = trailEffectNode.getComponent(BulletTrailController); if (trailController) { trailController.setTrailColor('white'); } } } } /** * 静态:根据给定世界坐标,寻找最近的敌人节点 */ private static findNearestEnemyGlobal(worldPos: Vec3): Node | null { const enemyContainer = find('Canvas/GameLevelUI/enemyContainer'); if (!enemyContainer) return null; const enemies = enemyContainer.children.filter(child => { if (!child.active) return false; const nameLower = child.name.toLowerCase(); if (nameLower.includes('enemy') || nameLower.includes('敌人')) return true; if (child.getComponent('EnemyInstance')) return true; return false; }); if (enemies.length === 0) return null; let nearest: Node = null; let nearestDist = Infinity; for (const enemy of enemies) { const dist = Vec3.distance(worldPos, enemy.worldPosition); if (dist < nearestDist) { nearestDist = dist; nearest = enemy; } } return nearest; } /** * 计算运行时数值(应用武器升级和技能加成) */ private calculateRuntimeStats() { // 获取基础伤害 let baseDamage = this.weaponConfig.stats.damage; // 应用武器升级加成 - 使用UpgradeController的伤害计算逻辑 const saveDataManager = SaveDataManager.getInstance(); if (saveDataManager && this.weaponId) { const weaponData = saveDataManager.getWeapon(this.weaponId); if (weaponData && weaponData.level > 0) { // 优先从武器配置的upgradeConfig中获取伤害值 if (this.weaponConfig.upgradeConfig && this.weaponConfig.upgradeConfig.levels) { const levelConfig = this.weaponConfig.upgradeConfig.levels[weaponData.level.toString()]; if (levelConfig && typeof levelConfig.damage === 'number') { baseDamage = levelConfig.damage; console.log(`[WeaponBullet] 从upgradeConfig获取伤害 - 武器ID: ${this.weaponId}, 等级: ${weaponData.level}, 伤害: ${baseDamage}`); } else { // 如果upgradeConfig中没有伤害值,使用基础伤害 + 等级加成作为后备 baseDamage = this.weaponConfig.stats.damage + (weaponData.level - 1); console.log(`[WeaponBullet] 使用基础伤害计算 - 武器ID: ${this.weaponId}, 等级: ${weaponData.level}, 基础伤害: ${this.weaponConfig.stats.damage}, 升级后伤害: ${baseDamage}`); } } else { // 如果没有upgradeConfig,使用默认公式 baseDamage = this.weaponConfig.stats.damage + (weaponData.level - 1); console.log(`[WeaponBullet] 无upgradeConfig,使用默认公式 - 武器ID: ${this.weaponId}, 等级: ${weaponData.level}, 升级后伤害: ${baseDamage}`); } } } // 应用稀有度伤害倍数(合成升级效果) // 优先从BlockInfo中获取稀有度等级,如果不存在则从武器配置中获取 let rarityLevel = 0; // 默认为common(0) let rarityName = 'common'; if (this.blockInfo) { rarityLevel = this.blockInfo.rarity; rarityName = this.blockInfo.getRarityName(); } else if (this.weaponConfig && this.weaponConfig.rarity) { // 兼容旧的JSON配置方式 rarityName = this.weaponConfig.rarity; } const rarityMultiplier = this.getRarityDamageMultiplierByLevel(rarityLevel); if (rarityMultiplier > 1) { baseDamage = baseDamage * rarityMultiplier; console.log(`[WeaponBullet] 稀有度伤害倍数应用 - 稀有度等级: ${rarityLevel}(${rarityName}), 倍数: ${rarityMultiplier}, 最终基础伤害: ${baseDamage}`); } const skillManager = PersistentSkillManager.getInstance(); if (!skillManager) { // 如果没有技能管理器,使用升级后的基础数值 this.weaponConfig.runtimeStats = { finalDamage: baseDamage, finalCritDamage: baseDamage, critChance: 0.1 // 基础暴击率10% }; console.log(`[WeaponBullet] 无技能管理器 - 最终伤害: ${baseDamage}`); return; } // 应用技能伤害加成(基于升级后的伤害) const finalDamage = skillManager.applyDamageBonus(baseDamage); // 暴击伤害应该基于最终伤害计算,而不是基础伤害 // 首先计算暴击倍数(默认2倍),然后应用技能暴击伤害加成 const baseCritDamage = finalDamage * 2; // 基础暴击倍数2倍 const finalCritDamage = skillManager.applyCritDamageBonus(baseCritDamage); // 应用局内技能暴击率加成 const baseCritChance = 0.1; // 基础暴击率10% let critChance = baseCritChance; // 应用局内技能加成(SkillManager) const inGameSkillManager = SkillManager.getInstance(); if (inGameSkillManager) { const critSkillLevel = inGameSkillManager.getSkillLevel('crit_chance'); if (critSkillLevel > 0) { critChance = SkillManager.calculateCritChance(critChance, critSkillLevel); } } this.weaponConfig.runtimeStats = { finalDamage, finalCritDamage, critChance }; // 输出详细的暴击率计算信息 const inGameCritLevel = inGameSkillManager ? inGameSkillManager.getSkillLevel('crit_chance') : 0; const inGameCritBonus = inGameSkillManager && inGameCritLevel > 0 ? ((SkillManager.calculateCritChance(baseCritChance, inGameCritLevel) - baseCritChance) * 100).toFixed(1) : '0.0'; console.log(`[WeaponBullet] 完整伤害计算完成 - 武器ID: ${this.weaponId}, 原始伤害: ${this.weaponConfig.stats.damage}, 稀有度: ${rarityName}, 计算后基础伤害: ${baseDamage}, 最终伤害: ${finalDamage}, 暴击伤害: ${finalCritDamage}`); console.log(`[WeaponBullet] 暴击率详情 - 基础: ${(baseCritChance * 100).toFixed(1)}%, 局内技能等级: ${inGameCritLevel}, 局内技能加成: +${inGameCritBonus}%, 最终暴击率: ${(critChance * 100).toFixed(1)}%`); } /** * 获取最终伤害值(应用技能加成后) */ public getFinalDamage(): number { return this.weaponConfig?.runtimeStats?.finalDamage || this.weaponConfig?.stats?.damage || 0; } /** * 获取最终暴击伤害值(应用技能加成后) */ public getFinalCritDamage(): number { return this.weaponConfig?.runtimeStats?.finalCritDamage || this.weaponConfig?.stats?.damage || 0; } /** * 获取暴击率 */ public getCritChance(): number { return this.weaponConfig?.runtimeStats?.critChance || 0.1; } /** * 根据稀有度获取伤害倍数 */ private getRarityDamageMultiplier(rarity: string): number { switch (rarity) { case 'common': return 1; // 1级,无倍数 case 'uncommon': return 1.5; // 2级,1.5倍伤害 case 'rare': return 2.25; // 3级,2.25倍伤害 case 'epic': return 8; // 4级,8倍伤害 default: return 1; } } /** * 根据稀有度等级获取伤害倍数 * @param rarityLevel 稀有度等级 (0: common, 1: uncommon, 2: rare, 3: epic) * @returns 伤害倍数 */ private getRarityDamageMultiplierByLevel(rarityLevel: number): number { switch (rarityLevel) { case 0: // common return 1; // 1级,无倍数 case 1: // uncommon return 1.5; // 2级,1.5倍伤害 case 2: // rare return 2.25; // 3级,2.25倍伤害 case 3: // epic return 8; // 4级,8倍伤害 default: return 1; } } }