Godot Onready var not working and getting error Unexpected "Identifier" in class body - godot

trying to use onready var to start a raycast to play a animation for a npc but even though the ray works it wont play the animation
code:
extends Node3D
enum
{
Attack1,
Death1,
Idle,
Pose,
Walk
}
var state = Idle
onready var raycast = $RayCast3D
onready var ap = $"maxdamage_zombie-low-poly"
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
if raycast.is_colliding():
state = Attack1
else:
state = Idle
match state:
Attack1:
ap.play("Attack1")
Death1:
ap.play("Death1")
Idle:
ap.play("Idle")
Pose:
ap.play("Pose")
Walk:
ap.play("Walk")
Explanation/Alternative simple answer on how to fix the code in a beginner/intermediate level explanationyour text

Related

Within the GameController API, is continuously polling of navigator.getGamepads() required?

EDITED at end!
Within the GameController API, is continuously polling of navigator.getGamepads() required?
I ask because my single call to this function returns a length = 0.
According to my Mac’s Bluetooth System Preferences my Nimbus+ game pad is connected.
Given that, should I use isetInterval` and wait for a length > 0?
EDIT begins here:
Macintosh with Monterey OS 12.4:
Safari (15.5) reports length = 0
Firefox (102.0b6) reports length = 0
Chrome (102.0.5005.115) reports length = 4,
but each in the array being = null
You first wait for the gamepad to be connected, which typically requires "waking" the gamepad by pressing one of its buttons:
window.addEventListener('gamepadconnected', (event) => {
console.log('✅ 🎮 A gamepad was connected:', event.gamepad);
});
Once the gamepad is connected, you start your game loop:
const pollGamepad = () => {
// Always call `navigator.getGamepads()` inside of
// the game loop, not outside.
const gamepads = navigator.getGamepads();
for (const gamepad of gamepads) {
// Disregard empty slots.
if (!gamepad) {
continue;
}
// Process the gamepad state.
console.log(gamepad);
}
// Call yourself upon the next animation frame.
// (Typically this happens every 60 times per second.)
window.requestAnimationFrame(pollGamepad);
};
// Kick off the initial game loop iteration.
pollGamepad();
You should stop polling when the gamepad gets disconnected, which you'll be informed of via an event:
window.addEventListener('gamepaddisconnected', (event) => {
console.log('❌ 🎮 A gamepad was disconnected:', event.gamepad);
});

Capturing every frame to recognize text ARcore - Do i need to use semaphores?

I am developing an app in which I want to recognize text in real-time.
At first I was using onTapListener so whenever the user was tapping on the screen the current frame was being captured and after that the text recognition was called.
Right now I want to do this completely real-time so the user will not tap on the screen to capture the current frame. But every current frame is going to be captured until the moment the text of one captured current frame will be recognized.
For this reason, I created a global boolean field name locked that is initialized in false and I use it as a "locker" as you will see in a bit.
private boolean locked = false;
And in a method onUpdateFrame(FrameTime frameTime) I use the above global variable locked. When the first feature points are tracked I "lock" the update. So only the current thread gonna capture the current frame. And if the recognized data is null the I put locked = true so the next frame gonna be captured.
This is my code
public void onUpdateFrame(FrameTime frameTime) {
Frame frame = arFragment.getArSceneView().getArFrame();
// If there is no frame, just return.
if (frame == null) {
return;
}
//Making sure ARCore is tracking some feature points, makes the augmentation little stable.
if(frame.getCamera().getTrackingState()==TrackingState.TRACKING && !locked) {
locked = true;
if (mProgressDialog == null) {
mProgressDialog = ProgressDialog.show(this, "Processing",
"OCR...", true);
} else {
mProgressDialog.show();
}
executor.execute(() -> {
Bitmap b = captureImage();
final String[] text = {getOCRResult(b)};
handler.post(() -> {
if(text[0] != null && !text[0].equals("")){
doSomething();
}
else{
locked = false;
}
}
This is not working though. And my app is crashing immediately when is detecting the surface.
I am getting the following error, and the Toast that the error talks about it refers to a Toast that I have inside the method captureImage()
E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1
Process: opencv.org, PID: 27860
java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
I cant understand what I am doing wrong.
I heard of semaphores and this is why I asked that on my question. Should i use semaphores , do i need something like that so my app will work. As i understand i need one thread anytime to do the capture of the current frame.
Could someone help me i am a bit lost?
thank you
The reason you are getting this error is that you can't show a toast, or any UI, on a non-UI thread.
The usual way to handle this is to create a 'Handler' on the UI thread and send a message to its message queue asking it to post the thread.
You can see examples in both Java and Kotlin in this answer: Can't create handler inside thread that has not called Looper.prepare()
More info on Handler here: https://developer.android.com/reference/android/os/Handler

GODOT - Signal not connecting when using connect(). Function is not getting executed

Here is the link to the files:
signal_test.gd
extends Node2D
signal do
func _ready() -> void:
print('signal_ready!')
emit_signal('do')
pass
test.gd
extends Node2D
onready var signal_test = preload('res://signal_test.tscn')
func _ready() -> void:
print('test ready')
func _process(delta: float) -> void:
if Input.is_action_just_pressed("jump"):
var h = signal_test.instance()
add_child(h)
h.connect('do', self, 'do')
print(h.is_connected('do', self, 'do'))
func do():
print('DONE CONNECTING!!')
The test.gd file creates an instance of a node and connect it to it's function using the connect() method. But the function is not getting executed. It only says true when I use is_connected() on the test.tscn, but false on the instance of the node. Anyone know why?
The signal will be emitted in _ready, which will execute after the node is added as child, before the next line:
var h = signal_test.instance()
add_child(h)
# <-- signal emitted here, it is NOT connected
h.connect('do', self, 'do')
Solution: connect the signal before adding the node as child:
var h = signal_test.instance()
h.connect('do', self, 'do')
add_child(h)
# <-- signal emitted here, it is connected

How to add Signals to objects created with add_child

I'm looking to create child objects that are duplicates of a pre-existing, using this method in my root class. While it successfully creates a copy of that object in the remote tree during runtime, it is not sending signals like the original object (for instance, the objects send a signal to a UI component which displays its global position in realtime). How do I create a child object that matches the signals emitted by the original?
func create_Object(Obj, size, position):
var New = Obj.instance()
add_child(New)
New.scale = size
New.global_transform.origin = position
You can enumerate the lists of defined signals of a Node with get_signal_list. Example:
var signals = node.get_signal_list()
for cur_signal in signals:
print(cur_signal.name)
You can use get_signal_connection_list to get the outgoing connections:
var signals = node.get_signal_list()
for cur_signal in signals:
var conns = node.get_signal_connection_list(cur_signal.name)
for cur_conn in conns:
print(cur_conn.signal)
print(cur_conn.target)
print(cur_conn.method)
Then connect them with, well, connect:
var signals = node.get_signal_list()
for cur_signal in signals:
var conns = node.get_signal_connection_list(cur_signal.name)
for cur_conn in conns:
new_node.connect(cur_conn.signal, cur_conn.target, cur_conn.method)

How to create an interruptible loop in node.js

Disclaimer: I'm a Node.js newbie and the following description may be lengthy...
I'm currently trying to teach myself Node.js for a little project I'm after. The project idea is the following: a RaspberryPI runs a Node.js application which allows me to control the colors of an RGB LED strip. The application should be able to set both a static color and also run color wheels that smoothly change colors.
My idea is now to create several Node.js scripts:
A "controller" that does the client communication, sets static colors or is able to start a color wheel
"client scripts" that each run a color wheel. At most one of them would be "alive", started/stopped by the "controller"
I've been able to create a little script that forks another script and is able to stop that script using child.send as follows:
controller.js
var fork = require('child_process').fork,
test2 = fork(__dirname + '/test2.js');
setTimeout(function() { test2.send({func: 'quit'}); }, 5000);
This forks the test2.js script and after 5 seconds sends a quit message that quits test2.js.
test2.js
function runLoop()
{
console.log("Hello");
setTimeout(runLoop, 1000);
}
process.on('message', function(m) {
if (m.func === 'quit')
{
process.exit(0);
}
});
setTimeout(runLoop, 1000);
This "client script" prints "Hello" every second until the controller sends the quit message.
This works pretty well - after 5 seconds the scripts finish gracefully.
My question is now: If I implement a color wheel, I'll need a possibly endless loop that changes the colors of the LED strip. Would the above (with shorter timer values of course - I need something like 10ms here) be a feasible way of implementing an interruptible loop or is there some neater mechanism I don't know of yet?
If you're using setTimeout, you shouldn't even need to fork a new process. Here's how I would write your example:
var ntrvl = setInterval(function() { console.log('Hello'); }, 1000);
setTimeout(function() { clearInterval(ntrvl); }, 5000);
... very simple. With setTimeout and setInterval, you're using asynchronous functions, so you will not block the event loop. When the timer is up, it runs your code, then waits for the next event. You should be able to control all of your "clients", you'll have bandwidth for far more than you'll actually need, all in the same process in this way, concurrently.
All you need to be wary of is that you're not blocking the script. If you attempt to perform any action synchronously (which means that the script will wait for the action to complete before performing the next command), then you need to make sure it runs quickly. If you have to run processor/time intensive tasks synchronously, that's when you'll need to fork a new process.
You're making the life complicated. Your global architecture is as follows:
external trigger --> listener ----------> code that changes color
(ie. web client) (ie. web server)
With that in mind you don't need to fork any process, you can control the LED strip within a single process. Somewhere in your code you'll have an object similar to this:
//"led" is the module that allows you to change the color of a led (suppose 4 leds)
var led = require ("led-controller");
var ColorChanger = module.exports = function (){
this._intervalId = null;
};
ColorChanger.prototype.setColor = function (hex){
//Color in hexadecimal
//Cancel any current interval
cancelInterval (this._intervalId);
led.color (0, hex);
led.color (1, hex);
led.color (2, hex);
led.color (3, hex);
};
ColorChanger.prototype.wheel = function (hex, ms){
//Color in hexadecimal
//"ms" is the time interval between leds going on and off
//Cancel any current interval
cancelInterval (this._intervalId);
//Shutdown all the leds
led.off (0);
led.off (1);
led.off (2);
led.off (3);
//Activate the first led
led.color (0, hex);
//Current active led
var curr = 0;
this._intervalId = setInterval (function (){
//Each "ms" the current led will go off and the next will go on
led.off (curr);
//Next led to activate
curr = ++curr%4;
led.color (curr, hex);
}, ms);
};
Then the listener module uses the ColorChanger.
var ColorChanger = require ("./color-changer");
var changer = new ColorChanger ();
//Set all the leds to red
changer.setColor ("#FF0000");
//Each 10ms one led goes green and the previous is turned off, in an endless loop
changer.wheel ("#00FF00", 10);

Resources