I got some signal problems when I attempt to spawn multiple nodes - 2d

My intend is to spawn node (I will say Stickman for now) on a specific position and make them move to left and right using buttons.
As you can see, I have two buttons to move my Stickman. The Attack button will move the Stickman to the right, while the Defense button will move it to the left. The small button from the right is used to spawn the stickman.
Things work like a charm, yes
The issues occurs when I try to spawn another Stickman. For some reasons the signal is cut with the second Stickman, which I believed is because I only connected my signal to Stickman's node, but in this case its currently rename as Stickman2, Stickman3 and so on.
The problem reveals itself
Here is the code of my stickman:
extends KinematicBody2D
var speed = 30
var velocity = Vector2.ZERO
onready var enemy_base = get_node("../Position/enemy_base").global_position
onready var allied_base = get_node("../Position/allied_base").global_position
enum {
ATTACK,
DEFENSE,
RETREAT
}
var state = DEFENSE
func _physics_process(delta):
match state:
ATTACK:
attack(delta)
DEFENSE:
defense(delta)
func attack(delta):
var direction = (enemy_base - global_position).normalized()
var desired_velocity = direction * speed
var steering = (desired_velocity - velocity) * delta * 2.5
velocity += steering
velocity = move_and_slide(velocity)
func defense(delta):
var direction = (allied_base - global_position).normalized()
var desired_velocity = direction * speed
var steering = (desired_velocity - velocity) * delta * 2.5
velocity += steering
velocity = move_and_slide(velocity)
func _on_Attack_pressed():
state = ATTACK
func _on_Defense_pressed():
state = DEFENSE
And this is the spawning code I used:
extends Node2D
var Stickboi = preload("res://StickBoy.tscn")
var Swordman = Swordman
func _on_StickBoi_pressed():
Swordman = Stickboi.instance()
Swordman.global_position = $Position/behind_allied_base.global_position
add_child(Swordman)
func _on_Attack_pressed():
Swordman.state = Swordman.ATTACK
func _on_Defense_pressed():
Swordman.state = Swordman.DEFENSE
I want all my Stickmans to react to my signal whenever I pressed the Attack or Defense buttons, which in this case doesn't work at all. I really appreciate if you have any ideas that could share, even if its just a hint. I'm still a beginner and I acknowledge my stupidity, so sorry to ask such simple question and also my bad English grammars. Please ask if there are anything you want to know in case my explanation is such simple, I will try my best to answer as fast as possible. Once again, thank you for your help.

