0

I am trying to implement a car spawn system but my problem is that when a car spawns it just flies through the level at an extremely high speed. This is the spawner script :

 private void Spawn()
    {
        //Get object and check for errors
        var obj = _objectPool.GetObject();
        if(obj == null)
            return;
        //Change location and enable object 
        GD.Randomize(); //Randomize seed
        var index = (int)GD.RandRange(0, 4);
        obj.Position = new Vector2(_pos[index], _posY.GlobalPosition.y);
        obj.SetProcess(true);
        GD.Print("Spawn" + obj.GlobalPosition);
    }// I also have a timer that repeats this function 

This is the object pool script:

private void Instantiate(){
        _objects = new Node2D[_count];
        for(int i=0; i<_count; i++){
            //Instanciate object
            Node2D node =(Node2D)_scene.Instance();
            //Disable it
            node.SetProcess(false);
            //Add to scene
            AddChild(node);
            //Add to object list
            _objects[i] = node;
        }
    }

    public Node2D GetObject(){
        //Return a diactivated object
        foreach (var obj in _objects){
            if(!obj.IsProcessing())
                return obj;
        }
        return null;
    }

And finaly this is the car script:

 public override void _Ready()
    {
        GD.Randomize();
        goingUp = false;
        _speed = 10;//(int)GD.RandRange(_minSpeed, _maxSpeed);   
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(float delta)
    {
        Move(delta);
    }   

    private void Move(float delta)
    {
        var motion = Vector2.Zero;
        motion = goingUp ? Vector2.Up : Vector2.Down;
        //Apply movement
        MoveAndSlide(motion);
    }

When i am not using a spawner and just add a car to the scene manualy everything works fine.

  • As you are spawning at a random position, could it be that the position is already occupied by any collision object? The collision might result in a rapid acceleration of your car. You might want to use [`ShapeCast2D`](https://docs.godotengine.org/en/stable/classes/class_shapecast2d.html) to test if the position is already occupied and retry in a loop until you find a free spot. – zett42 Apr 05 '23 at 19:32

1 Answers1

0

When you add an object to the scene, it triggers physics. Likely when "it just flies through the level at an extremely high speed" it is as a result of a collision. Thus, give position to the object before adding it to the scene. Which also means you need to tell the position to your object pool.

Theraot
  • 31,890
  • 5
  • 57
  • 86