mteb/FreshStackRetrieval huggingface dataset:
(new here) Following a tutorial, this is a platformer game and they made a system where the level.gd can work on all levels although that doesn't work in my case the player doesn't collide with deathzone or ending collision shapes. so it doesn't emit the signals and basically, my game becomes unplayable, I thought it was an engine error so I made this project in Godot 4.0.3 but even now loading in 4.1.1 the problem is the same maybe its something as simple as doing something from inspector tab but I don't know
heres my level.gd
# same script is used on all my lvls 
extends Node2D

@export var next_level: PackedScene = null

@onready var start = $Start
@onready var exit = $Exit
@onready var deathzone = $deathzone
var player = null

func _ready():
    
    player = get_tree().get_first_node_in_group("player")
    if player!=null:
        player.global_position = start.get_spawn_pos()
    var traps = get_tree().get_nodes_in_group("traps")
    for trap in traps:
        # trap.connect("touched_player", _on_trap_touched_player)
        trap.touched_player.connect(_on_trap_touched_player)
    
    exit.body_entered.connect(on_exit_body_entered)
#   deathzone.body_entered.connect(_on_deathzone_body_entered)
#   deathzone.connect("body_entered", _on_deathzone_body_entered)
    deathzone.body_entered.connect(_on_deathzone_body_entered)

func _process(delta):
    if Input.is_action_just_pressed("quit"):
        get_tree().quit()
    elif Input.is_action_just_pressed("reset"):
        get_tree().reload_current_scene()


func _on_trap_touched_player():
    reset_player()

func _on_deathzone_body_enetered():
    reset_player()

func reset_player():
    player.velocity = Vector2.ZERO
    player.global_position = start.get_spawn_pos()

func on_exit_body_entered(body):
    if next_level != null:
        if body is Player:
            exit.animate()
            player.active = false
            await get_tree().create_timer(1.5).timeout
            get_tree().change_scene_to_packed(next_level)

func _on_deathzone_body_entered(body):
    reset_player()


main LVL NODE OREDR
LVL2 Node order
I did try to reloading project or making the simple death zone scene again but its always like from which lvl I create the deathzone it works, so instead of saving brach as a scene I created its scene separately so now it works in other lvls but doesn't work in main lvl on other hand the exit part only work for main scene the other spike trap and saw traps are not working on other scenes as well
one thing that I noticed that all the nodes that are not working are all area2d or have area 2d inside their scene (obv) since it looks like a collision problem
any info on this would be appreciated
I'm currently following this tutorial / resource:  https://github.com/amzker/Gsheet_Godot
This outputs data sent from a Godot program to a sheet that looks like this,




GreekAlphabet
WhatHungryDogDo
BananasGoodFor
HowManyWords




Alpha
The
Bananas
These


Beta
Hungry
Are
Are


Delta
Dog
Nice
Four


Gamma
Eats
Snacks
Words




My goal is to upload data to a Google Sheet from Godot in a format that resembles this,













GreekAlphabet
Alpha
Beta
Delta
Gamma


WhatHungryDogDo
The
Hungry
Dog
Eats


BananasGoodFor
Bananas
Are
Nice
Snacks


HowManyWords
These
Are
Four
Words




The relevant apps script code is as follows:
function json(sheetName) {
  const spreadsheet = SpreadsheetApp.openById("1h_KlXz9IWt2MtQQWYUSk4FJbIr02MbfXWU3ZRqY7U3I") //CHANGE WITH YOUR SHEET ID ( see url of you sheet d/)
  const sheet = spreadsheet.getSheetByName(sheetName)
  const data = sheet.getDataRange().getValues()
  const jsonData = convertToJson(data)
  return ContentService
        .createTextOutput(JSON.stringify(jsonData))
        .setMimeType(ContentService.MimeType.JSON)
}
function convertToJson(data) {
  const headers = data[0]
  const raw_data = data.slice(1,)
  let json = []
  raw_data.forEach(d => {
      let object = {}
      for (let i = 0; i < headers.length; i++) {
        object[headers[i]] = d[i]
      }
      json.push(object)
  });
  return json
}
function doGet(params) {
  const sheetname = params.parameter.sheetname
  return json(sheetname)
}

