角色移动逻辑修改技术需求:碰撞方块后切换Rigidbody.isKinematic属性并设置3秒无敌状态
Hey there! Let's walk through how to build this collision and invincibility system for your character—super straightforward once you break it down:
Core Implementation Approach
- Listen for collision events between your character and the target block
- Use a coroutine to handle the 3-second delay (avoids blocking the main thread)
- Add a boolean flag to track invincibility status, preventing duplicate triggers during the cooldown
Unity C# Code Example
Assuming your character has a Rigidbody and collider (like a CapsuleCollider), and your block has a collider (either standard or set to trigger):
using UnityEngine; using System.Collections; public class PlayerCollisionHandler : MonoBehaviour { private Rigidbody _playerRigidbody; private bool _isInvincible = false; [SerializeField] private float invincibilityLength = 3f; private void Awake() { // Grab the character's Rigidbody component on start _playerRigidbody = GetComponent<Rigidbody>(); } // Use this if your block uses a standard (non-trigger) collider private void OnCollisionEnter(Collision collision) { // Check if we hit the damage block AND we're not already invincible if (collision.gameObject.CompareTag("DamageBlock") && !_isInvincible) { ActivateInvincibility(); } } // Use this if your block uses a trigger collider (tick "Is Trigger" on its collider) private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("DamageBlock") && !_isInvincible) { ActivateInvincibility(); } } private void ActivateInvincibility() { // Freeze physics by setting kinematic to true _playerRigidbody.isKinematic = true; _isInvincible = true; // Start the coroutine to reset status after the delay StartCoroutine(ResetInvincibility()); } private IEnumerator ResetInvincibility() { // Wait the specified invincibility duration yield return new WaitForSeconds(invincibilityLength); // Re-enable physics and remove invincibility _playerRigidbody.isKinematic = false; _isInvincible = false; } }
Key Details to Note
- Tag Setup: Make sure your damage block has a unique tag (like "DamageBlock") so the script only reacts to the right objects
- Coroutine Flexibility: Using a coroutine instead of
Invokelets you easily add extra logic later (like visual effects for invincibility, or canceling the cooldown early) - Invincibility Flag: The
_isInvinciblevariable prevents the collision logic from firing multiple times while the cooldown is active—critical for avoiding broken state - Movement Adjustment: If you want the character to keep moving while invincible, you can control their position directly via
Transforminstead of relying on physics, or adjust Rigidbody constraints instead of settingisKinematic
内容的提问来源于stack exchange,提问作者Cliver Raimundo
相关产品推荐
相关产品推荐

