Unity自定义PlayerCombat战斗脚本设置startTimeBtwAttack大于0时失效求助
问题根因
你的攻击冷却计时逻辑和输入检测、攻击状态更新的代码块层级完全错误,核心错误有两个:
- 你把
timeBtwAttack的重置操作timeBtwAttack = startTimeBtwAttack写在了冷却归零的判断块最开头,等于冷却刚归零就直接被重新赋值成冷却时长,输入检测和攻击状态更新的代码只在冷却归零的单帧能执行,Input.GetKeyDown只有刚好和冷却归零帧完全重合才会触发,几乎不可能触发成功 - 冷却计时的递减逻辑
timeBtwAttack -= Time.deltaTime被放在了if(hasSword == true)的块外面,只有当你没有剑的时候才会走冷却递减,有剑的时候冷却值永远不会正常往下掉
修复后代码
把冷却重置逻辑移到攻击触发之后,冷却递减逻辑移到hasSword判断块内部,调整后的完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerCombat : MonoBehaviour { private PlayerMovement speed; public bool hasSword = true; private float timeBtwAttack; public float startTimeBtwAttack; public Animator animator; public Transform attackPos; public float attackRange; public LayerMask whatIsEnemies; public int damage; public AudioSource swordSrc; public AudioClip swordClip; public float startDazedTime; private float dazedTime; private float attackTime = .25f; private float attackCounter = .25f; private bool isAttacking; void Start() { speed = FindObjectOfType<PlayerMovement>(); // 初始化冷却值,避免开局第一帧就可以攻击,不需要可以删除 timeBtwAttack = startTimeBtwAttack; } void Update() { if (hasSword == true) { // 处理眩晕逻辑 if (dazedTime <= 0) { speed.MovementSpeed = 5f; } else { speed.MovementSpeed = 0f; dazedTime -= Time.deltaTime; } // 攻击状态更新不受冷却影响,单独提取到冷却判断外 if(isAttacking) { attackCounter -= Time.deltaTime; if (attackCounter <= 0) { animator.SetBool("isAttacking", false); isAttacking = false; } } // 统一处理冷却计时 if (timeBtwAttack > 0) { timeBtwAttack -= Time.deltaTime; } else { // 冷却归零后检测攻击输入 if (Input.GetKeyDown(KeyCode.X)) { dazedTime = startDazedTime; attackCounter = attackTime; animator.SetBool("isAttacking", true); swordSrc.PlayOneShot(swordClip); isAttacking = true; Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsEnemies); for (int i = 0; i < enemiesToDamage.Length; i++) { enemiesToDamage[i].GetComponent<EnemyScript>().TakeDamage(damage); } // 攻击触发后再重置冷却 timeBtwAttack = startTimeBtwAttack; } } } } void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(attackPos.position, attackRange); } }
内容的提问来源于stack exchange,提问作者Aseed Kid
相关产品推荐
相关产品推荐