function doPost(params) {
  const datee = params.parameter.date
  const timee = params.parameter.time
  const catee = params.parameter.cate
  const amounte = params.parameter.amount
  const desce = params.parameter.desc
  const sheetname = params.parameter.sheetname

  
  if(typeof params !== 'undefined')
  Logger.log(params.parameter);

  var ss  = SpreadsheetApp.openById("1h_KlXz9IWt2MtQQWYUSk4FJbIr02MbfXWU3ZRqY7U3I") //CHANGE WITH YOUR SHEET ID ( see url of you sheet d/)
  var sheet = ss.getSheetByName(sheetname)
  var Rowtoenter = sheet.getLastRow()+1
  sheet.appendRow([datee,timee,catee,amounte,desce])
  

/* 
  var datecol = sheet.getRange(Rowtoenter,1)
  var timecol = sheet.getRange(Rowtoenter,2)
  var catecol = sheet.getRange(Rowtoenter,3)
  var amountcol = sheet.getRange(Rowtoenter,4)
  var descol = sheet.getRange(Rowtoenter,5)
  
  datecol.setValue(datee)
  timecol.setValue(timee)
  catecol.setValue(catee)
  amountcol.setValue(amounte)
  descol.setValue(desce)
*/
  
}

When the data leaves Godot, it's in the form of a URL with a string of parameters appended.

date=TODAY&time=NOW&cate=CATE&amount=AMOUNT&desc=DESC&flibble=SPONDS&sheetname=Sheet1

