Multiplayer issue

im trying to make a damage system in multiplayer but im struggling to make it work i dont know how needle engine sync damage for example i have player A and player B when Player A attacks Player B it shows Player B reduced health but in screen of Player B its health stays the same so its not sending changes over network how can i fix it

Hi Danial Apex,

To sync the damage system effectively in a multiplayer environment using Needle Engine, you’ll need to ensure that both players are correctly updating and receiving health state changes. Here’s a plan to help you implement the synchronization:

Plan

  1. Use @syncField: Create a health variable in the player’s script and apply the @syncField decorator to it. This ensures the variable is synchronized across all clients.
  2. Handle Damage: When Player A attacks Player B, you need to ensure Player B’s health is updated locally and the change is communicated to others.
  3. Listen for Changes: In Player B’s script, listen for the health change event and update the display accordingly.

Code Example

Create a PlayerHealth component with synchronized health:

import { Behaviour, syncField } from "@needle-tools/engine";

export class PlayerHealth extends Behaviour {
    @syncField("onHealthChange")
    health: number = 100; // Initial health

    // Method to apply damage
    applyDamage(amount: number) {
        this.health -= amount;
    }

    // Callback when health changes
    private onHealthChange(newHealth: number) {
        this.health = newHealth;
        console.log("Player health updated:", this.health);
        // Update UI or any other representation here
    }
}

In the attacking script for Player A:

export class PlayerAttack extends Behaviour {
    attack(target: PlayerHealth) {
        // Deal damage
        const damage = 10;
        target.applyDamage(damage);
    }
}

Brief Explanation

  • @syncField: Automatically synchronizes the health variable over the network.
  • applyDamage: Deducts health and triggers synchronization automatically.
  • onHealthChange: Method called when health changes, allowing you to update the game UI or other relevant states.

Additional Tips

  • Ensure that both players have a PlayerHealth script attached to their GameObjects.
  • Test the game with multiple browser instances to see the synchronization in action.

You can expand on this by handling health UI updates and potentially adding events for when health reaches zero. If you need more assistance, please let me know!

1 replies left - Get a PRO license for more AI replies.
thread_gigsrHHIAiFj0yTzIAgZDoHu
Reply to this message to continue the conversation

Hi, the bot’s reply should work (using syncField would be the easiest way).

Here’s a little example on stackblitz - just click the cube to see it and notice the value is synchronized and saved in the networked room when you reload the website: Needle-engine - Vite Template (forked) - StackBlitz