Search code examples
godotgdscriptgodot4

Godot 4 CharacterBody2D movement goes haywire on multiple instances


I've set up a basic player. It works when I place only one instance of it in a scene. I need two instances due to local multiplayer.

However, once I place two instances of it in a scene, it just moves out of my vision. By observing where it's positioned using a basic print function, it starts moving in random directions crazily super fast for a few seconds, and then it's movement becomes normal.

Here's my code for it.

extends CharacterBody2D

@export var speed = 100
@export var dash_speed = 300
@export var prefix = ''
var dashing = false

@export var texture: Texture2D:
    set(v): 
        $Sprite2D.set_texture(v)

func _ready():
    $CPUParticles2D.emitting = false

func get_input():
    var input_direction = Input.get_vector(prefix + "left", prefix + "right", prefix + "up", prefix + "down")
    velocity = input_direction * speed
    if Input.is_action_pressed(prefix + "dash-jump"):
        velocity += input_direction * dash_speed
        dashing = true

func _physics_process(_delta):
    get_input()
    if dashing:
        $CPUParticles2D.process_material.gravity = Vector3(-velocity.x, -velocity.y, 0) / 2
        $CPUParticles2D.restart()
    move_and_slide()
    dashing = false

I don't know if the problem's in move_and_slide or something else. Don't mind the particles, and the input prefix is so the second player can use different input actions from the first one and be independent. By the way, the texture variable exists so I can easily change it from Inspector, in case I wanna have a different sprite for player 2.


Solution

  • So I found the problem, but this is temporary until MRM posts it. My two players were colliding on start, causing this to happen.