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
Related
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.
I'm new to pico, only using arduinos before. I'm trying to make a simple rotary encoder program that displays a value from 0-12 on an 0.96 oled display, and lights up that many leds on a strip.
I wanted to try out using multiple cores, as interrupts made the leds not run smooth when I had them just cycling (everything would be paused while the encoder was being turned)
However, when I run this program, aside from the encoder being bouncy, the pico would crash maybe 30 seconds into running the program, making a mess on the display and stopping the code. I feel like there's some rule of using multiple cores that I completely ignored.
Here's the code:
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import _thread
import utime
import neopixel
#general variables section
numOn = 0
#Encoder section
sw = Pin(12,Pin.IN,Pin.PULL_UP)
dt = Pin(11,Pin.IN)
clk = Pin(10,Pin.IN)
encodeCount = 0
lastClk = clk.value()
lastButton = False
#Encoder thread
def encoder(): #don't mind the indentation here,
#stackoverflow kinda messed up the code block a bit.
while True:
#import stuff that I shouldn't need to according to tutorials but it doesn't work without
global encodeCount
global lastClk
global clk
import utime
if clk.value() != lastClk:
if dt.value() != clk.value():
encodeCount += 1
else:
encodeCount -= 1
if encodeCount > 12:
encodeCount = 0
elif(encodeCount < 0):
encodeCount = 12
lastClk = clk.value()
print(encodeCount)
utime.sleep(0.01)
_thread.start_new_thread(encoder,())
#LED section
numLed = 12
ledPin = 26
led = neopixel.NeoPixel(machine.Pin(ledPin),numLed)
#Screen Section
WIDTH = 128
HEIGHT = 64
i2c = I2C(0,scl=Pin(17),sda=Pin(16),freq=200000)
oled = SSD1306_I2C(WIDTH,HEIGHT,i2c)
#loop
while True:
for i in range(numLed):
led[i] = (0,0,0)
for i in range(encodeCount):
led[i] = (100,0,0)
led.write()
#Display section
oled.fill(0)
oled.text(f'numLed: {numOn}',0,0)
oled.text(f'counter: {encodeCount}',0,40)
oled.show()
I'm probably doing something stupid here, I just don't know what.
Also, any suggestions on simply debouncing the encoder would be very helpful.
Any help would be appreciated! Thanks!
Update: The code above bricked the pico, so clearly I'm doing something very very wrong. _thread start line stopped it from crashing again, so the problem is there.
Same issue with very similar code on a Raspberry Pico W. I specify the 'W' because my code works without crashing on an earlier Pico.
I'm wondering if the low level networking functions might be using the 2nd core and causing a conflict.
I'm adding thread locking to see if passing a baton helps, the link below has an example, eg:
# create a lock
lck= _thread.allocate_lock()
# Function that will block the thread with a while loop
# which will simply display a message every second
def second_thread():
while True:
# We acquire the traffic light lock
lck.acquire()
print("Hello, I'm here in the second thread writting every second")
utime.sleep(1)
# We release the traffic light lock
lck.release()
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 using QT 5.11.2 on both linux and windows. I am trying to optimize my UI to prevent it from freezing in large functions. I started using QThread and was able to do exactly what I want on windows. However, I tried to test the same functions on linux RHEL7 but threads never finished.
Here is what I tried:
void MainWidget::Configure_BERT_DSO(bool isOptimization, double lineRate, int Scaling)
{
QThread *bertThread = QThread::create([this, lineRate, Scaling]{ ConfigureBert(lineRate, Scaling);
QThread *dsoThread = QThread::create([this, lineRate]{ ConfigureDSO(lineRate); });
bertThread->setObjectName("My Bert Thread");
dsoThread->setObjectName("My DSO Thread");
bertThread->start();
dsoThread->start();
while(bertThread->isRunning() || dsoThread->isRunning()) // even tried isFinished()
{
qApp->processEvents();
}
bertThread->exit();
dsoThread->exit();
delete bertThread;
delete dsoThread;
}
In windows the while loop exits after a while and both threads execute correctly with no problem.
On linux, to make sure that both functions execute correctly, I added qDebug() at the start and end of each function and they are all reached at the excpected time. But the problem is that isRunning never becomes true again and the same goes for isFinished and my loop gets stuck.
Thread: QThread(0x1d368b0, name = "My Bert Thread") started.
Thread: QThread(0x1d368e0, name = "My DSO Thread") started.
Thread: QThread(0x1d368b0, name = "My Bert Thread") finished.
Thread: QThread(0x1d368e0, name = "My DSO Thread") finished.
Is it something platform dependent or is there something that I might be missing?
EDIT
I also tried to use bertThread->wait() and dsoThread->wait() to check if it exits after my functions finish but it never returns from the first one I called although both functions reach their end successfully
Your help is much appreciated
Lua novice asks:
How do I transition from this...
(a simple example to establish a how-to)...
visual = display.newImage( "redCircle.png", 50, 50 )
local music = audio.loadStream("sound1.mp3")
audio.play(music)
audio.stopWithDelay(60000/60)
to this, timed by the first sound file ending?
visual = display.newImage( "blueCircle.png", 50, 50 )
local music = audio.loadStream("sound2.mp3")
audio.play(music)
audio.stopWithDelay(60000/60)
Which api should I be experimenting with? I've looked at https://docs.coronalabs.com/api/index.html
What am I missing?
What you can do is create a function listener for the first audio file you can look more here: https://docs.coronalabs.com/api/library/audio/play.html Below is a sample code I can give you. Note that I did not use audio.stopWithDelay
--DECLARE LOCAL VARIABLES
local visual1
local visual2
local music1
local music2
--LOAD SOUNDS
music1 = audio.loadStream("sound1.mp3")
music2 = audio.loadStream("sound2.mp3")
local function soundIsFinished(event)
if (event.completed) then
--PLAY SECOND AUDIO AND HIDE/REMOVE VISUAL 1
visual1.isVisible = false
visual2.isVisible = true
audio.play(music2, {duration = 1000})
end
end
--DISPLAY VISUAL1 and play MUSIC1
visual1 = display.newImage("redCircle.png", 50,50)
--AUDIO WILL PLAY FOR 1 SECOND (60000/60) is 1 second
audio.play(music1, { duration=1000, onComplete=soundIsFinshed } )
-- HIDE VISUAL2 FIRST
visual2 = display.newImage("blueCircle.png", 50,50)
visual2.isVisible = false
Hope This helps.