Invalid get index 'global' (on base: 'KinematicBody2D ('player.gd')) - godot

I'm trying to make the enemy bullet follow the player, but the error: invalid get index 'global' (on base: 'Kinematicbody2D ('player.gd')) always pops up. When I looked this up, I found some problems similar to mine. The solution says to check the reference, but when I checked the reference, it looked right.
func atirar():
var dog = tirim.instance()
get_tree().get_root().add_child(dog)
dog.global_position = global_position
dog.add_to_group("delete_on_restart")
dog.dir = (get_tree().get_nodes_in_group("player")[0].global.position - global_position).normalized()
func _ready():
add_to_group("player")

dog.dir = (get_tree().get_nodes_in_group("player")[0].global.position - global_position).normalized()
it's a typo, it should be global_position
dog.dir = (get_tree().get_nodes_in_group("player")[0].global_position - global_position).normalized()

Related

I have a few question about referencing and location nodes in Godot

I'm making a game that's top down and has enemies. They don't shoot just walk at you. Well there supposed too. I just can't seem to get to enemies to be able to locate the player even if the player is the parent node.
This is the code here:
extends KinematicBody2D
var health: int = 100
var motion = Vector2()
var speed = 100
func _on_Area2D_body_entered(body):
yield(get_tree().create_timer(0.1), 'timeout')
if "Bullet" in body.name:
health -= 20
if health <= 1:
queue_free()
func _physics_process(delta):
var Player = get_parent().get_node("Player")
position += (Player.position - position)/50
look_at(Global.player.global_position)
move_and_collide(motion)
but all I get from this is an error saying: Invalid get index 'position' (on base: 'null instance').
I don't understand what's going here. So far I've had to make the Player the parent but I also need to make it the main scenes parent so I can instance it so there are multiple of them. That's literally impossible in Godot standards. another question is I'm trying to make the enemies spawn around a moving camera but all they do is go to one corner.
My code is as showed in a camera 2d :https://youtu.be/klBvssJE5Qg
extends Node2D
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
var normal_zombie = preload("res://scenes/Enemy.tscn")
var player = null
func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)
Last problem I'm facing is that I made it so the zombies had 100 health and would die at 0. Whenever a bunch spawn(ed) (I tried fixing it but ended up making it worse) and I killed 2 at the same time it would just crash. The codes here.
func _on_Area2D_body_entered(body):
yield(get_tree().create_timer(0.1), 'timeout')
if "Bullet" in body.name:
health -= 20
if health <= 1:
queue_free()
If you read all of this your a legend. If you helped me out with all the questions I would've given you boba tea. To bad I don't know where you live and can't send it to you. Please someone answer :3
UwU
I have looked up many many ways to do it. I only use stack overflow if it's my last hope. Please help!!!
Before looking at anything else, you say you have this error:
Invalid get index 'position' (on base: 'null instance')
This is not hard to understand. You have a null and you are trying to get position of it.
And looking at the code, that got to be here:
func _physics_process(delta):
var Player = get_parent().get_node("Player")
position += (Player.position - position)/50
look_at(Global.player.global_position)
move_and_collide(motion)
More precisely, here:
position += (Player.position - position)/50
So Player is null. So this get_parent().get_node("Player") gave you null.
Please notice that get_parent().get_node("Player") is looking for a sibling. It literally wants to get a child called "Player" from the parent. A child from the parent. A sibling.
I'll also point out that get_parent().get_node("Player") is equivalent to get_node("../Player") which is equivalent to $"../Player". If you need to put the Player somewhere else, update the path accordingly.
Let us break this code down:
extends Node2D
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
var normal_zombie = preload("res://scenes/Enemy.tscn")
var player = null
func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)
First of all, here you are taking a copy of these values when the Node is ready:
onready var camera_x = $Player/playercamera.global_position.x
onready var camera_y = $Player/playercamera.global_position.y
And second I don't see you update them or use them.
I would, instead have a reference to the camera. Which assuming these lines are correct would be like this:
onready var camera = $Player/playercamera
Which means that the Player is a child of this Node, and playercamera is a child of Player. If you need to put the camera somewhere else, you can update the path accordingly.
Then (I assuming the indentation problem was when posting the code here), you have this:
func _on_Timer_timeout():
var enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
while enemy_position.x < 510 and enemy_position.x > -510 and enemy_position.y < 310 and enemy_position.y > -310:
enemy_position = Vector2(rand_range(-510, 310), rand_range(510, -310))
var normal_zombie_instance = normal_zombie.instance()
normal_zombie_instance.position = enemy_position
add_child(normal_zombie_instance)
You are using position, which as I said in the other answer is relative to the parent. And the parent is not not the camera. Quite the opposite, the camera is a child of the Player, which is a child of this Node.
Instead set the global_position (or the global_transform.origin if you prefer) to camera.to_global(enemy_position) (where camera is the reference to the camera).
In the other answer mentioned to use camera.to_global if the camera was not the parent but you had a reference to it. You are not forced to make it a parent.
Note: The global_position is not relative to the parent, but to the world.
And about the crash (also assuming the indentation problem was posting the code here), you have this:
func _on_Area2D_body_entered(body):
yield(get_tree().create_timer(0.1), 'timeout')
if "Bullet" in body.name:
health -= 20
if health <= 1:
queue_free()
I want you to imagine the following scenario:
A first body enters.
The execution for the first body reaches yield.
After the timeout the execution for the first body resumes and reaches queue_free.
A second body enters, the same frame that queue_free was called.
The execution for the second reaches yield.
Godot frees the Node (because you had called queue_free).
After the timeout… Eh? Godot cannot resume the execution for the second body because the Node was freed.
That is not the only way it can happen. It is just the easier to explain because it is the most sequential scenario. It could also be something like this:
A first body enters.
The execution for the first body reaches yield.
A second body enters.
The execution for the second reaches yield.
After the timeout the execution for the first body resumes and reaches queue_free.
Godot frees the Node (because you had called queue_free).
After the timeout… Eh? Godot cannot resume the execution for the second body because the Node was freed.
I bring this up because the way I described it earlier might suggest to you that you can avoid this problem simply by using is_queued_for_deletion but that is not the case.
Even if you were to fix that for this method, anything else that was pending in yield when the Node was freed would be an issue. Thus, you have two solutions:
Don't call queue_free unless you know nothing is pending in yield.
Don't use yield.
There are gotchas and caveats. I'll point you to Are Yields a Bad Code Practice in GDScript?.
I'll side on not using yield in this case. So my fix would be like this:
func _on_Area2D_body_entered(body):
get_tree().create_timer(0.1).connect("timeout", self, take_damage, [20])
func take_damage(amount) -> void:
health -= amount
if health <= 1:
queue_free()
In principle it is the same idea. You are creating a timer, and when the timer emits the "timeout" signal it will execute some code. The difference is that we didn't use yield, instead we connected to the signal, and when a Node is freed Godot disconnect any signals it might have connected.
I have said a couple times that you can update a path according to where the Nodes are relative to each other. You could also export a NodePath which I also mentioned in the other answer and set it via the inspector. For the camera example, it could be like this:
export var camera_path:NodePath
onready var camera = get_node(camera_path)
With the caveat that, as I mentioned earlier, the value of the onready variable is a copy taken when the Node is ready. So, changing the camera_path in runtime won't update the camera, you could handles that using setget if you need to.
I am going to, once more, point you to Nodes and scene instances, and see the documentation on NodePath too.