Once it reaches Sheets, it's converted into the first kind of table, where I really want it to appear as the second kind of table. =/
I'm trying to wade through the source and read through the Docs (https://developers.google.com/apps-script/reference/spreadsheet/sheet) but I'm very new to working with JSON and I'm finding it hard to get a starting point.
Any thoughts appreciated!
(https://i.sstatic.net/EY0Yl.png)
(https://i.sstatic.net/kASx9.png)
Consider a control that behaves as a decorator to user provided controls, like a window frame. I want my control to have all the common logic of the window (title bar, draggable window borders, buttons to hide the window, etc) and any time it's instanced in the main scene I want it to "eat" any of its node children and place them into a container of my choice.
This is the control I made, and the LinesContainer container is where I want any of its children to reside:
 
And just to be absolutely clear what I mean, when it's instantiated into a scene as below, I want its children (the label, in this case) to behave as if they were children of the LinesContainer node instead:

If you are familiar with .Net XAML at all, this is what the ContentPresenter tag does in a control, it "eats" the Content property of the entire control (ie, the children of the control instance, as above) and displays it inside that tag, allowing me to create anything I need around it (or behind it, or over it, etc).
Is there anything built-in like ContentPresenter? Or if not, how would I go about making something of my own? If possible, that also works correctly in the editor, allowing me to add and remove items as I need and have them layout correctly.
My buttons are displayed (show method) after a short pause, and if I hover the mouse cursor over the position where the button will be and leave it, the button will not realize that it is hovered. This is fixed when moving the mouse, but I really want to fix this little problem.
I used base signals mouse_entered() and mouse_exited()
After show() buttons must understand is mouse in or not. That's all(
I am making a third person game in godot4, and my third person camera has been flipping around when I drag my mouse up. How do I make it so that it sticks there and not allow it to flip over like other third person games?
My code right now (for player movement and camera):
extends RigidBody3D

@onready var horizontal_pivit = $HorizontalPivit
@onready var vertical_pivit = $HorizontalPivit/VerticalPivit

var mouse_sensitivity := 0.001
var horizontal_input := 0.0
var vertical_input := 0.0

func _ready() -> void:
   Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)


func _process(delta) -> void:
   var input := Vector3.ZERO
   input.x = Input.get_axis("left", "right")
   input.z = Input.get_axis("forward", "backward")
   
   apply_central_force(input * 1200.0 * delta)
   
   horizontal_pivit.rotate_y(horizontal_input)
   vertical_pivit.rotate_x(vertical_input)



func _unhandled_input(event: InputEvent) -> void:
   if event is InputEventMouseMotion:
       if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
           horizontal_input = -event.relative.x * mouse_sensitivity
           vertical_input = -event.relative.y * mouse_sensitivity

my player scene:
I wrote Python code on a Raspberry Pi that sends data when the sound sensor is triggered. when I connect to it using Python script everything works fine but for some reason Godot 4 doesn't recognize buttons pressed through t keyboard.press_and_release() so I thought about making the connection directly in Godot's gdscript. For some reason, the status is always connecting even when the serverside says it is connected.
I'm using WebSocketPeer in GDScript to connect to the URL. if there are any alternatives I would love some advice or maybe just a way to register the responses received by the py script as Godot input
Solution
i created a global file that connects to the pi server when the game starts:
extends Node

var players = []
var scene
const port = 8880
var ip = "192.168.4.1"
var connection 

func _ready():
    connection = StreamPeerTCP.new()
    connection.connect_to_host( ip,port )

then I just use the responses and simulate buttons where I need:
func _process(delta):
    GameData.connection.poll()
    
    var state = GameData.connection.get_status()
    
    if GameData.connection and state == GameData.connection.STATUS_CONNECTED:
        if GameData.connection.get_available_bytes() > 0:
            var s = GameData.connection.get_utf8_string(GameData.connection.get_available_bytes())
            print(str(s))
            if str(s) == "1":
                Input.action_press("1")
            elif str(s) == " ":
                Input.action_press("space")
I have been following this tutorial on creating a Character Movement System where I ran into a problem related to signals. I was trying to have Spikes Node2D with an Area2D child send a signal when a body entered its CollisionShape2D. I was successfully able to connect the signal to the Spikes Node2D and I Ctrl + C the receiver method then added it to Spike Script.
private void _on_area_2d_body_entered()
{
    GD.Print("Body has entered");
}

On VS, it says that there is 1 reference to the receiver method, though I cant seem to access the code where it is called. That being said, whenever my Player CharacterBody2D passes through the Spikes' Sprite2D, which is perfectly aligned with the CollisionShape2D, I get the following debug error:
emit_signalp: Error calling from signal 'body_entered' to callable:
'Node2D(SpikeTrap.cs)::_on_area_2d_body_entered': Method not found.

I followed the tutorial, and the guy added object body as parameters in the method. When I did the same, I got no references to my method. I have no clue what is going wrong here.
I watched that part in the video multiple times, and I searched through google and the Godot documentation to no avail.
i make loop, but it stop main loop. Help plz
extends Area2D


@onready var sprite = $Sprite
@onready var audio = $Audio
@onready var body = $Body
var rock = false


func disable_stone(player, stone_thread):
    stone_thread.start(await disable(player, stone_thread))

func disable(player, stone_thread):
    if !rock:
        print("super")
        rock = true
        await get_tree().create_timer(0.5).timeout
        body.colbox.disabled = true
        sprite.modulate.a8 = 100
        audio.play()
        await get_tree().create_timer(2).timeout
        while !(player in get_overlapping_areas()): pass
        body.colbox.disabled = false
        sprite.modulate.a8 = 255
        rock = false
    stone_thread.wait_to_finish()


I spawn thread. I dont know how fix that. I trying all thats i know.
For a game I'm working on, I wanted to make a ring of cannons, and attach to these cannons a node that controls their logic (e.g, what cannons shoot when, what they fire, etc). I want this node to be extremely flexible, so that all I have to do is write a new function for the logic in some sub node, and then when the subnode is ready it will emit a signal, passing a list of all of the functions created up to the central node, which will then decide which function to use based on properties, user input etc.
In order to ensure correctness when creating each function, I was hoping to create some sort of "prototype", which basically dictates that all functions in a node needs to follow a specific set of rules, e.g, they must all take an arg of a list of Cannon objects, and an index, and all must return a list of Cannon objects. I was wondering if there is anything within the Godot framework that would allow for this. Effectively an interface, but for multiple functions within a node.
An interface would also allow me to more easily call references to the function in the parent node, since I don't have to worry about ensuring the correctness of my calls.
The closest thing I have found to this would be using a class with nodes, but that requires creating a new node for every function, which sounds messier than just having one central script that contains them all.
I want to fill my array with loaded scenes of rooms in godot 4.1.1. So i created func to check whether they exist or not. If they exist then append to array, if not exist then break the loop. So when i run script i get error in debugger like this scene does not exist and failed to loading. Is it good? or there are any other ways to check whether scene exist or not? Im new to godot
func get_room_array():
    var i = 1
    while true:
        if load(get_room_path(i)) != null:
            room_array.append(load(get_room_path(i)))
        else:
            break
        i+=1
Within Godot, I am attempting to create a function that would basically dynamically create a property list based on the children nodes (to allow maximum composition).
Currently though, I am stuck on one single issue. When I updated the _get_property_list, I don't want to have to hard code a variable to store an int for an enum for every single node. Instead, I want the variables for each node to be created dynamically, i.e., I don't know what variables I will be using within the class until I run the editor.
I tried making a dictionary that will hold all of the variables, but when I overrided the _get and _set funcs as follows:
func _get(key):
return propertyHolder[key]
func _set(key, value):
propertyHolder[key] = value
I got never ending errors, which tells me that I've gotten something wrong. I couldn't find any _get_variable_list funcs, like the _get_method_list, and so I am stuck. I also considered each node holding their own variable locally and passing it to the parent, but I ultimately ran into the same issue that since the number of nodes is dynamic, I somehow need to dynamically receive these nodes in the parent class.
Any advice would be much appreciated.
Following this tutorial (its a bit back in Godot 3) and I have run into some issues with PhysicasRayQueryParameters2D. Here is the code from the video:
if (ableToShoot)
{
    var spaceState = GetWorld2D().DirectSpaceState;
    Godot.Collections.Dictionary result = spaceState.IntersectRay(this.Position, player.Position, new Godot.Collections.Array {this} );

    if (result != null)
    {
        if (result.Contains("collider"))
        {
            if (result["collider"] == player)
            {
                GD.Print("Shooting");
                ableToShoot = false;
                shootTimer = shootTimerReset;
            }
        }
    }
}


And here is my code:
if (ableToShoot)
{
    var spaceState = GetWorld2D().DirectSpaceState;
    //Change 1
    var query = PhysicsRayQueryParameters2D.Create(this.Position, player.Position);
    query.Exclude = new Godot.Collections.Array<Rid> {  };
    query.CollisionMask = 1;
    Godot.Collections.Dictionary result = spaceState.IntersectRay(query);

    if (result != null)
    {
        if (result.ContainsKey("collider")) //Change 2
        {
            if (result["collider"] == player) //Error Message
            {
                GD.Print("Shooting");
                ableToShoot = false;
                shootTimer = shootTimerReset;
            }
        }
    }

The code from the video is obviously different due to the changes form Godot 3 to 4. However, I am not entirely sure if the corrections/changes I have made are the correct ones. I am still new to both C# and Godot. I marked the two places I made changes so that it is easier to compare. My main issue however is that I keep getting an error message where it says result["collider"] == player.
That is how it was in the tutorial, and I did it myself but I get an error when I do, saying that I cannot use the '==' opperators when applyed to a Variant and PlayerController(a class from a different script). I tried casting result into a PlayerController, but once the tile's started blocking between me and the enemy I started getting error messages saying that I cannot convert Godot.TileMap to Godot.PlayerController. What should I do instead? And are there any other mistakes I have made when translating the code?
I looked over many reddit forms and the Godot documentation but I could not get over that last error.
Hey I am trying to make a 2D platformer with sprite animations, but I keep getting this error "Invalid get index 'flip'(on base: 'AnimatedSprite2D')". This is my code, does anyone have a idea of what im doing wrong?
I was expecting the player to move to the left without the game chrasing.
extends CharacterBody2D

const SPEED = 300.0
const JUMP_VELOCITY = -400.0

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
@onready var anim = get_node("AnimationPlayer")

func _physics_process(delta):
if not is_on_floor():
velocity.y += gravity * delta

if Input.is_action_just_pressed("ui_accept") and is_on_floor():
    velocity.y = JUMP_VELOCITY
    anim.play("Jump")

var direction = Input.get_axis("ui_left", "ui_right")
print(direction)
if direction == -1:
    get_node("AnimatedSprite2D").flip.h = true
elif direction == 1:
    get_node("AnimatedSprite2D").flip.h = false
    
if direction:
    velocity.x = direction * SPEED
    if velocity.y == 0:
        anim.play("Run")
    
    velocity.x = move_toward(velocity.x, 0, SPEED)
    if velocity.y == 0:
        anim.play("Idle")
        
    if velocity.y > 0:
        anim.play("Fall")

move_and_slide()
I am using Godot 4.1. I want to add a property via a script export to my node3d that has translation and rotation tools in the inspector, exactly like a Node3D's existing Transform property.
This is what I want to achieve:

Precisely, I want an X, Y, Z position field, followed by a X, Y, Z Rotation field (ideally with the little sliders too). I would not mind also having the Scale, Rotation Edit Mode, etc either, if it makes the solution easy to achieve.
I have tried adding a Transform3D, but that exposes a transformation matrix, which is not the desired control:


How can the desired controls be achieved?
I am new to Godot 4, I am transferring from Unity. In my game the player controls a spaceship, which is followed by a camera. After getting the input, I update the player's velocity and rotation. However, I do not like when the camera mirrors exactly the player's rotation so I added a lerp in the player's script to control the camera's rotation. The player setup looks like this:
Player
   Marker3D
       Camera


And the lines of code in the player's script that move and rotate the camera:
Marker3D.position = Marker3D.position.lerp(playerbody.position,.5)
Marker3D.rotation = Marker3D.rotation.lerp(playerbody.rotation,.3)

This works great to make the camera follow the player, except when the player turns 180° in any direction, when the camera jumps to the current player's current rotation instead of smoothly transitioning. Is there any way to fix this? Thanks!
I used ChatGPT to generate a script as I cannot code very well yet
it does not know Godot 4 even exists yet so it gives me Godot 3 code,
I fixed a lot of things that don't work in Godot 4 and found newer equivalents that will work but this is the one thing I can't figure out at all.
This is the snippet of my script I believe is broken:
extends CharacterBody3D

# Structure to represent an inventory slot
class InventorySlot:
    var background: TextureRect
    var item_icon: TextureRect

    # Constructor for InventorySlot
    func _init():
        background = TextureRect.new()
        item_icon = TextureRect.new()

# Container for inventory slots
class InventorySlotContainer(Node):
    var inventory_slots: Array[InventorySlot]

    # Constructor for InventorySlotContainer
    func _init():
        inventory_slots = []

    # Function to add an inventory slot
    func add_inventory_slot():
        var slot = InventorySlot.new()
        inventory_slots.append(slot)
        add_child(slot.background)
        add_child(slot.item_icon)

# Declare the inventory container
var inventory_container: InventorySlotContainer

@onready var inventory_slot_container = InventorySlotContainer.new()

# Declare the inventory slots
var inventory_slots: Array[InventorySlot]


I have tried changing lots of things but to no avail
I get these errors:
Line 14:Expected ":" after class declaration.
Line 14:Unexpected "(" in class body.
Line 15:Unexpected "Indent" in class body.
Line 29:Expected end of file.
In my project, I have an Area2D. I want to perform some actions if a CharacterBody2D I created overlaps it.
I am thinking of using the body_entered signal to do this. I connected the signal, but how do I determine which character body triggered the signal? I have multiple character bodys in the scene and only one can trigger this action on overlap.
Godot's documentation of its SizeFlags mentions for the three "shrink-like" flags SIZE_SHRINK_BEGIN, SIZE_SHRINK_CENTER, and SIZE_SHRINK_END:

It is mutually exclusive with SIZE_FILL and other shrink size flags, but can be used with SIZE_EXPAND in some containers.

Combining "shrink" with "expand" sounds counter-intuitive.
What would be an example of such a use case, i.e., which containers do allow this combination and is there a common semantic what "shrink and expand" should mean?
I am writing a plugin for custom import assets from OS. I pick assets on disk and copy them to Godot project structure. Then I need to trigger generating .import file for the imported images, but I cannot see any way to do it from code.
I know there is a way of writing own import plugin and import assets from Godot IDE but I prefer to do the task by standalone separated plugin.
Found EditorImportPlugin class but it does not do what I am looking for.
I am trying to set up my game to play a specific song during a match, and then switch to different songs at the end depending on which character won (those being just placeholders here for now).  I have this code in a script that I plan to call methods from in the script for the main game loop as needed:
extends AudioStreamPlayer

class_name Sounds

enum CURRENT_SONG {MATCH, CHAR1, CHAR2}

@onready var matchMusic: AudioStreamPlayer = $MatchMusic

func playMusic(song := CURRENT_SONG.MATCH) -> void:
    match song:
        CURRENT_SONG.MATCH:
            matchMusic.play()
        CURRENT_SONG.CHAR1:
            pass
        CURRENT_SONG.CHAR2:
            pass

I have an AudioStreamPlayer node in the scene tree named "MatchMusic" with a placeholder song attached.
I watched this tutorial, where something similar to what I'm doing above worked, and changed things around to attach sound playback to certain steps in the gameplay loop instead of just clicking a button.  Instead, when I attempt to run my game, I get the error "Cannot call method 'play' on a null value."
I tested commenting out the matchMusic.play() method, replacing it with a print statement, and running it then, to make sure it's not just a problem with how I'm trying to call my playMusic() function somehow- that part seems to be working fine.