Hi, yes, that helps a lot! So, what I’m noticing here is that your player script does not have a way to see where the other players are, or to know which node belongs to the currently active player. Since you’ve already assigned a number to each player, a simple way to do this would be by using a dictionary. So, in your switching system, I would add a dictionary + a way to function the current player node:
extends Node
@export var is_player = 1
# I suggest a dictionary, where you use
# numbers as the keys, and nodes as the values
var player_nodes = {}
# Look up the current player's node in the dictionary
# and return it. If not found, print an error message
func get_current_player():
var player = player_nodes[is_player]
if !player:
push_error("Player " + str(is_player) + " not found.")
return player
# The _input function you can leave unchanged, it's perfectly fine
Now, we need some way to actually fill that dictionary. I suggest doing it from the player scripts:
extends CharacterBody2D
class_name Player
# It's nice to have this in a variable, since we'll now be using
# it a couple of times through the code
var player_id = 1
func _ready():
# Tell the switching system that player 1 means
# this node
IsPlayer.player_nodes[player_id] = self
The first half of the _physics_process
function is more or less unchanged (I’ve changed some 1’s to use the player_id variable instead). In the second half, I’ve added code that finds the direction towards whatever player is currently active, and moves in that direction. This is of course very simple movement, and you might need something more sophisticated, but I hope it’s a starting point you can work with.
func _physics_process(delta: float) -> void:
var direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
# I changed this line to use player_id
if IsPlayer.is_player == player_id:
if direction:
velocity = direction * SPEED * delta
else:
velocity.x = move_toward(velocity.x, 0, SPEED * delta)
velocity.y = move_toward(velocity.y, 0, SPEED * delta)
if velocity != Vector2.ZERO:
animated_sprite_2d.play_movement_animation(velocity)
else:
animated_sprite_2d.play_idle_animation()
# I changed this line to use player_id
if IsPlayer.is_player != player_id:
# Now, let's get the direction to the current player,
# and use that for our movement
var current_player = IsPlayer.get_current_player()
if !current_player: # If the player could not be found
velocity.x = 0
velocity.y = 0
else: # Yay, we found the current player! Let's move towards it
var direction_to_player = current_player.global_position - global_position
direction_to_player = direction_to_player.normalized()
velocity = direction_to_player * SPEED * delta
move_and_slide()
The code above is untested, and may have some errors, but I hope the idea is clear.