Invalid set index 'startDirection' (on base: 'KinematicBody2D(Enemy.gd)') with value of type 'Vector2'

I am making a Godot platformer game and made a respawn enemy script. I expected it to work perfectly fine, but something unexpected happened. when I ran the game, a error showed up, and it went like this:
Invalid set index 'startDirection' (on base: 'KinematicBody2D(Enemy.gd)') with value of type 'Vector2'. I spend 20 minutes trying to figure out what the issue was, butIi have absolutely
no clue. Here is the script:
extends Position2D
enum Direction { RIGHT, LEFT }
export(PackedScene) var enemyScene
export(Direction) var startDirection
var currentEnemyNode = null
var spawnOnNextTick = false
func _ready():
# warning-ignore:return_value_discarded
$SpawnTimer.connect("timeout", self, "on_spawn_timer_timeout")
call_deferred("spawn_enemy")
func spawn_enemy():
currentEnemyNode = enemyScene.instance()
currentEnemyNode.startDiretion = Vector2.RIGHT if startDirection == Direction.RIGHT else Vector2.LEFT
get_parent().add_child(currentEnemyNode)
currentEnemyNode.global_position = global_position
func check_enemy_spawn():
if(!is_instance_valid(currentEnemyNode)):
if(spawnOnNextTick):
spawn_enemy()
spawnOnNextTick = false
else:
spawnOnNextTick = true
func on_spawn_timer_timeout():
check_enemy_spawn()
I would appreciate some help!

