Java 2D游戏:实体攻击视觉渲染及特定状态渲染问题咨询
Hey there, let's tackle the issue you're having with rendering a specific state for individual entities in your Java 2D game. The core problem here lies in how you're tracking the isHurt state—let's break it down and fix it step by step.
The Root Cause
You've defined isHurt as a static variable:
// Checks if entity is hurt by player public static boolean isHurt = false;
Static variables belong to the Player class itself, not to individual instances. That means every Player object shares the same isHurt value. When you set isHurt = true for one entity, all entities will report being hurt, which breaks your goal of rendering a state specific to a single entity.
Step-by-Step Solution
Convert
isHurtto an instance variable
Remove thestatickeyword so eachPlayerinstance has its ownisHurtstate. It's best to make it private and use getter/setter methods for proper encapsulation:// Checks if this specific entity is hurt private boolean isHurt = false; // Getter to access the state safely public boolean isHurt() { return isHurt; } // Setter to update the state public void setHurt(boolean hurt) { isHurt = hurt; }Update the
checkAttacks()method
Instead of modifying the static class variable, update the instance-specific state using the setter (or direct assignment if you prefer package-private access):// Inside checkAttacks() when you identify the hurt entity if (e.equals(this)) { this.setHurt(true); // Update only THIS instance's hurt state // Or if you skipped the setter: this.isHurt = true; }Adjust your rendering logic
When rendering eachPlayerentity, check its individualisHurtstate to decide what to draw:// In your Player class's render method if (this.isHurt()) { // Render the hurt state sprite/effect for this specific entity g.drawImage(hurtSprite, x, y, width, height, null); } else { // Render the normal state sprite g.drawImage(normalSprite, x, y, width, height, null); }
Bonus Tip: Reset the Hurt State
Don't forget to reset isHurt after a short delay (e.g., using a frame counter) so the entity doesn't stay in the hurt state forever. Add this logic to your update() method:
// Add these variables to your Player class private int hurtTimer = 0; private static final int HURT_DURATION = 30; // 30 frames (~0.5s at 60fps) // In your update() method public void update() { if (isHurt()) { hurtTimer++; if (hurtTimer >= HURT_DURATION) { setHurt(false); hurtTimer = 0; } } // Rest of your update logic }
内容的提问来源于stack exchange,提问作者Pete

