### Connect and Join Room Example Source: https://doc.photonengine.com/fusion-godot/current/manual/connection A complete script demonstrating connection to Photon, joining a room with custom options, and handling room-joined events. Connects to Photon and then attempts to join or create a room. ```gdscript extends Node func _ready(): Fusion.room_joined.connect(_on_room_joined) Fusion.connection_failed.connect(func(e): print("Failed: ", e)) Fusion.connect_to_photon("player_%d" % randi()) Fusion.connected_to_photon.connect(func(): Fusion.join_or_create_room("lobby", { "max_players": 8, "is_visible": true, "map": "arena", "lobby_properties": ["map"], }) ) func _on_room_joined(): print("In room as player ", Fusion.get_local_player_id()) ``` -------------------------------- ### Broadcast RPC Setup and Usage Source: https://doc.photonengine.com/fusion-godot/current/manual/rpcs/basics Register a node as a broadcast receiver using `Fusion.register_broadcast_receiver(self)` in `_ready()`. Unregister in `_exit_tree()` to prevent crashes. This example demonstrates sending and receiving chat messages. ```gdscript func _ready(): Fusion.register_broadcast_receiver(self) func _exit_tree(): if Fusion: Fusion.unregister_broadcast_receiver(self) @rpc("any_peer", "call_local") func chat_message(sender: String, text: String): print('[%s]: %s' % [sender, text]) func send_chat(text: String): Fusion.rpc(chat_message, local_player_name, text) ``` -------------------------------- ### Setup Custom Mode for Scene Loading Source: https://doc.photonengine.com/fusion-godot/current/manual/large-scenes Use Custom mode for manual control over scene loading, such as displaying a loading screen. Emit `scene_load_requested` and then call `Fusion.notify_scene_ready()` after instantiating the scene. ```GDScript func _ready(): Fusion.set_scene_load_mode(Fusion.SCENE_LOAD_CUSTOM) Fusion.scene_load_requested.connect(_on_load) func _on_load(index: int, scene: PackedScene): var instance = scene.instantiate() add_child(instance) Fusion.notify_scene_ready(instance, index) ``` -------------------------------- ### Setup Auto Mode for Scene Loading Source: https://doc.photonengine.com/fusion-godot/current/manual/large-scenes In Auto mode, Fusion manages scene loading and parenting internally. Connect to `scene_ready` to be notified when scene objects are synced. Load scenes using `Fusion.load_scene()`. ```GDScript const ArenaScene = preload("res://maps/arena.tscn") func _ready(): Fusion.set_scene_load_mode(Fusion.SCENE_LOAD_AUTO) Fusion.set_scene_parent(self) Fusion.scene_ready.connect(func(idx): print("Scene objects synced: ", idx)) func start_game(): Fusion.load_scene(ArenaScene) # master client only ``` -------------------------------- ### Property Path Examples in GDScript Source: https://doc.photonengine.com/fusion-godot/current/manual/replication/syncing-properties Use the `node:property` syntax to specify properties relative to the replicator's root node. This allows targeting properties on the root itself or nested children. ```gdscript ":health" # Root node "Sprite2D:modulate" # Child Sprite2D ``` -------------------------------- ### Object-Targeted RPC Example Source: https://doc.photonengine.com/fusion-godot/current/manual/rpcs/basics Invoke a method on a specific networked object across clients. The method must be on a node with a replicator child, allowing Fusion to route the call. This example shows calling `take_damage` on remote clients and specifically to the object's owner. ```gdscript @rpc("any_peer", "call_local") # any_peer: any client may send; call_local: also runs locally on the sender func take_damage(amount: int): health -= amount func attack(): # take_damage is a method on this node, and this node has a replicator child, # so Fusion routes the call through that replicator on remote clients. Fusion.rpc(take_damage, 10) # Same routing, but delivered only to the object's owner. Fusion.rpc_to(Fusion.TARGET_OWNER, take_damage, 10) ``` -------------------------------- ### 2D RigidBody Input Handling Source: https://doc.photonengine.com/fusion-godot/current/manual/physics-replication Example of handling input on the authority client for a 2D RigidBody. Remote clients automatically receive physics state updates via the FusionSharedReplicator. ```GDScript extends RigidBody2D const MOVE_FORCE := 600.0 @onready var sync: FusionSharedReplicator = $FusionSharedReplicator func _physics_process(delta): if sync.has_authority(): var dir = Input.get_axis("ui_left", "ui_right") if dir != 0: apply_central_force(Vector2(dir * MOVE_FORCE, 0)) if Input.is_action_just_pressed("ui_accept"): apply_central_impulse(Vector2(0, -500)) ``` -------------------------------- ### Check and Request Authority Source: https://doc.photonengine.com/fusion-godot/current/manual/replication/ownership-modes Use these methods to determine current ownership, get the owner's ID, and request or release ownership of an object. ```gdscript $FusionSharedReplicator.has_authority() # am I the current owner? $FusionSharedReplicator.get_owner_id() # which player owns this object? $FusionSharedReplicator.want_authority(true) # claim ownership $FusionSharedReplicator.want_authority(false) # release ownership ``` -------------------------------- ### Initialize Custom Replicated Property in Godot Source: https://doc.photonengine.com/fusion-godot/current/getting-started/quick-start-guide Set the custom replicated property 'player_name' in the _ready() function of a movement script, ensuring it's only done on the authoritative client. This example demonstrates initializing player names dynamically. ```GDScript if sync.has_authority(): player_name = "Player" + str(Fusion.get_local_player_id()) ``` -------------------------------- ### Setting Property Interpolation Mode and Custom Callable Source: https://doc.photonengine.com/fusion-godot/current/manual/replication/syncing-properties Dynamically switch a property's interpolation mode or install a custom interpolation callable at runtime using `set_property_interpolation`. This allows for fine-grained control without altering the saved replication configuration. ```GDScript replicator.set_property_interpolation( property: NodePath, mode: int, # FusionReplicationConfig.INTERPOLATE_NONE / LERP / ANGLE callable: Callable = Callable() # empty Callable = no custom interpolator ) -> void ``` ```GDScript # Typed signature (recommended): types must match the property's runtime Variant type. func smooth_health(current: float, target: float, decay_time: float, delta: float) -> float: return lerp(current, target, 1.0 - exp(-delta / decay_time)) func _ready() -> void: replicator.set_property_interpolation( ^":health", FusionReplicationConfig.INTERPOLATE_LERP, smooth_health) # Switch mode without a callable replicator.set_property_interpolation(^":yaw", FusionReplicationConfig.INTERPOLATE_ANGLE) # Disable both for a property replicator.set_property_interpolation(^":health", FusionReplicationConfig.INTERPOLATE_NONE) ``` -------------------------------- ### Connect to Photon and Join Room (GDScript) Source: https://doc.photonengine.com/fusion-godot/current/getting-started/quick-start-guide Initiates connection to the Photon master server and then attempts to join or create a room. This function should be called when a user action, like clicking a connect button, occurs. It registers a callback for successful connection to handle room joining. ```gdscript func _connect_and_join_room(): print("clicked connect") var user_id = "user_%d" % randi() Fusion.connect_to_photon(user_id) Fusion.connected_to_photon.connect(func(): print("trying to join/create room as user: ", user_id) Fusion.join_or_create_room() ) ``` -------------------------------- ### Connect and Join Room (GDScript) Source: https://doc.photonengine.com/fusion-godot/current/manual/connection Connect to the Photon Cloud first, then join or create a room once the connection succeeds. For local development, set the connection mode to 'Local' in Project Settings. ```gdscript Fusion.connect_to_photon("player_123", "us") # Wait for connection, then join Fusion.connected_to_photon.connect(func(): Fusion.join_or_create_room("lobby") ) ``` -------------------------------- ### Connect to Photon and Join/Create Room in GDScript Source: https://doc.photonengine.com/fusion-godot/current/fusion-intro Connects to the Photon Cloud and then joins or creates a room. Ensure you have a valid Photon region string. ```gdscript Fusion.connect_to_photon("player_42", "us") # "us" = Photon Cloud region Fusion.connected_to_photon.connect(func(): Fusion.join_or_create_room("arena", {"max_players": 8}) ) ``` -------------------------------- ### Connect to Photon Cloud (GDScript) Source: https://doc.photonengine.com/fusion-godot/current/manual/connection Connect to the Photon Cloud. All parameters are optional; empty values are filled from Project Settings. ```gdscript # Simplest: everything from Project Settings Fusion.connect_to_photon() # With a specific user ID Fusion.connect_to_photon("player_123") # With a specific region (forces Cloud mode) Fusion.connect_to_photon("player_123", "us") ``` -------------------------------- ### Initialize Fusion Connection and Spawn Player Source: https://doc.photonengine.com/fusion-godot/current/getting-started/quick-start-guide This script initializes the Fusion connection to Photon, connects to a room, and registers a spawnable player scene. It's intended to be attached to the root node of the main scene. ```GDScript extends Node2D const PlayerScene = preload("res://player.tscn") @onready var spawner: FusionSpawner = $FusionSpawner @onready var connect_button: Button = $UIConnectButton func _ready(): Fusion.room_joined.connect(_on_room_joined) connect_button.pressed.connect(_connect_and_join_room) spawner.add_spawnable_scene(PlayerScene) ``` -------------------------------- ### Spawning a Scene with FusionSpawner Source: https://doc.photonengine.com/fusion-godot/current/manual/spawning Preload a scene, add it to a FusionSpawner, bind a replicator, and then spawn instances of that scene. Ensure sub-objects have their own replicators and that ownership follows the root object. ```gdscript const TurretScene = preload("res://turret.tscn") @onready var sub_spawner: FusionSpawner = $SubSpawner func _ready(): sub_spawner.add_spawnable_scene(TurretScene) sub_spawner.bind_root_replicator(get_node("FusionSharedReplicator")) # or "FusionServerReplicator" in Client-Server func spawn_turret(): var turret = sub_spawner.spawn(TurretScene) turret.position = Vector2(0, -20) ``` -------------------------------- ### Room Operations (GDScript) Source: https://doc.photonengine.com/fusion-godot/current/manual/connection Provides methods to create, join, or leave rooms. The 'options' parameter is an optional Dictionary; omit it or pass '{}' for defaults. ```gdscript # Create a new room (fails if it already exists) Fusion.create_room("my_room", options) # Join an existing room (empty name = random room) Fusion.join_room("my_room", options) # Join if exists, create if not Fusion.join_or_create_room("my_room", options) # Leave current room (stays connected for re-matchmaking) Fusion.leave_room() ``` -------------------------------- ### Registering Spawnable Scenes with FusionSpawner Source: https://doc.photonengine.com/fusion-godot/current/manual/spawning Add scenes to the FusionSpawner's registry to make them available for networked spawning. Ensure all clients register the same scenes in the same order. Connect to spawned and despawned signals for event handling. ```gdscript const PlayerScene = preload("res://player.tscn") const ProjectileScene = preload("res://projectile.tscn") @onready var spawner = $FusionSpawner func _ready(): spawner.add_spawnable_scene(PlayerScene) spawner.add_spawnable_scene(ProjectileScene) spawner.spawned.connect(func(n): print("Spawned: ", n.name)) spawner.despawned.connect(func(n): print("Despawned: ", n.name)) ``` -------------------------------- ### Spawn Vehicle on Room Join (GDScript) Source: https://doc.photonengine.com/fusion-godot/current/game-samples/racing-starter-kit This snippet shows how to spawn a vehicle for the player when they join a room and position it in a specific lane based on player ID. Ensure `vehicle_spawner` is correctly set up. ```gdscript func _on_room_joined(): vehicle = vehicle_spawner.spawn() vehicle.position = Vector3(player_id * 4.0, 2.0, 0.0) ``` -------------------------------- ### Send RPC to All Peers Source: https://doc.photonengine.com/fusion-godot/current/manual/rpcs/basics Use `Fusion.rpc()` to send a method call to every peer. This is the default behavior and equivalent to `rpc_to(Fusion.TARGET_ALL, ...)`. Ensure the target method and arguments are correctly provided. ```gdscript Fusion.rpc(my_method, arg1, arg2) ``` -------------------------------- ### Spawning and Despawning Networked Objects Source: https://doc.photonengine.com/fusion-godot/current/manual/spawning Use the `spawn()` method to create networked instances of registered scenes and `despawn()` to remove them from all clients. Properties set on the returned node after spawning will be replicated. ```gdscript # Spawn first registered scene var player = spawner.spawn() player.position = Vector2(100, 200) # Spawn a specific registered scene var projectile = spawner.spawn(ProjectileScene) # Despawn spawner.despawn(player) ``` -------------------------------- ### Spawn Player Scene on Room Join (GDScript) Source: https://doc.photonengine.com/fusion-godot/current/getting-started/quick-start-guide Spawns a player instance when the client successfully joins a room. This function is typically connected to the `room_joined` signal. It assigns a random position to the spawned player and prints a confirmation message. ```gdscript func _on_room_joined(): var pos = Vector2(randf_range(100, 700), randf_range(100, 500)) var player = spawner.spawn() player.position = pos print("joined room and spawned player scene at: ", pos) ``` -------------------------------- ### Manual Exponential Interpolation with Fusion Singleton Source: https://doc.photonengine.com/fusion-godot/current/manual/replication/syncing-properties Use Fusion's singleton helpers for manual exponential smoothing of properties when 'Interpolate' is set to 'None'. These functions are useful for smoothing local copies of replicated state, such as UI display values. ```GDScript var smoothed_health: float = 0.0 var smoothed_yaw: float = 0.0 func _process(delta: float) -> void: smoothed_health = Fusion.interpolate_exponential(smoothed_health, health, 0.15, delta) smoothed_yaw = Fusion.interpolate_exponential_angle(smoothed_yaw, target_yaw, 0.15, delta) ``` -------------------------------- ### Configure RPC Permissions and Execution with @rpc Source: https://doc.photonengine.com/fusion-godot/current/manual/rpcs/basics Use the @rpc annotation to define who can send an RPC and if it runs locally on the sender. Options include 'any_peer' for broad access and 'authority' for restricted access, along with 'call_local' for immediate sender execution. ```gdscript @rpc("any_peer", "call_local") # any client may send; also runs on the sender @rpc("authority") # only the authority may send; default is "call_remote" @rpc("any_peer", "call_remote") # any client may send; only remotes execute ``` -------------------------------- ### Spawn Networked Objects in GDScript Source: https://doc.photonengine.com/fusion-godot/current/fusion-intro Loads a player scene and registers it with the spawner, then spawns an instance of it. This scene will be created on all clients in the same room. ```gdscript var player_scene = preload("res://player.tscn") spawner.add_spawnable_scene(player_scene) var player = spawner.spawn() ``` -------------------------------- ### Implement and Send RPC Message in Godot Source: https://doc.photonengine.com/fusion-godot/current/getting-started/quick-start-guide Define an RPC function 'show_message' to display a message on a label and a 'send_message' function to trigger this RPC. This is suitable for one-shot events like chat messages or notifications. ```GDScript @rpc("any_peer", "call_local") func show_message(text: String): $MessageLabel.text = text func send_message(): Fusion.rpc(show_message, "Hello!") ``` -------------------------------- ### Player Movement and Authority Check (GDScript) Source: https://doc.photonengine.com/fusion-godot/current/getting-started/quick-start-guide Handles player movement input only on the client that has authority over the player object. Remote clients receive position updates via replication. The script also visually distinguishes the authoritative client's player (green) from remote clients' players (red) upon initialization. ```gdscript extends Node2D const SPEED := 200.0 @onready var sync: FusionSharedReplicator = $FusionSharedReplicator func _process(delta): if sync.has_authority(): var dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down") position += dir * SPEED * delta func _ready(): $Sprite2D.modulate = Color.GREEN if sync.has_authority() else Color.RED ``` -------------------------------- ### Subscribe to Interest Keys in GDScript Source: https://doc.photonengine.com/fusion-godot/current/manual/replication/syncing-properties Manually subscribe to area and user interest keys. Area keys should be refreshed each frame, while user keys are persistent. ```gdscript Fusion.set_area_keys([[cell_key, 0]]) # area keys (refresh each frame) Fusion.add_user_key(42) # user keys (persistent) ``` -------------------------------- ### Trigger RPC on Key Press in Godot Source: https://doc.photonengine.com/fusion-godot/current/getting-started/quick-start-guide Extend the _process function to send an RPC message when the 'E' key is pressed, but only on the authoritative client. This allows for user-initiated RPC events. ```GDScript if Input.is_key_pressed(KEY_E): send_message() ``` -------------------------------- ### Runtime App ID Override Source: https://doc.photonengine.com/fusion-godot/current/manual/connection Use this when the App ID is determined at runtime. Must be called before connecting to Photon. ```gdscript # Runtime override — must be called before connect_to_photon() Fusion.set_app_id("my-runtime-app-id") ``` -------------------------------- ### Disconnect from Photon Source: https://doc.photonengine.com/fusion-godot/current/manual/connection Call this function to cleanly leave the current room and close the Photon Cloud connection. ```gdscript Fusion.disconnect_from_photon() ``` -------------------------------- ### Claim/Release Authority (Transaction Mode) Source: https://doc.photonengine.com/fusion-godot/current/manual/replication/ownership-modes Use `want_authority(true)` to claim ownership when interacting with an object and `want_authority(false)` to release it when done. This is typical for the Transaction ownership mode. ```GDScript # Pickup / vehicle pattern func _on_interact(player): $FusionSharedReplicator.want_authority(true) # claim when interacting func _on_exit(player): $FusionSharedReplicator.want_authority(false) # release when done ``` -------------------------------- ### Send RPC to Specific Player Source: https://doc.photonengine.com/fusion-godot/current/manual/rpcs/basics Use `Fusion.rpc_to_player()` to target a single player by their numeric ID. This is useful for direct communication with a specific client. The player ID must be greater than 0. ```gdscript Fusion.rpc_to_player(player_id, my_method, arg1, arg2) ```