Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

Script inherits from native type 'CharacterBody3D', so it can't be assigned to an object…

  1. User

    Script inherits from native type 'CharacterBody3D', so it can't be assigned to an object of type: 'Node3D'

    extends CharacterBody3D class_name Player3D enum State { IDLE, RUN, JUMP, ATTACK } var state = State.IDLE

    @export var movement_data : MovementData @export var stats : Stats

    References

    @onready var animation_tree : AnimationTree = $AnimationTree @onready var animation_state : AnimationNodeStateMachinePlayback = animation_tree.get("parameters/playback")

    func _ready(): animation_tree.active = true stats.health = stats.max_health

    func _physics_process(delta): process_movement_input(delta) process_gravity(delta) process_actions()

    # Move and slide with snap when on floor, else without snap
    var snap = Vector3.DOWN * 20 if is_on_floor() else Vector3.ZERO
    move_and_slide()
    update_animation_state()
    

    func process_gravity(delta): if not is_on_floor(): velocity.y += movement_data.gravity * movement_data.gravity_scale * delta else: velocity.y = -0.01 # The small sinking force to keep the player snapped to the floor

    func process_movement_input(delta): var input_vector = Vector2( Input.get_action_strength("move_right") - Input.get_action_strength("move_left"), -(Input.get_action_strength("move_back") - Input.get_action_strength("move_forward")) ).normalized()

    if input_vector.length() > 0:
    	var direction = global_transform.basis * Vector3(input_vector.x, 0, input_vector.y)
    	direction = direction.normalized()
    	state = State.RUN
    	velocity.x = direction.x * movement_data.max_speed
    	velocity.z = direction.z * movement_data.max_speed	
    	look_at(global_transform.origin + direction, Vector3.UP)  # Rotate the player to face the direction of movement
    else:
    	if state == State.RUN:
    		state = State.IDLE  # When there’s no input, and we were running, switch to idle state
    	velocity.x = lerp(velocity.x, 0, movement_data.friction * delta)  # Smoothly reduce velocity to zero using linear interpolation
    	velocity.z = lerp(velocity.z, 0, movement_data.friction * delta)  # Smoothly reduce velocity to zero using linear interpolation	
    # Debug prints (optional)
    print("Input Vector: ", input_vector)
    print("Velocity: ", velocity)
    

    func process_actions(): if Input.is_action_just_pressed("jump") and is_on_floor(): perform_jump()

    if Input.is_action_just_pressed("attack"):
    	perform_attack()
    

    func perform_jump(): velocity.y = movement_data.jump_strength state = State.JUMP # Update state to JUMP when jumping is performed # Handle jump animation, sound etc.

    func perform_attack(): state = State.ATTACK # Set state to ATTACK animation_state.travel("Attack") # Add attack logic here …

    func update_animation_state(): match state: State.IDLE: animation_state.travel("Idle") State.RUN: animation_state.travel("Run") State.JUMP: if velocity.y > 0: animation_state.travel("Jump") else: animation_state.travel("Fall")

  2. Assistant

    The code you've posted is for a Godot 3D player script that extends CharacterBody3D, which seems to indicate that you are using Godot 4.0 or a more recent version, as CharacterBody3D is a type that was introduced in Godot 4.0. In previous versions (Godot 3.x), you would extend KinematicBody or KinematicBody2D for character movement.

    The error message you've provided suggests that there is an attempt to assign this script to a Node of the wrong type. You should make sure that the node you are trying to assign this script to is of the type CharacterBody3D or a compatible subclass.

    Here is the error: "Script inherits from native type 'CharacterBody3D', so it can't be assigned to an object of type: 'Node3D'"

    To fix it, follow these steps:

    1. In your Godot Scene panel, locate the node to which you want to assign the Player3D script.
    2. Make sure that this node is either a CharacterBody3D node or a node that directly inherits from CharacterBody3D.
    3. If it's not, then you will need to either change the type of the node to CharacterBody3D or add a CharacterBody3D node as a child or parent to which the script can be assigned, depending on your use case.
    4. Once the correct node type is in place, drag and drop the script onto the CharacterBody3D node, or use the Inspector to load the script onto the node manually.

    If you need further assistance or encounter other issues, please don't hesitate to ask.

  3. User

    [gd_scene load_steps=20 format=3 uid="uid://bknwcnwkvguq5"]

    [ext_resource type="Script" path="res://Scripts/Characters/Player/player3D.gd" id="1_6pgcl"] [ext_resource type="Script" path="res://Scripts/Resources/movement_data.gd" id="2_ofk25"] [ext_resource type="PackedScene" uid="uid://cjgoeugpyg7n1" path="res://prefabs/Powerups/shooting.tscn" id="3_h4lb3"] [ext_resource type="Script" path="res://Scripts/Resources/stats.gd" id="3_lcka0"] [ext_resource type="Texture2D" uid="uid://cwsyo2nlc1ij6" path="res://demo/Scenes/qdqdq.png" id="3_y5ugw"] [ext_resource type="PackedScene" uid="uid://cr6nu73ixtmqt" path="res://prefabs/Powerups/spirit_water.tscn" id="4_cm2ek"] [ext_resource type="PackedScene" uid="uid://dqtmic37ehaoq" path="res://temp_imp/_tmp_e81b26e6231c0e7a10cbe4de97e3bde47e35b8b5_e6014746489714ce1c20ef28305677173b0f24ec290d0dd3a28e5e8a00a101e1.glb" id="4_qud7j"] [ext_resource type="PackedScene" uid="uid://cxsvig1irj1y5" path="res://prefabs/Powerups/lifesteal.tscn" id="5_c6obf"] [ext_resource type="PackedScene" uid="uid://cry7wgh8tlrqd" path="res://prefabs/Powerups/floating_sphere.tscn" id="6_eygic"] [ext_resource type="PackedScene" uid="uid://bjuqvgbfyhybk" path="res://addons/kaykit_characters/Mage.glb" id="8_fob2n"]

    [sub_resource type="Resource" id="Resource_xcswl"] script = ExtResource("2_ofk25") max_speed = 80 acceleration = 500 friction = 500 gravity_scale = 0.8 jump_strength = 215 knockback_force = 250

    [sub_resource type="Resource" id="Resource_j63vp"] script = ExtResource("3_lcka0") max_health = 10

    [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_smpp8"] cull_mode = 2 no_depth_test = true shading_mode = 0 albedo_texture = ExtResource("3_y5ugw") shadow_to_opacity = true

    [sub_resource type="PlaneMesh" id="PlaneMesh_molad"] lightmap_size_hint = Vector2i(12, 12) material = SubResource("StandardMaterial3D_smpp8") size = Vector2(5, 5)

    [sub_resource type="AnimationNodeAnimation" id="AnimationNodeAnimation_fam3i"] animation = &"Walking_A"

    [sub_resource type="AnimationNodeAnimation" id="AnimationNodeAnimation_4oeam"] animation = &"Idle"

    [sub_resource type="AnimationNodeBlend2" id="AnimationNodeBlend2_fkkp7"]

    [sub_resource type="AnimationNodeBlendTree" id="AnimationNodeBlendTree_nf623"] nodes/Animation/node = SubResource("AnimationNodeAnimation_4oeam") nodes/Animation/position = Vector2(-280, 60) "nodes/Animation 2/node" = SubResource("AnimationNodeAnimation_fam3i") "nodes/Animation 2/position" = Vector2(-280, 180) nodes/walking/node = SubResource("AnimationNodeBlend2_fkkp7") nodes/walking/position = Vector2(0, 100) node_connections = [&"output", 0, &"walking", &"walking", 0, &"Animation", &"walking", 1, &"Animation 2"]

    [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_adgmg"]

    [node name="Player" type="CharacterBody3D"] collision_mask = 9 script = ExtResource("1_6pgcl") movement_data = SubResource("Resource_xcswl") stats = SubResource("Resource_j63vp")

    [node name="Camera3D" type="Camera3D" parent="."] transform = Transform3D(1, 0, 0, 0, 0.707106, 0.707106, 0, -0.707106, 0.707106, 0, 10, 10) size = 10.0 far = 100.0

    [node name="Visual" parent="." instance=ExtResource("8_fob2n")]

    [node name="Skeleton3D" parent="Visual/Rig" index="0"] transform = Transform3D(1.35142, 0, 0, 0, 1.35142, 0, 0, 0, 1.35142, 0, 0, 0) bones/1/position = Vector3(0, 0.369295, 0) bones/1/rotation = Quaternion(-1.11123e-10, 0.0431578, 2.57241e-09, 0.999068) bones/4/rotation = Quaternion(-0.550382, -0.058025, -0.644283, 0.527838) bones/5/rotation = Quaternion(2.12708e-08, -6.40352e-08, -0.504593, 0.863357) bones/7/rotation = Quaternion(-0.319448, -0.337352, 0.144722, 0.873615) bones/8/rotation = Quaternion(0.00138427, 0.00138426, -0.702006, 0.712168) bones/11/rotation = Quaternion(-0.609373, 0.0784899, 0.619068, 0.489142) bones/12/rotation = Quaternion(2.96119e-08, 5.81758e-08, 0.527415, 0.849608) bones/14/rotation = Quaternion(-0.318513, 0.312882, -0.226808, 0.86557) bones/15/rotation = Quaternion(0.00419042, 0.00493569, 0.702735, 0.711422) bones/18/rotation = Quaternion(-5.80608e-11, -0.0313417, -1.88012e-09, 0.999509) bones/21/rotation = Quaternion(0.989581, 0.0837304, 0.0787354, 0.0867202) bones/22/rotation = Quaternion(0.394131, 6.25568e-08, -2.6512e-07, 0.919054) bones/23/rotation = Quaternion(-0.621041, -0.200882, 0.0765833, 0.753717) bones/25/rotation = Quaternion(0.991437, -0.0333583, 0.0298082, 0.122683) bones/26/rotation = Quaternion(0.438342, -5.77186e-08, 3.05132e-07, 0.898808) bones/27/rotation = Quaternion(-0.647071, 0.112485, -0.02329, 0.753727) bones/28/rotation = Quaternion(3.04791e-08, 0.920355, -0.391084, -6.94849e-08) bones/29/rotation = Quaternion(0.707107, -2.29302e-07, -4.60552e-08, 0.707107) bones/30/position = Vector3(0.202182, 0.0259903, 0.205181) bones/30/rotation = Quaternion(-0.707107, -7.05285e-08, -7.05285e-08, 0.707107) bones/31/rotation = Quaternion(9.65792e-09, 1.77955e-09, 0.985719, -0.168398) bones/32/rotation = Quaternion(-1.04035e-07, 0.391084, 0.920355, -2.9526e-08) bones/34/rotation = Quaternion(1, -3.10863e-15, 1.94707e-07, -6.91739e-22) bones/36/rotation = Quaternion(0.707107, -3.82385e-08, 1.45009e-07, 0.707107) bones/37/rotation = Quaternion(-0.707107, -7.05285e-08, -7.05285e-08, 0.707107) bones/38/rotation = Quaternion(-5.83589e-09, 6.43837e-10, 0.994809, 0.101756) bones/39/rotation = Quaternion(-1.04035e-07, 0.391084, 0.920355, -2.95261e-08) bones/44/position = Vector3(0.520841, 0.769702, -0.0576374) bones/44/rotation = Quaternion(0.794627, -1.11759e-07, 0.607098, -5.96046e-08) bones/46/position = Vector3(-0.510844, 0.769702, 0.0597369) bones/46/rotation = Quaternion(-0.758253, -1.52737e-07, 0.651961, -1.11759e-08)

    [node name="Spellbook" parent="Visual/Rig/Skeleton3D" index="0"] transform = Transform3D(3.58968e-07, 0.964832, 0.262865, -0.999888, 0.0039154, -0.014369, -0.0148932, -0.262836, 0.964725, 0.577122, 0.614025, 0.238271) visible = false bone_idx = 9

    [node name="Spellbook_open" parent="Visual/Rig/Skeleton3D" index="1"] transform = Transform3D(3.58968e-07, 0.964832, 0.262865, -0.999888, 0.0039154, -0.014369, -0.0148932, -0.262836, 0.964725, 0.545486, 0.615754, 0.122164) visible = false bone_idx = 10

    [node name="1H_Wand" parent="Visual/Rig/Skeleton3D" index="2"] transform = Transform3D(-0.00296098, -0.162626, 0.986683, 0.999923, -0.0122886, 0.000974851, 0.0119668, 0.986611, 0.16265, -0.490441, 0.622263, 0.107036) visible = false bone_idx = 16

    [node name="2H_Staff" parent="Visual/Rig/Skeleton3D" index="3"] transform = Transform3D(-0.00296098, -0.162626, 0.986683, 0.999923, -0.0122886, 0.000974851, 0.0119668, 0.986611, 0.16265, -0.490441, 0.622263, 0.107036) visible = false bone_idx = 17

    [node name="2H_Staff" parent="Visual/Rig/Skeleton3D/2H_Staff" index="0"] transform = Transform3D(0.999837, -0.0179838, 0.00164115, 0.0179498, 0.999662, 0.0188559, -0.00197948, -0.0188236, 0.999821, 0.427177, 0.0438049, -0.315132)

    [node name="Mage_Hat" parent="Visual/Rig/Skeleton3D" index="4"] transform = Transform3D(0.99972, -0.00612019, 0.0228409, 1.39341e-09, 0.965926, 0.258819, -0.0236466, -0.258747, 0.965656, -7.48419e-09, 1.74773, -1.02479e-07) visible = false bone_idx = 19

    [node name="Mage_Hat" parent="Visual/Rig/Skeleton3D/Mage_Hat" index="0"] visible = false

    [node name="Mage_Cape" parent="Visual/Rig/Skeleton3D" index="5"] transform = Transform3D(0.996275, -5.14962e-09, 0.0862353, 5.13043e-09, 1, 4.44077e-10, -0.0862353, 1.8939e-15, 0.996275, -1.2997e-08, 1.17951, -1.01951e-07) visible = false bone_idx = 20

    [node name="Mage_Cape" parent="Visual/Rig/Skeleton3D/Mage_Cape" index="0"] visible = false

    [node name="Mage_ArmLeft" parent="Visual/Rig/Skeleton3D" index="6"] visible = false

    [node name="Mage_ArmRight" parent="Visual/Rig/Skeleton3D" index="7"] visible = false

    [node name="MeshInstance3D" type="MeshInstance3D" parent="Visual/Rig/Skeleton3D" index="8"] transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0.0539248, 1.258, 0.457847) visible = false mesh = SubResource("PlaneMesh_molad") skeleton = NodePath("../..")

    [node name="Mage_Body" parent="Visual/Rig/Skeleton3D" index="9"] visible = false

    [node name="_tmp_e81b26e6231c0e7a10cbe4de97e3bde47e35b8b5_e6014746489714ce1c20ef28305677173b0f24ec290d0dd3a28e5e8a00a101e1" parent="Visual/Rig/Skeleton3D" index="10" instance=ExtResource("4_qud7j")] transform = Transform3D(1.76647, 0, 0, 0, 1.76647, 0, 0, 0, 1.76647, 0, 1.10842, 0)

    [node name="Mage_Head" parent="Visual/Rig/Skeleton3D" index="11"] visible = false

    [node name="Mage_LegLeft" parent="Visual/Rig/Skeleton3D" index="12"] visible = false

    [node name="Mage_LegRight" parent="Visual/Rig/Skeleton3D" index="13"] visible = false

    [node name="AnimationTree" type="AnimationTree" parent="."] tree_root = SubResource("AnimationNodeBlendTree_nf623") anim_player = NodePath("../Visual/AnimationPlayer") root_motion_track = NodePath("Rig/Skeleton3D:root") parameters/walking/blend_amount = 0.0

    [node name="CollisionShape3D" type="CollisionShape3D" parent="."] transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0) shape = SubResource("CapsuleShape3D_adgmg")

    [node name="AttackCooldown" type="Timer" parent="."] autostart = true

    [node name="Shooting" parent="." instance=ExtResource("3_h4lb3")] visible = false BulletSpeed = 5.0

    [node name="SpiritWater" parent="." instance=ExtResource("4_cm2ek")] visible = false

    [node name="Lifesteal" parent="." instance=ExtResource("5_c6obf")] visible = false

    [node name="FloatingSphere" parent="." instance=ExtResource("6_eygic")] visible = false SphereDistance = 4.0

    [connection signal="timeout" from="AttackCooldown" to="." method="OnAttackTimeOut"]

    [editable path="Visual"]

  4. Assistant

    From the structure of the .tscn file, it appears that the Player node is properly set as a CharacterBody3D, which matches the type required by your player3D.gd script. This means that you should not be experiencing the error message:

    Script inherits from native type 'CharacterBody3D', so it can't be assigned to an object of type: 'Node3D'
    

    Here's the relevant section from the .tscn file for the Player node that is typed as a CharacterBody3D:

    [node name="Player" type="CharacterBody3D"]
    collision_mask = 9
    script = ExtResource("1_6pgcl")
    movement_data = SubResource("Resource_xcswl")
    stats = SubResource("Resource_j63vp")
    

    Given the information provided in your Godot scene file and assuming the error message is verbatim, there are some potential causes and solutions:

    1. Scene corruption or cached data: The Godot IDE can sometimes hold onto outdated information which can be resolved by restarting the editor or by clearing the cache.

    2. Incorrect script attachment: Double-check that the script isn't accidentally attached to a different node, perhaps through copy and pasting in the editor or an error in the scene hierarchy.

    3. IDE Bug: Sometimes, Godot's editor might bug out, displaying incorrect errors or not updating the scene properly. The traditional "turn it off and on again" — reopening the editor might fix it.

    4. Script modifications: If you have refactored or changed the base type of the script while the editor was open, it might not have updated the internal script state. Again, reloading the editor or even the entire project can refresh this.

    To troubleshoot further, try the following:

    • If you made changes to the base class of the script, ensure that you reassign the script to the node after saving the changes.
    • Close and reopen the Godot editor, as this can resolve issues related to script assignments and IDE bugs.
    • Make sure there are no other nodes in your scene that might have the player3D.gd script attached erroneously.
    • Confirm that no other scripts are interfering with the player3D.gd script import or causing a conflict.
    • If this scene file was created in an older version of Godot and later imported into Godot 4, there could have been import issues, and recreating the scene afresh in Godot 4 might solve the issue.

    In conclusion, the .tscn file content does not show an apparent issue with the types of nodes and scripts being used. Following the troubleshooting steps above should hopefully resolve the issue. If the issue persists, consider checking other parts of the project for inconsistencies and errors.

  5. User

    but the script is attached to a character3d? I don't know why it happens

  6. Assistant

    If the script is indeed attached to a CharacterBody3D node as indicated in the .tscn content you provided, but you are still getting the error, it might be due to reasons not immediately visible in the .tscn file or in the script snippet you provided.

    Here are a few additional suggestions which might help you resolve the issue:

    1. Check for External References: Make sure that there are no other references in the project that might be trying to assign the script to an incompatible node type.

    2. Validate Node Paths: Ensure that all node paths used in your script ($AnimationTree, etc.) are correct and refer to nodes that exist in your scene. Sometimes, a misconfigured node path can lead to unexpected behavior.

    3. Check the Script: Ensure that there are no errors within the player3D.gd script itself that could cause conflicts or problems.

    4. Dependencies: Verify that the script doesn't rely on other scripts or nodes that are missing or improperly configured.

    5. Godot Version Compatibility: Double-check if your Godot editor is up to date and that the project and all its assets are compatible with the version you're using.

    6. Other Scripts: Look for any other scripts in the project that might be executing before the script in question and causing the error indirectly.

    7. Reimport the Scene: If the scene was imported from another version or different source, try to reimport it, making sure that nothing was lost or corrupted during the process.

    8. Clear Script: Temporarily remove all code from the player3D.gd script (except the extends CharacterBody3D line), save it, and then see if the error persists. This will help you determine if the issue arises from the code inside the script or from somewhere else.

    9. Fresh Scene: As a last resort, you could create a new Godot scene and manually reconstruct the node setup to see if the problem was with the scene file itself.

    If none of these steps resolve the issue, you might want to ask for help in the Godot community forums or Discord channels, providing the actual project files for others to inspect. Sometimes issues like this can be very specific to the project setup and require a thorough inspection beyond just the snippets of code and scene file provided.

  7. User

    removing the animation fixed it but I can't move around still:

    extends CharacterBody3D class_name Player3D enum State { IDLE, RUN, JUMP, ATTACK } var state = State.IDLE

    @export var movement_data : MovementData @export var stats : Stats

    References

    func _ready(): stats.health = stats.max_health

    func _physics_process(delta): process_movement_input(delta) process_gravity(delta) process_actions()

    # Move and slide with snap when on floor, else without snap
    var snap = Vector3.DOWN * 20 if is_on_floor() else Vector3.ZERO
    move_and_slide()
    update_animation_state()
    

    func process_gravity(delta): if not is_on_floor(): velocity.y += movement_data.gravity * movement_data.gravity_scale * delta else: velocity.y = -0.01 # The small sinking force to keep the player snapped to the floor

    func process_movement_input(delta): var input_vector = Vector2( Input.get_action_strength("move_right") - Input.get_action_strength("move_left"), -(Input.get_action_strength("move_back") - Input.get_action_strength("move_forward")) ).normalized()

    if input_vector.length() > 0:
    	var direction = global_transform.basis * Vector3(input_vector.x, 0, input_vector.y)
    	direction = direction.normalized()
    	state = State.RUN
    	velocity.x = direction.x * movement_data.max_speed
    	velocity.z = direction.z * movement_data.max_speed	
    	look_at(global_transform.origin + direction, Vector3.UP)  # Rotate the player to face the direction of movement
    else:
    	if state == State.RUN:
    		state = State.IDLE  # When there’s no input, and we were running, switch to idle state
    	velocity.x = lerp(velocity.x, 0, movement_data.friction * delta)  # Smoothly reduce velocity to zero using linear interpolation
    	velocity.z = lerp(velocity.z, 0, movement_data.friction * delta)  # Smoothly reduce velocity to zero using linear interpolation	
    # Debug prints (optional)
    print("Input Vector: ", input_vector)
    print("Velocity: ", velocity)
    

    func process_actions(): if Input.is_action_just_pressed("jump") and is_on_floor(): perform_jump()

    if Input.is_action_just_pressed("attack"):
    	perform_attack()
    

    func perform_jump(): velocity.y = movement_data.jump_strength state = State.JUMP # Update state to JUMP when jumping is performed # Handle jump animation, sound etc.

    func perform_attack(): state = State.ATTACK # Set state to ATTACK # Add attack logic here …

    func update_animation_state(): match state: State.IDLE:

  8. Assistant

    Based on the improved code snippet you provided (where animation is temporarily removed), if you're still unable to move around, here are a few things you should check or update:

    1. Ensure Input Actions are Defined: Make sure the input actions move_right, move_left, move_forward, and move_back are defined in your project's Input Map (accessible through Project > Project Settings > Input Map). They should correspond to keypresses or other input events.

    2. Use velocity with move_and_slide: The move_and_slide function should take velocity as an argument. Update your call to move_and_slide with the velocity vector and snap vector, like this:

      move_and_slide(velocity, snap)
      
    3. Update velocity in _physics_process: You are correctly calculating the velocity in process_movement_input and process_gravity, but since you aren't updating velocity in _physics_process, it would not be utilized by move_and_slide. Amend the velocity update to be inside _physics_process or ensure it is updated each frame before being passed to move_and_slide.

    4. Check for Unintended Script Errors: Confirm that there aren't any hidden issues such as misuse of variables or other interference within process_movement_input, process_gravity, and process_actions. This can include ensuring all associated scripts (like movement_data) are correctly configured and error-free.

    5. Physics Settings: Also, make sure that the physics properties (like mass, physics material, etc.) on the CharacterBody3D node are set up properly in a way that allows movement. Extreme values or incorrect configurations can impede movement.

    6. Verify Global Transform Usage: The line look_at(global_transform.origin + direction, Vector3.UP) uses global_transform, which may cause issues if the player's transform is not being updated correctly. You might want to simply change the rotation or use transform instead.

    7. Gravity Handling: Your gravity implementation requires that movement_data.gravity and movement_data.gravity_scale are both defined and nonzero to actually apply gravity properly.

    8. Check the Snap Vector: You're using a snap vector, but you haven't included it in your move_and_slide call. If you intended to use it, pass the snap vector to move_and_slide like so:

      move_and_slide(velocity, snap, false, 4, deg2rad(45.0))
      

      Adjust the additional parameters as necessary for your game (up direction, max slopes, etc.).

    9. Empty update_animation_state Function: Although the animations have been removed, the call to update_animation_state at the end of _physics_process function is to an empty function. While this shouldn't affect movement, it's unnecessary and can be commented out for now.

    In your _physics_process method, make sure that the function calls include all the necessary logic and that they execute in the proper order to update the character's velocity vector before calling move_and_slide.

    Please apply the necessary changes and see if that resolves your issue. If not, you may need to provide more context or investigate other parts of your project setup that may be affecting movement.

  9. User

    rewrite this for me so I can move, right now it stucks in the air:

    extends CharacterBody3D class_name Player3D enum State { IDLE, RUN, JUMP, ATTACK } var state = State.IDLE

    @export var movement_data : MovementData @export var stats : Stats

    References

    func _ready(): stats.health = stats.max_health

    func _physics_process(delta): process_movement_input(delta) process_gravity(delta) process_actions()

    # Move and slide with snap when on floor, else without snap
    var snap = Vector3.DOWN * 20 if is_on_floor() else Vector3.ZERO
    move_and_slide(velocity, snap)
    
    update_animation_state()
    

    func process_gravity(delta): if not is_on_floor(): velocity.y += movement_data.gravity * movement_data.gravity_scale * delta else: velocity.y = -0.01 # The small sinking force to keep the player snapped to the floor

    func process_movement_input(delta): var input_vector = Vector2( Input.get_action_strength("move_right") - Input.get_action_strength("move_left"), -(Input.get_action_strength("move_back") - Input.get_action_strength("move_forward")) ).normalized()

    if input_vector.length() > 0:
    	var direction = global_transform.basis * Vector3(input_vector.x, 0, input_vector.y)
    	direction = direction.normalized()
    	state = State.RUN
    	velocity.x = direction.x * movement_data.max_speed
    	velocity.z = direction.z * movement_data.max_speed	
    	look_at(global_transform.origin + direction, Vector3.UP)  # Rotate the player to face the direction of movement
    else:
    	if state == State.RUN:
    		state = State.IDLE  # When there’s no input, and we were running, switch to idle state
    	velocity.x = lerp(velocity.x, 0, movement_data.friction * delta)  # Smoothly reduce velocity to zero using linear interpolation
    	velocity.z = lerp(velocity.z, 0, movement_data.friction * delta)  # Smoothly reduce velocity to zero using linear interpolation	
    # Debug prints (optional)
    print("Input Vector: ", input_vector)
    print("Velocity: ", velocity)
    

    func process_actions(): if Input.is_action_just_pressed("jump") and is_on_floor(): perform_jump()

    if Input.is_action_just_pressed("attack"):
    	perform_attack()
    

    func perform_jump(): velocity.y = movement_data.jump_strength state = State.JUMP # Update state to JUMP when jumping is performed # Handle jump animation, sound etc.

    func perform_attack(): state = State.ATTACK # Set state to ATTACK # Add attack logic here …

    func update_animation_state(): match state: State.IDLE:

  10. Assistant

    It appears that your process_gravity function is applying gravity only when the character is not on the floor. Additionally, the -0.01 sinking force applied while the character is on the floor may not be sufficient to counter any residual upward velocity.y from jumping, which could lead to getting stuck in the air due to not snapping properly to the floor.

    Let's tweak your code so the gravity is applied consistently and only cleared when on the floor. Here's the revised code:

    extends CharacterBody3D
    class_name Player3D
    enum State { IDLE, RUN, JUMP, ATTACK }
    var state = State.IDLE
    
    var velocity = Vector3.ZERO
    
    @export var movement_data : MovementData
    @export var stats : Stats
    
    func _ready():
        stats.health = stats.max_health
    
    func _physics_process(delta):
        process_movement_input(delta)
        process_gravity(delta)
        process_actions()
    
        # Move and slide with snap when on floor, else without snap
        var snap = Vector3.DOWN * 20 if is_on_floor() else Vector3.ZERO
        velocity = move_and_slide(velocity, snap, false, 4, deg2rad(45.0))
    
        update_animation_state()
    
    func process_gravity(delta):
        if not is_on_floor() or velocity.y > 0:
            velocity.y += movement_data.gravity * movement_data.gravity_scale * delta
    
        if is_on_floor() and velocity.y <= 0:
            velocity.y = 0  # Stop vertical movement when on the floor
    
    func process_movement_input(delta):
        var input_vector = Vector2(
            Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
            Input.get_action_strength("move_back") - Input.get_action_strength("move_forward")
        ).normalized()
    
        if input_vector.length() > 0:
            var basis = global_transform.basis.orthonormalized()
            var direction = basis.xform(Vector3(input_vector.x, 0, input_vector.y)).normalized()
            state = State.RUN
            velocity.x = direction.x * movement_data.max_speed
            velocity.z = direction.z * movement_data.max_speed
            look_at(global_transform.origin + direction, Vector3.UP)
        else:
            if state == State.RUN:
                state = State.IDLE  # When there’s no input, and we were running, switch to idle state
            velocity.x = lerp(velocity.x, 0, movement_data.friction * delta)
            velocity.z = lerp(velocity.z, 0, movement_data.friction * delta)
        # Debug prints (optional)
        print("Input Vector: ", input_vector)
        print("Velocity: ", velocity)
    
    func process_actions():
        if Input.is_action_just_pressed("jump") and is_on_floor():
            perform_jump()
        # Consider adding more actions here and in perform_attack as needed.
    
    func perform_jump():
        velocity.y = movement_data.jump_strength
        state = State.JUMP
    
    func perform_attack():
        state = State.ATTACK
    
    func update_animation_state():
        # Add animation logic here
    

    Key changes and reasons:

    • Introduced var velocity = Vector3.ZERO to store the character's velocity.
    • process_gravity: Now applies gravity consistently whether the character is on the floor or in the air. When the character lands (is_on_floor()), we set the vertical velocity (velocity.y) to zero.
    • process_movement_input: Fixed the order of subtraction (Input.get_action_strength("move_back") - Input.get_action_strength("move_forward")) to correctly move the character forward and back.
    • Normalized the direction vector after transforming it with the basis for consistency.
    • move_and_slide: Extended to include an up direction parameter and a slope angle which are useful for slope handling. Also, assigned its return value to velocity to reflect the adjusted velocity after the collision response.
    • Removed empty update_animation_state function since it's not being used (you'll add animation logic later as needed).

    With these fixes, your character should no longer get stuck in the air when jumping, and should properly respond to gravity and floor collisions. Remember to test the input actions and ensure they are mapped correctly in the Godot Input Map settings.

  11. User

    E 0:00:01:0869 SceneChanger.gd:8 @ change_to_3d(): Failed to load script "res://Scripts/Characters/Player/player3D.gd" with error "Parse error". <C++ Source> modules/gdscript/gdscript.cpp:2705 @ load() SceneChanger.gd:8 @ change_to_3d() player2D.gd:180 @ _on_swapPlane() player2D.gd:43 @ _physics_process()

  12. Assistant

    The error you're encountering indicates that there's a parse error within the player3D.gd script when attempting to load it. This can happen due to various reasons, including syntax errors, missing variables, incorrect file paths, among others.

    To resolve this issue, follow these steps:

    1. Open the player3D.gd file in the Godot script editor and look at the line numbers mentioned in the error message. The error indicates there is an issue on line 8 of your SceneChanger.gd script, which triggers when calling the change_to_3d() function.

    2. Check Syntax: Look for common syntax issues in your player3D.gd script that could lead to a parse error—things like missing colons, improper indentation, unmatched parentheses or brackets, incorrect use of keywords, etc.

    3. Inspect the Function Invocation: Check the function change_to_3d() in the SceneChanger.gd script. There may be an issue with how you're attempting to load the player3D.gd script. If there are errors in the method call or the filepath provided does not correspond to the actual location of the script, this error may occur.

    4. Confirm Script Path: Verify that the path provided to load the script is correct. It must be the relative path within the res:// directory of the Godot project.

    5. Check Error Location: The error is sometimes misreported as being from one script while actually originating in another. Ensure that there are no issues in both SceneChanger.gd and player3D.gd.

    Here's an example of how you might be loading the script in SceneChanger.gd that could cause such an error:

    # Incorrect way to load a script that might cause a parse error example:
    var script_path = "res://Scripts/Characters/Player/player3D.gd"
    var script_resource = load(script_path)  # potential to fail if parse error
    

    Instead, if you're trying to instantiate a node that uses the script or change scenes, make sure you do it correctly:

    # Correct way to instantiate a node from a script:
    var Player3DClass = preload("res://Scripts/Characters/Player/player3D.gd")
    var player_instance = Player3DClass.new()
    
    # Or if changing to a new scene:
    get_tree().change_scene("res://path_to_scene_that_uses_player3D.tscn")
    

    In the case of calling get_tree().change_scene(), ensure the scene file you're switching to is correctly set up and that the script paths are accurate.

    Lastly, it's worth remembering that Godot's editor provides error reporting and highlighting, which can be invaluable for locating and understanding syntax and parse issues. Follow error and warning messages, checking the problematic lines to identify and correct the issues.

  13. User

    extends Node

    Singleton for changing scenes

    func change_to_3d(player_2d_position: Vector2): # Save the 2D position if you need to retain it # Additional setup can be done here, such as setting the player’s position get_tree().change_scene_to_file("res://demo/Scenes/main_scene.tscn")

    func change_to_2d(player_3d_position: Vector3): # Save the 3D position if you need to retain it # Additional setup can be done here, such as setting the player’s position get_tree().change_scene_to_file("res://Scenes/Levels/prototype.tscn")

  14. Assistant

    Based on the provided script snippet, there are a few tweaks we need to make.

    First, the change_scene_to_file method does not exist. The correct method for changing scenes is using change_scene (which takes a string path to a .tscn file) or change_scene_to (which takes a preloaded PackedScene resource).

    The script provided as a singleton should use the correct method and pass in the file path of the scene directly. If you have set up autoload for this script to be a global singleton, here is the corrected script:

    extends Node
    
    # Singleton for changing scenes
    
    func change_to_3d(player_2d_position: Vector2):
    	# Save the 2D position if you need to retain it
    	# Additional setup can be done here, such as setting the player’s position
    	get_tree().change_scene("res://Scenes/3D/main_scene.tscn")  # Assuming the proper path
    
    func change_to_2d(player_3d_position: Vector3):
    	# Save the 3D position if you need to retain it
    	# Additional setup can be done here, such as setting the player’s position
    	get_tree().change_scene("res://Scenes/2D/prototype.tscn")    # Assuming the proper path
    

    In the above example, we use the change_scene method where you replace the file paths "res://demo/Scenes/main_scene.tscn" and "res://Scenes/Levels/prototype.tscn" with the correct paths to your 3D and 2D main scene files respectively.

    If you have a PackedScene resource that you want to preload and then change to, you can use change_scene_to like so:

    extends Node
    
    # Singleton for changing scenes
    var main_scene_3d = preload("res://Scenes/3D/main_scene.tscn")
    var main_scene_2d = preload("res://Scenes/2D/prototype.tscn")
    
    func change_to_3d(player_2d_position: Vector2):
    	# Save the 2D position if you need to retain it
    	# Additional setup can be done here
    	get_tree().change_scene_to(main_scene_3d)
    
    func change_to_2d(player_3d_position: Vector3):
    	# Save the 3D position if you need to retain it
    	# Additional setup can be done here
    	get_tree().change_scene_to(main_scene_2d)
    

    To call these functions from another script and change scenes, make sure the singleton is added to the auto-load list with a name that you can use to call it. For example:

    # Assuming the singleton is named 'SceneChanger'
    SceneChanger.change_to_3d(player_position_in_2d)
    

    Double-check the path names to ensure they match the location of your scenes within the project to avoid any Failed to set current scene errors. Also, ensure that these scene files actually exist in your project. If they don't, Godot will fail to change the scene, which could be one of the reasons why you are encountering errors.

  15. User

    E 0:00:01:0869 SceneChanger.gd:8 @ change_to_3d(): Failed to load script “res://Scripts/Characters/Player/player3D.gd” with error “Parse error”. <C++ Source> modules/gdscript/gdscript.cpp:2705 @ load() SceneChanger.gd:8 @ change_to_3d() player2D.gd:180 @ _on_swapPlane() player2D.gd:43 @ _physics_process()

    extends Node

    Singleton for changing scenes

    func change_to_3d(player_2d_position: Vector2): # Save the 2D position if you need to retain it # Additional setup can be done here, such as setting the player’s position get_tree().change_scene_to_file("res://demo/Scenes/main_scene.tscn")

    func change_to_2d(player_3d_position: Vector3): # Save the 3D position if you need to retain it # Additional setup can be done here, such as setting the player’s position get_tree().change_scene_to_file("res://Scenes/Levels/prototype.tscn")

  16. Assistant

    The error message is pointing out that there is a parse error in the player3D.gd script, and not necessarily an error in the SceneChanger.gd script. A parse error occurs when Godot tries to load or compile a script, and it encounters something it does not understand. This can be due to various syntax issues within the script, such as missing colons, incorrect indentations, or misspelled keywords, etc.

    Given that the error specifically mentions a failure to load player3D.gd, you should first address any issues in player3D.gd. Open the player3D.gd script in the Godot editor and look for red squiggly lines indicating where the error is, or try to run the scene that contains the Player3D node to trigger the script parsing and see where the error occurs.

    Once you have resolved the issues in player3D.gd, you should address the change_scene_to_file method in your SceneChanger.gd script, as that method does not exist within Godot's API. You should use change_scene() instead. Here is the corrected SceneChanger.gd script:

    extends Node
    
    # Singleton for changing scenes
    
    func change_to_3d(player_2d_position: Vector2):
    	# Save the 2D position if you need to retain it
    	# Additional setup can be done here, such as setting the player’s position
    	get_tree().change_scene("res://demo/Scenes/main_scene.tscn")
    
    func change_to_2d(player_3d_position: Vector3):
    	# Save the 3D position if you need to retain it
    	# Additional setup can be done here, such as setting the player’s position
    	get_tree().change_scene("res://Scenes/Levels/prototype.tscn")
    

    Please make sure that the paths provided in change_scene are correct and that the scenes exist at those paths in your project. If you still encounter errors, the issue likely lies within the player3D.gd script, so correct all syntax issues there. Alternatively, you might need to share the player3D.gd script content for further analysis of the parse error.

  17. User

    extends CharacterBody3D class_name Player3D enum State { IDLE, RUN, JUMP, ATTACK } var state = State.IDLE

    var velocity = Vector3.ZERO

    @export var movement_data : MovementData @export var stats : Stats

    func _ready(): stats.health = stats.max_health

    func _physics_process(delta): process_movement_input(delta) process_gravity(delta) process_actions()

    # Move and slide with snap when on floor, else without snap
    var snap = Vector3.DOWN * 20 if is_on_floor() else Vector3.ZERO
    velocity = move_and_slide(velocity, snap, false, 4, deg2rad(45.0))
    
    update_animation_state()
    

    func process_gravity(delta): if not is_on_floor() or velocity.y > 0: velocity.y += movement_data.gravity * movement_data.gravity_scale * delta

    if is_on_floor() and velocity.y <= 0:
    	velocity.y = 0  # Stop vertical movement when on the floor
    

    func process_movement_input(delta): var input_vector = Vector2( Input.get_action_strength("move_right") - Input.get_action_strength("move_left"), Input.get_action_strength("move_back") - Input.get_action_strength("move_forward") ).normalized()

    if input_vector.length() > 0:
    	var basis = global_transform.basis.orthonormalized()
    	var direction = basis.xform(Vector3(input_vector.x, 0, input_vector.y)).normalized()
    	state = State.RUN
    	velocity.x = direction.x * movement_data.max_speed
    	velocity.z = direction.z * movement_data.max_speed
    	look_at(global_transform.origin + direction, Vector3.UP)
    else:
    	if state == State.RUN:
    		state = State.IDLE  # When there’s no input, and we were running, switch to idle state
    	velocity.x = lerp(velocity.x, 0, movement_data.friction * delta)
    	velocity.z = lerp(velocity.z, 0, movement_data.friction * delta)
    # Debug prints (optional)
    print("Input Vector: ", input_vector)
    print("Velocity: ", velocity)
    

    func process_actions(): if Input.is_action_just_pressed("jump") and is_on_floor(): perform_jump()

    if Input.is_action_just_pressed("attack"):
    	perform_attack()
    

    func perform_jump(): velocity.y = movement_data.jump_strength state = State.JUMP # Update state to JUMP when jumping is performed # Handle jump animation, sound etc.

    func perform_attack(): state = State.ATTACK # Set state to ATTACK # Add attack logic here …

    func update_animation_state(): match state: State.IDLE:

  18. Assistant

    The code for the Player3D class you've posted looks syntactically correct, so if Godot is complaining about a parsing error when attempting to load the player3D.gd script file, the issue might be related to something outside of the presented code.

    Here are several steps you can take to debug the parse error:

    1. Syntax Check: Open the player3D.gd file in the Godot Script Editor and look for any syntax errors that might be indicated by red squiggle lines under the code. Although the snippet looks fine, ensure there are no issues beyond what you've posted, such as at the end of the script or before the sections shown.

    2. Syntax Error Reporting: Godot usually reports syntax errors in the Output panel at the bottom of the editor when you try to run a scene that contains the script. Check the Output panel or Debugger for more details on the nature of the parse error.

    3. Script Encoding: Verify that the script file is saved with UTF-8 encoding without BOM. File encoding issues can sometimes cause scripts to fail loading. If you suspect this issue, try recreating the script file in the Godot editor and copy-pasting the code back into it.

    4. Check Resource Classes: Ensure that the MovementData and Stats classes that you're referencing in the exported variables exist and are error-free. They should be valid resource scripts or be otherwise loadable by Godot.

    5. Script Dependencies: If the MovementData and Stats resources rely on external scripts or have missing properties that you're trying to access in Player3D, they may cause errors. Ensure these scripts are accurate and properly referenced.

    6. Try Clean Build: Sometimes Godot editor might hold onto old errors or state. Try clearing the script editor's cache or restarting the editor. If all else fails, you may want to try re-importing the project or cleaning the build by deleting the .import folder and opening the project again.

    7. Check Godot Version: Make sure that your Godot version supports all the features you are using. If you copied the script from a project that was using a different version of Godot, some functionality might not be compatible.

    8. Missing Custom Types: If you are using any custom types in your MovementData and Stats resources (like signals, enums, or other types), ensure they're declared correctly.

    If Godot cannot parse the script, it won't be able to compile it into bytecode, and thus you won't be able to run any scenes that depend on it, which in your case seems to be the 3D scene you're trying to switch to. After addressing the parsing error, update the change_scene_to_file calls in SceneChanger.gd to the correct change_scene method as previously mentioned.

  19. User

    but help me figure out the problem

  20. Assistant

    Certainly! To figure out the parsing problem with your player3D.gd script, follow these steps:

    1. Check the Complete Script: Ensure that you are examining the complete player3D.gd script. The code you posted may be correct, but there could be syntax errors elsewhere in the file.

    2. View Syntax Errors: With the player3D.gd script open in the Godot script editor, look for syntax error indicators—these usually appear as red squiggly lines beneath the problematic code. The editor should also display an error message in the script editor's bottom panel, pointing out what's wrong.

    3. Godot Output Panel: Run the scene (or the project) that includes the player3D.gd script. If there are syntax issues, the Godot editor's Output panel at the bottom will display errors pointing to the line numbers and files where the issues occurred.

    4. Go to the Error Line: Navigate to the lines indicated by the error messages to directly address the problems. Common syntax issues include typos, incorrect use of keywords, improper indentation, missing parentheses or colons, and erroneous variable declarations.

    5. Check Resource Scripts: If the MovementData or Stats classes contain errors or are missing from the file system, this would also cause parsing errors in the script that tries to utilize them. Open those scripts and verify that they are also free of syntax errors.

    6. Check Other Node Paths: If you use node paths to reference nodes in the scene tree from your script, ensure they are accurate. Incorrect node paths won't typically cause parsing errors but can result in runtime errors.

    7. Validate Exported Variables: Verify that the exported variables (@export var movement_data: MovementData and @export var stats: Stats) are pointing to resource types that exist, and make sure that MovementData and Stats are valid class names. If they are contained within separate files, ensure those files are free of errors.

    8. Check for Encoding Issues: Open your script with a text editor that can display and save file encoding (such as Notepad++ or VSCode) and make sure the file is encoded as UTF-8 without BOM. Non-standard encodings might cause the Godot script editor to fail in parsing the script.

    9. Look for Incomplete Functions: Sometimes, accidentally leaving a block of code or function incomplete (e.g., a function with a declaration but missing body or a missing end in an expression) may cause parsing errors.

    10. Recreate the Script: If you can't find any errors through the editor, try creating a new script file and copying the contents over to the new file line by line, making sure to save and check for errors after each significant addition.

    By carefully looking at these areas and following Godot's error messages, you should be able to identify and fix the script's parsing issue. If you've checked everything and still can't find the problem, you may consider posting the complete player3D.gd script here for a more in-depth review.