I don't see you connect the signals.
Instead, it appears to me, that the signals are connected to the Node2D that has the spawning code. And it calls into the Swordman instance, which is the last instance it created.
You can actually connect the signals.
I'm guessing that the Node2D that has the spawning code is the parent of the buttons.
First of all, you will have no need to keep a reference to the instance. Nor will you connect the buttons to the Node2D that has the spawning code. I'm getting rid of that:
extends Node2D
var Stickboi = preload("res://StickBoy.tscn")
func _on_StickBoi_pressed():
var swordman = Stickboi.instance()
swordman.global_position = $Position/behind_allied_base.global_position
add_child(swordman)
Instead we are going to connect the buttons to the instance (you seem to have conveniently created methods for that, so I'll use them).
extends Node2D
var Stickboi = preload("res://StickBoy.tscn")
func _on_StickBoi_pressed():
var swordman = Stickboi.instance()
$Attack.connect("pressed", swordman, "_on_Attack_pressed")
$Defense.connect("pressed", swordman, "_on_Defense_pressed")
swordman.global_position = $Position/behind_allied_base.global_position
add_child(swordman)
And that should work.

Related

how to create a shooting bullet using gamemakers built in physics

I'm new to GameMaker, and to making games, for my second game ever I was just going to use GameMakers built in physics. It's a RPG and I'm having lot's of trouble getting the guy to shoot the bullet. I can get the bullet to be placed in the room and at the angle it needs to be at. You could normally then just use the objectnamehere.speed = to what ever you want your speed to be. But! using physics you could use the phy.speed but that's a read only variable. So i half to use the phy_speed_x and phy_speed_y. But how do I get it to shoot in the direction the bullet object is? Here's the code I have so far.
// Player shoot
var shootButton = mouse_check_button_pressed(mb_left);
var bulletSpeed = 10;
if (shootButton) {
bullet = instance_create(ot_player.x, ot_player.y, ot_bullet);
bullet.phy_rotation = phy_rotation;
bullet.phy_speed_x = bulletSpeed;
bullet.phy_speed_y = bulletSpeed;
}
I have tried putting many different variables where I have the bulletSpeed variables but nothing has seem to work. I'm stuck here, I've watch tutorials and read lots of stuff but nothing has worked!
I figured it out.
var shootButton = mouse_check_button_pressed(mb_left);
var bulletSpeed = 10;
if (shootButton) {
bullet = instance_create(ot_player.x, ot_player.y, ot_bullet);
with(bullet) {
phy_rotation = other.phy_rotation;
ldx = lengthdir_x(15, -phy_rotation)
ldy = lengthdir_y(15, -phy_rotation)
physics_apply_impulse(x, y, ldx, ldy);
}
}

How should I Parse and Delay a Hot Reactive Extensions IConnectableObservable<T> stream?

I am unable to implement this, so unfortunately I have no Rx code to show where I am at. I will explain what i would like t do, and hopefully someone out there with enough expertise might be able to guide me in the right direction.
Let us say that I have a collection of List TimeObjects that I pulled from a database. TimeObject has this form.
public class TimeObject
{
public DateTime time{get;set;}
public decimal price{get;set;}
}
What I want to do is produce a Hot IConnectableObservable stream, where each element is separated by a variable time delay.
The variable time delay is equal to the difference between the time of the current and the next TimeObject.
For example, if the stream is this:
s1, s2, s3, ...sN, where each 's' represents an element of TimeObject
Then, the time delay before s2 is pushed out to the stream is (s2.time - s1.time),
the time delay before s3 is pushed out to the stream is (s3.time - s2.time) and so on.
Is this at all possible, and if so, what should my implementation look like?
I have included a for loop that accomplishes the same task using a classical approach.
FireEvent(TimeObject[0]); //Post the first element as an event
for(int _counter = 0; _counter < TimeObject.Count; _counter++)
{
if ( _counter + 1 < TimeObject.Count )
{
TimeObject timeObjectA = TimeObject[_counter];
TimeObject timeObjectB = TimeObject[_counter + 1];
int millisecondsDelay = (timeObjectB.time - timeObjectA.time).Milliseconds;
Thread.Sleep(millisecondsDelay);
FireEvent(timeObjectB); //this posts the latest tick as an event with variable time delay.
}
What I would like is for this to be converted into an Observable stream.
Thanks.
Try this:
var observable =
Observable
.Generate(
1,
x => x < timeObjects.Count,
x => x + 1, x => timeObjects[x],
x => timeObjects[x].time.Subtract(timeObjects[x - 1].time)))
.StartWith(timeObjects[0]);
Now, this is a regular cold observable. You could make it hot by calling .Publish(). Why do you need it hot?
It also requires your list to have at least two elements

How to set focus on a client under mouse cursor when a tag is changed?

When I switch to another tag, a new client gets selected, but it is sometimes not a client that I have my mouse cursor over. To get a client under my mouse pointer focused, I have to either click somewhere on it, or switch to it with Mod4+j / k, or move mouse cursor out and back on that client.
I want awesome to give focus to a client that is under the mouse cursor whenever a tag is changed. How do I do that?
I found a function mouse.object_under_pointer() that finds the client I need, but I don't know when to call that function. Should I connect a handler to some particular signal? I tried connecting to various signals from Signals page on the wiki and checking with naughty.notify() if that is the right signal, but none of them were triggered when I was switching between tags.
This code did the trick, however there should be a better way to do this than setting up a huge 200 ms timer (smaller timeouts didn't properly focus some clients for me, but you can try setting a smaller one).
tag.connect_signal(
"property::selected",
function (t)
local selected = tostring(t.selected) == "false"
if selected then
local focus_timer = timer({ timeout = 0.2 })
focus_timer:connect_signal("timeout", function()
local c = awful.mouse.client_under_pointer()
if not (c == nil) then
client.focus = c
c:raise()
end
focus_timer:stop()
end)
focus_timer:start()
end
end
)
tag is this global object, so you should just place this code anywhere in your rc.lua.
Two things should be done:
First, you should remove require("awful.autofocus") from your config, so that this module no longer tries to focus some client via the focus history when you switch tags.
Then, this code works for me:
do
local pending = false
local glib = require("lgi").GLib
tag.connect_signal("property::selected", function()
if not pending then
pending = true
glib.idle_add(glib.PRIORITY_DEFAULT_IDLE, function()
pending = false
local c = mouse.current_client
if c then
client.focus = c
end
return false
end)
end
end)
end
This uses GLib directly to get a callback for when no other events are pending. This should mean that "everything else" was handled.
I know this is pretty old, but it helped me to come up with this
function focus_client_under_mouse()
gears.timer( { timeout = 0.1,
autostart = true,
single_shot = true,
callback = function()
local n = mouse.object_under_pointer()
if n ~= nil and n ~= client.focus then
client.focus = n end
end
} )
end
screen.connect_signal( "tag::history::update", focus_client_under_mouse )

Implementing an IObservable to compute digits of Pi

This is an academic exercise, I'm new to Reactive Extensions and trying to get my head around the technology. I set myself a goal of making an IObservable that returns successive digits of Pi (I happen to be really interested in Pi right at the moment for unrelated reasons). Reactive Extensions contains operators for making observables, the guidance they give is that you should "almost never need to create your own IObsevable". But I can't see how I can do this with the ready-made operators and methods. Let me elucidate a bit more.
I was planning to use an algorithm that would involve the expansion of a Taylor series for Arctan. To get the next digit of Pi, I'd expand a few more terms in the series.
So I need the series expansion going on asynchronously, occasionally throwing out the next computed digit to the IObserver. I obviosly don't want to restart the computation from scratch for each new digit.
Is there a way to implement this behaviour using RX's built-in operators, or am I going to have to code an IObservable from scratch? What strategy suggests itself?
For something like this, the simplest method would be to use a Subject. Subject is both an IObservable and IObserver, which sounds a bit strange but it allows you to use them like this:
class PiCalculator
{
private readonly Subject<int> resultStream = new Subject<int>();
public IObservable<int> ResultStream
{
get { return resultStream; }
}
public void Start()
{
// Whatever the algorithm actually is
for (int i = 0; i < 1000; i++)
{
resultStream.OnNext(i);
}
}
}
So inside your algorithm, you just call OnNext on the subject whenever you want to produce the next value.
Then to use it, you just need something like:
var piCalculator = new PiCalculator();
piCalculator.ResultStream.Subscribe(n => Console.WriteLine((n)));
piCalculator.Start();
Simplest way is to create an Enumerable and then convert it:
IEnumerable<int> Pi()
{
// algorithm here
for (int i = 0; i < 1000; i++)
{
yield return i;
}
}
Usage (for a cold observable, that is every new 'subscription' starts creating Pi from scratch):
var cold = Pi().ToObservable(Scheduler.ThreadPool);
cold.Take(5).Subscribe(Console.WriteLine);
If you want to make it hot (everyone shares the same underlying calculation), you can just do this:
var hot = cold.Publish().RefCount();
Which will start the calculation after the first subscriber, and stop it when they all disconnect. Here's a simple test:
hot.Subscribe(p => Console.WriteLine("hot1: " + p));
Thread.Sleep(5);
hot.Subscribe(p => Console.WriteLine("hot2: " + p));
Which should show hot1 printing only for a little while, then hot2 joining in after a short wait but printing the same numbers. If this was done with cold, the two subscriptions would each start from 0.

Bitwise ops on bitmaps in Flex/AS3

There is a specific bitwise logical op on three bitmaps I would like to achieve in Flex/AS3. It would presumably have to be done with some combination of DisplayObject blendmodes, ColorMatrix filters, and possibly something else I haven't thought of, as FLex/As3 doesn't have bitwise logical ops on pixels (except for BlendMode.INVERT).
So here is the operation:
(B & S) | (F & ~S)
[where B,S,F are three bitmaps]
That's it.
Incidentally, I tried this with Pixel Bender, but incredibly, it doesn't have bitwise logical ops either. (What exactly were you thinking Adobe). So I simulated them without about 50 modulos and divides but it came out way too slow. (Could be because I didn't have a supported graphcs card which brings up another question - if Pixel Bender only works with certain cards, how do you find out at runtime from Flex/AS3 if the browser computer has a supported card.)
But anyway, my main question is how to perform that trivial little bitwise op above in Flex/AS3. (It would have to be as fast as BlendModes).
I'm not very experienced using bitwise operations, but i threw together a quick test case using the fancy new Flash player 10 vectors which are very nice for this type of data wrangling.
This runs through the 2000x2000 pixels in 115ms using the standalone debug player on my computer, it'll likely be a bit faster in the release player.
I'm not sure if this is fast enough since I don't know how often or on how large images you need to run it, but it might at least be a starting point.
package {
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.text.TextField;
import flash.utils.getTimer;
/**
* ...
* #author Martin Jonasson
*/
public class Test extends Sprite {
public function Test() {
var output:TextField = new TextField();
output.autoSize = "left";
addChild(output);
var bmpB:BitmapData = new BitmapData(2000, 2000, false, 0xff00ff);
var bmpS:BitmapData = new BitmapData(2000, 2000, false, 0xffffff);
var bmpF:BitmapData = new BitmapData(2000, 2000, false, 0x000000);
var rect:Rectangle = new Rectangle(0, 0, 2000, 2000)
var vecB:Vector.<uint> = bmpB.getVector(rect);
var vecS:Vector.<uint> = bmpS.getVector(rect);
var vecF:Vector.<uint> = bmpF.getVector(rect);
var vecFinal:Vector.<uint> = new Vector.<uint>(vecB.length, true);
var startTime:int = getTimer();
for (var i:int = vecB.length - 1; i >= 0; --i) {
vecFinal[i] = (vecB[i] & vecS[i]) | (vecF[i] & ~vecS[i]);
}
output.appendText("bitwise stuff done, took: " + (getTimer() - startTime) + "ms \n");
startTime = getTimer();
var bmpFinal:BitmapData = new BitmapData(2000, 2000, false);
bmpFinal.setVector(rect, vecFinal);
output.appendText("created bitmapdata, took: " + (getTimer() - startTime) + "ms \n");
}
}
}
To grapefrukt:
With 1000X1000 bitmaps its 47 ms on my system, so this is looking very promising (approaching standard refresh rates with some tweaks one would hope).
I learned Flex 2 first, so didn't know about Vectors, which are evidently just highly efficient one-type only arrays.
I need to start paying it forward at some point, because this forum is amazing (4 for 4 on some fairly obscure questions since I first found out about it 10 days ago.)
Thanks again.

Resources