GameMaker Studio 2; Weapon System. Error: DoConv :1: illegal undefined/null use; how to fix it?

Im trying to implement a weapon switching system in GameMaker Studio 2 and I'm following a tutorial to do so since I'm not too experienced with GML.
When I'm trying to run this script I'm getting the following error, and I can't find a way to get it to work.
############################################################################################
ERROR in
action number 1
of Create Event
for object :
DoConv :1: illegal undefined/null use
at gml_GlobalScript_ChangeWeapon (line 2) - var wp_map = weapons[weapon];
############################################################################################
gml_GlobalScript_ChangeWeapon (line 2)
And the script is:
weapon = argument0;
var wp_map = weapons[weapon];
sprite = wp_map[? "sprite"];
recoil = wp_map[? "recoil"];
recoil_push = wp_map[? "recoil_push"];
damage = wp_map[? "damage"];
projectile = wp_map[? "projectile"];
startup = wp_map[? "startup"];
bulletspeed = wp_map[? "bulletspeed"];
length = wp_map[? "length"];
cooldown = wp_map[? "cooldown"];
automatic = wp_map[? "automatic"];
This error may mean a few things:
You did not wrap the contents of the script in function <name>() { ... } (as per the message that you get when you create new scripts in 2.3), causing your code to be executed on game start (and, surely enough, without arguments)
You called your script without an argument (ChangeWeapon() vs ChangeWeapon(arg)).
You called your script with an argument, but argument's value is undefined.
Based on the error message, I would assume this to be the first of three.

how do I fix an "invalid get index 'position' (on base: Nil)." error

