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.
Related
So I want to set my _target_node to null when an enemy dies.
Here how I target an enemy:
in my player.gd I have:
var _target_node: Node = null
func handle_target_lock():
if Input.is_action_just_pressed("target_lock"):
if _target_node:
_target_node = null
else:
var enemies: Array = get_tree().get_nodes_in_group("Enemy")
if enemies.size() > 0:
_target_node = enemies[0]
if _target_node:
look_at(_target_node.global_transform.origin, Vector3.UP)
Problem is, when an enemy dies, _target_node is now referencing a deleted instance.
My enemy node emits a signal died when its hp is 0, but I don't know how to use this information to notify my player.
How do I notify the player that the targeted enemy is dead and _target_node should be set to null?
Godot version 3.5.1
So you are saying there is a died signal so you could connect to it's die signal, when it is targeted:
if Input.is_action_just_pressed("target_lock"):
if _target_node:
#"died" should be renamed to your signal name!
_target_node.disconnect("died",self, "on_target_died") # disconnect if you switch the target
_target_node = null
else:
var enemies: Array = get_tree().get_nodes_in_group("Enemy")
if enemies.size() > 0:
_target_node = enemies[0]
#"died" should be renamed to your signal name!
_target_node.connect("died",self, "on_target_died")
func on_target_died():
_target_node = null
Edit: It could help to pass the enemy as a parameter in the died signal so you can check, if the event was really fired from the enemy that is currently targeted. Otherwise there could be the chance, the player is still connected to the wrong enemy while switching targets
Problem is, when an enemy dies, _target_node is now referencing a deleted instance.
You can check for that:
if is_instance_valid(_target_node):
On the other hand, this form:
if _target_node:
Is checking if the variable is not zeroed. For an Object type (such as Node) it is checking if the variable is not set to null. However you can free Nodes while there are still references to them. As you might now, Node is not reference counted (it does not extend Reference), instead you free them manually with free or queue_free. When a Node is freed, Godot does not automatically turn the references that point to it into null, instead they become invalid references. We use is_instance_valid to check for that.
im making a 2d platformer in godot with a dash mechanic. i have already tried implementing it myself. i have put in a cool down timer for the dash(which works), made it so that cant dash while in air(which works), and animation(which doesn't work).my code has the following problems:
player "teleports" rather than smoothly and quickly dashing
the animation for dashing is barely visible (visible for only a frame)
for some reason if you are idle(not pressing any buttons) and then push the dash button it propels you further than if you are running(holding one of the arrow keys) and push the dash button.
here is my code. it has a lot of code in it that probably isn't causing the problem but i left it in just in case it is. i put #important in front of all the parts of the code that i deemed important
extends KinematicBody2D
var vel = Vector2(0,0)
var fallswitch=0
var can_jump
var can_dash=true
const GRAVITY = 30
const SPEED = 250
const JUMPFORCE = -1000
const DASHSPEED = 1000
func _physics_process(delta):
#important
if Input.is_action_pressed("dash") and is_on_floor() and can_dash==true:
$Sprites.play("dash")
if $Sprites.flip_h==false:
vel.x = DASHSPEED
else:
vel.x = -DASHSPEED
can_dash=false
$dashcooldown.start()
elif Input.is_action_pressed("right"):
vel.x = SPEED
$Sprites.flip_h=false
$Sprites.play("run")
elif Input.is_action_pressed("left"):
vel.x = -SPEED
$Sprites.flip_h=true
$Sprites.play("run")
else:
pass
$Sprites.play("idle")
if not is_on_floor():
if vel.y < 200 and vel.y > 0:
$Sprites.play("fall.t")
elif vel.y > 200:
$Sprites.play("fall")
else:
$Sprites.play("air")
if is_on_floor():
can_jump=true
elif can_jump==true and $CoyoteTimer.is_stopped() :
$CoyoteTimer. start()
if Input.is_action_just_pressed("jump") && can_jump==true:
vel.y = JUMPFORCE
vel.y+=GRAVITY
vel=move_and_slide(vel,Vector2.UP)
vel.x = lerp(vel.x,0,0.1)
func _on_CoyoteTimer_timeout():
can_jump=false
#important
func _on_dashcooldown_timeout():
can_dash=true
thank in advance :)
Your code seems good. The problem might be from your camera2d. In order to implement a proper dash effect the camera needs to have a smoothing effect(it has to slowly stop when it reaches the player whenever the player moves). It acts as a lag, if there is no lag then the camera will sharply follow the player at every moment and will make a dash seem like a teleport. Try out these camera settings. In the camer2d property section enable the current property, under the limit section enable the smooth property, under the smoothing section enable the smoothing and set the speed to 8.8.
More Tips
At _on_dashcooldown_timeout(), be sure to set the player x vector component back to zero
Only use one sprite frame for dash as you do not need multiple images for it, since it is short and quick.
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.
I am making a game in godot. But I can't unpause after pausing. I used Input Map to create two keyboard shortcuts(one to pause and other to un-pause) and auto-loaded the script. This is the code:
extends Node
var players_coin = 0
func _ready():
PAUSE_MODE_PROCESS
func _input(event):
if Input.is_action_pressed("pause"):
get_tree().paused = true
if Input.is_action_pressed("unpause"):
get_tree().paused = false
I am bad at stack overflow, but this should work.
I am using "Godot 3.2.2.stable" and any help would be great.
Just replace your ready function with following:
func _ready():
pause_mode = Node.PAUSE_MODE_PROCESS
Or
you can do the same thing in Node under Inspector Tab.
here is the offical documentation link
The problem you are facing is when you pause the tree, even the input process also stops.
FIX:
don't make it an auto-load script, attach it to a node and set its pause mode to process.
func _process(delta):
if Input.is_action_pressed("pause"):
get_tree().paused = true
if Input.is_action_pressed("unpause"):
get_tree().paused = false
I hope it will fix the issue. if not here is godot's documentation on this
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()