In Godot I am trying to make a simple space shooter game where the player has to destroy a certain amount of enemies to get to the next level of the game. I am trying to get the enemy's to shoot the player to make the game a bit more fun but I am getting an error that I have no idea how to fix
invalid get index 'position' (on base: Nil).
I think the problem here is that the variable position is showing up as null but I don't know how to fix it
Script:
extends StaticBody2D
var dir = Vector2()
var player
var bullet = preload("res://scebes/EnemyBullet.tscn")
func _ready():
_get_dir(player)
func _get_dir(target):
dir = (target.position - position).normalized()
func _on_Timer_timeout():
_get_dir(player)
var b = bullet.instance()
get_parent().add_child(b)
b.position = position + dir * offset
b.dir = dir
With the error appearing on the line:
dir = (target.position - position).normalized()
Scene tree:
Node2D
├ Player
│ └ (...)
├ simple
│ ├ Sprite
│ └ CollisionShape2D
└ enemy
├ Sprite
├ CollisionShape2D
└ Timer
With the timeout of the Timer signal connected to _on_Timer_timeout.
Superficial Diagnose
The error is telling you that you are trying to access position on something that is null.
In the line:
dir = (target.position - position).normalized()
You try to access position of target (target.position) and position of self (position). Where self is the object that has the script attached. Evidently self is not null. So, let it has to be target.
The code gets target as parameter:
func _get_dir(target):
dir = (target.position - position).normalized()
Symptomatic Treatment
You would get rid of the error if you null check target:
The code gets it as parameter:
func _get_dir(target):
if target == null:
return
dir = (target.position - position).normalized()
Or better yet, check with is_instance_valid:
func _get_dir(target):
if not is_instance_valid(target):
return
dir = (target.position - position).normalized()
That way it will also handle the case where target is not null, but it references a deleted node. There are more checks you could do such as is_inside_tree or is_queued_for_deletion, but usually you don't need those.
However, that does not get rid of the real problem. The real problem is why target is null to begin with.
Deeper Diagnose
So, where is _get_dir called? Here:
func _ready():
_get_dir(player)
And later, here:
func _on_Timer_timeout():
_get_dir(player)
# ...
And where does player gets it value? Nowhere. That is the real problem. The variable player is not initialized.
Solution 1 (Simple, Fragile)
Presumably you want player to reference the Player node on the scene tree, right?
And we need to do it just in time for _ready. So we need to either insert lines at the start of _ready, or do it in an onready var.
This is possible, even though, it is fragile code:
onready var player := get_node("../Player")
The problem with that is that it assumes that the node with this script and the Player node are siblings. Which might not be true in the future. That is, reorganizing the scene tree would break the code. Hence, we say the code is fragile (easy to break).
Solution 2 (Complex, Robust)
We are in this situation becase the enemy (I'm assuming this code in the enemy) always knows where the player is. These are omniscient enemies. Thus, another option is to embrace that.
You can create an autoload (singleton). To do that, begin by creating a new script (secondary click on the FileSystem panel and select "New Script...") that looks like this:
var player
Perhaps type it (Node2D, KinematicBody2D or whatever):
var player:Node2D
Register it as an autoload on project settings with some name, let us say PlayerInfo.
Now, the player needs to register itself:
func _ready() -> void:
PlayerInfo.player = self
And the enemy can find it like this:
func _ready() -> void:
player = PlayerInfo.player
Plot twist: this code is still fragile, because the order in which _ready execute depends on the scene tree.
To avoid that, you can skip a frame in _ready before reading PlayerInfo.player:
func _ready() -> void:
yield(get_tree(), "idle_frame")
player = PlayerInfo.player
That way, you are sure Player had a chance to set PlayerInfo.player.
You may also register the player in _enter_tree:
func _enter_tree() -> void:
PlayerInfo.player = self
The _enter_tree method would run before _ready for a given node. But not necessarily before _ready of another node.
Another thing you can do is get rid of the player variable and use PlayerInfo.player directly:
_get_dir(PlayerInfo.player)
So even if the code got null the first time, it would not be stuck with that null.
By the way, you could use PlayerInfo.player from any node.
By the way, do you remember the extra checks? you could have them in the autoload:
var player:Node2D setget , get_player
func get_player() -> Node2D:
if not is_instance_valid(player):
# player is null, or deleted
return null
if not player.is_inside_tree():
# player has not been added or has been removed form the scene
return null
if player.is_queued_for_deletion():
# player is queued for deletion (e.g. queue_free)
return null
return player
Which would run every time PlayerInfo.player is read.
Note: there are other reasons to have an autoload that references the player in some way. For example, you could put save and load game functionality there. Or it can help you move the player from one scene to another. Thus, this extra complexity may proof useful in the long run, for big games.

Sprite object is not iterable, Platform Game (Python)

I am creating a platform game. I was trying to do a platform that went constantly up and down like an elevator, when i got this error: TypeError: 'Sprite' object is not iterable.
Here's the code related to the elevator:
IN SET UP:
self.platform_list = arcade.SpriteList()
self.elevator = arcade.Sprite()
for i in range(600,800,32):
self.elevator =
arcade.Sprite("imagenes/platformer/Ground/dirt_grass.png", SCALE_PLATFORMS)
self.elevator.center_x = i
self.elevator.center_y = 420
self.elevator.change_y = 2
self.platform_list.append(self.elevator)
IN UPDATE:
self.platform_list.update()
for plat in self.elevator :
if plat.center_y > 680 :
plat.change_y = - 2
if plat.center_y < 400 :
plat.change_y = 2
if i change the update by replacing plat for self.elevator, and get rid of the for, only one block of the ones that conform the platform goes up and down, the rest goes up without stoping, and gets out of the screen. I have tried also changing the for by "for self.elevator in self.platform_list" and then changing plat for self.elevator, but when i execute it, all platforms move up and down.
¿How can i fix this? Please help me.

Resources