i am a beginner as you can see and i've been following a video tutorial on defold with lua about 2D animation since then i've been asking me some question about this code, why the local variable currentAnimation is equal to 0 a then to 1 on the code, then about self.currentAnimation, as i understand currentAnimation is a method because is an action which is called through self so the object can move right?
local currentAnimation = 0
function init(self)
msg.post(".", "acquire_input_focus")
end
function final(self)
end
function update(self, dt)
end
function on_message(self, message_id, message, sender)
end
function on_input(self, action_id, action)
if action_id == hash("right") and action.pressed == true then
if self.currentAnimation == 1 then
msg.post("#sprite", "play_animation", {id = hash("runRight")})
self.currentAnimation = 0
else
msg.post("#sprite", "play_animation", {id = hash("idle")})
self.currentAnimation = 1
end
end
if action_id == hash("left") and action.pressed == true then
if self.currentAnimation == 1 then
msg.post("#sprite", "play_animation", {id = hash("runLeft")})
self.currentAnimation = 0
else
msg.post("sprite", "play_animation", {id = hash("idle")})
self.currentAnimation = 1
end
end
end
What steps should i follow so i can change the code in a way so while i press the right arrow from the keyword the "hero" moves and when i stop pressing the "hero" stops moving because with this code it doesn't stop moving until i press again the same button, btw the second chunk of code did it myself following the first one.
Now i got another question, i want to make it jump when i pressed a designated button:
if action_id == hash("jump") then
if action.pressed then
msg.post("#sprite", "play_animation", {id = hash("heroJump")})
self.currentAnimation = 0
else
msg.post("#sprite", "play_animation", {id = hash("idle")})
end
end
With this code it doesn't jump, i have tried other code but act like a loop making the jumping animation over a over, i just want it to jump every time i pressed the designated button.
The currentAnimation is surely not a method, it is a field of a table that happens to be named self.
It is anyone's guess what purpose is achieved with the line local currentAnimation = 0, it is never used afterwards.
Apparently, it seems that the code you've provided is used to describe behavior of an object (in truth, lua table). According to manual in defold framework you implement behaviors using message passing between different objects and by subscribing listeners to event relevant to your object.
The init, final,update, on_message and, importantly, on_input are all event handlers you define for particular events. The game engine then calls those whenever it decides to do so.
While handling event of pressed button, your object uses the line
msg.post("#sprite", "play_animation", {id = hash("runRight")})
to send message to engine indicating that it should draw something and probably perform some behaviors defined elsewhere.
The above code implements character as a simple finite state automata. currentAnimation is a variable indicating current state, 1 is for standing still, 0 is for running. The code inside if operator handles the transition between states. The way you've currently done it, it'll take two keypresses to change direction of running.
Your on_input event handler receives action table, which describes the event, it then filters events handling only the right button pressed down if action_id == hash("right") and action.pressed == true then (and your addition checks for left button). According to documentation, you can also check for button being released by checking field action.released. If you want the character to stop, you should add corresponding branch in the event handler. They have a bunch of examples there. You can combine those to implement behavior you want.
Related
I'm new to programming in LUA, although I've learned similar languages like JS. It's frustrating if I have to alter the same script in many parts in a group by replacing each script, and I don't know of an elegant way to do it. Instead, I decided to nest all the parts inside of the script. I've seen some examples and I've tried to adapt some of them, but they don't exactly apply to what I want to do and I can't get them to work.
In essence, what I'm trying to do is monitor all the bricks for a player to contact them. I took the original disappearing brick script that was nested inside each brick and modified it. If a part (brick) is touched, that should call the onTouch function, which will make the brick's transparency decrease over time until the in pairs loop is done, after which the brick disappears and CanCollide is turned off. After 2 seconds, it then returns back to normal. I think the problem is with the coding I used to monitor the parts as I don't really understand the right way to monitor multiple objects. Can someone please help? Thanks!
File structure:
function onTouched(brick)
local delay = .1 -- the delay between each increase in transparency (affects speed of disappearance)
local RestoreDelay = 2 -- delay before the brick reappears
local inc = .1 -- how much the brick disappears each time
-- All characters have a Humanoid object
-- if the model has one, it is a character
local h = script.Child:findFirstChild("Humanoid") -- Find Humanoids in whatever touched this
if (h ~=nil) then -- If there is a Humanoid then
h.Health = h.MaxHealth -- Set the health to maximum (full healing)
for x=0,1, inc do
script.Child.Transparency = x+inc
script.Child.CanCollide = true
wait(delay)
end
wait(delay)
script.Child.Transparency = 1
script.Child.CanCollide = false
wait(RestoreDelay)
script.Child.Transparency = 0
script.Child.CanCollide = true
else
end
end
while true do
local bricks=script:GetChildren():IsA("basic.part")
for x=1,brick in pairs(bricks) do
brick.Touched:connect(onTouched(brick)) -- Make it call onTouched when touched
end
end
end
For the most part, you've gotten it right, but you've got a few syntax errors where there are different conventions between JavaScript and Lua.
In JS, you would fetch an array of objects and then bee able to filter it immediately, but in Lua, there is limited support for that. So a JavaScript line like :
var bricks = script.GetChildren().filter(function(item) {
return item === "basic.part"
})
cannot be done all in one line in Lua without assistance from some library. So you'll need to move the check into the loop as you iterate over the objects.
Other than that, the only other thing to change is the onTouched handler's function signature. The BasePart.Touched event tells you which object has touched the brick, not the brick itself. But by creating a higher order function, it's easy to get access to the brick, and the thing that touched it.
-- create a helper function to access the brick and the thing that touched it
function createOnTouched(brick)
-- keep track whether the animation is running
local isFading = false
return function(otherPart)
-- do not do the animation again if it has already started
if isFading then
return
end
local delay = .1 -- the delay between each increase in transparency (affects speed of disappearance)
local restoreDelay = 2 -- delay before the brick reappears
local inc = .1 -- how much the brick disappears each time
-- All characters have a Humanoid object, check for one
local h = otherPart.Parent:FindFirstChild("Humanoid")
if h then
-- heal the player
h.Health = h.MaxHealth
-- start fading the brick
isFading = true
brick.CanCollide = true
for i = 0, 1, inc do
brick.Transparency = i
wait(delay)
end
-- turn off collision for the brick
wait(delay)
brick.Transparency = 1
brick.Anchored = true
brick.CanCollide = false
-- turn the part back on
wait(restoreDelay)
brick.Transparency = 0
brick.CanCollide = true
-- reset the animation flag
isFading = false
end
end
end
-- loop over the children and connect touch events
local bricks = script:GetChildren()
for i, brick in ipairs(bricks) do
if brick:IsA("BasePart") then
local onTouchedFunc = createOnTouched(brick)
brick.Touched:Connect(onTouchedFunc)
end
end
I have this sprite: spr_meteoriteLv3, which has two sub-images with index image_index 0 and 1 respectively.
I have these objects: obj_meteoriteLv3, obj_tempMeteoriteLv3, and obj_score. Object obj_meteoriteLv3 spawns from above with random position, random amount, and random sub-image. Object obj_tempMeteoriteLv3 makes obj_meteoriteLv3s spawn. When player clicks on a meteorite, the program checks the value of image_index for that object.
obj_meteoriteLv3 has these events:
Create Event: change sprite_index into spr_meteoriteLv3, and start moving downwards.
Left-pressed Mouse Event: destroy the self instance, and check image_index: if image_index == 0 then score += 5; else score -= 5).
obj_tempMeteoriteLv3 has these events:
Create Event: set Alarm 0 to 3600, set variable exist to 1, and set variable add to 1.
Alarm 0: set variable add to 0, and destroy the obj_meteoriteLv3 instance.
Alarm 1: set variable exist to 1.
Step Event: if (exist == 1) then, if (add == 1) then create instance of obj_meteoriteLv3, set variable exist to 0, and set Alarm 1 to 10.
obj_score has these events:
Create Event: set score to 0.
Draw Event: draw the value of score.
The problem is, no matter which sub-image the meteorite image_index has when clicked, the score will always be incremented by 5 points. It's like the else condition isn't working. How can I fix this? Please explain your answer. Thanks.
I add some images for better understanding. Link 1. Link 2
In obj_meteoriteLv3 it's being destroyed before it can execute the rest of the code blocks. Move "Destroy Instance" to the bottom.
In obj_tempMeteoriteLv3 both variables "add" and "exist" are not necessary, instead have-
Create Event-
alarm[0] = 3600
alarm[1] = 10
Alarm[0] Event-
destroy_instance
Alarm[1] Event
Create_instance of obj_meteoriteLv3
alarm[1] = 10
Potentially, when you click, every single meteorite is triggered.
On the left click event of the meteorite, you did not check if the cursor was on the sprite. You have to use the position_meeting function, to which you pass the mouse position and the instance to click.
it would look like :
if (position_meeting(mouse_x, mouse_y, id))
{
//your destroy code
}
Moreover, when the instance_destroy(); line is read, the following code is ignored and the program jumps to the destroy_event. William explained it well and suggested to change the order of the lines of code, but you can also change the score in the destroy event directly.
I would like to add that checking for clicks in every instance of the meteorites is not optimal for performances.
My recommendation would be to use a single object to check for clicks (your player or your meteorite spawner, for example), in which you would check for clicks, and if a meteorite is touched, you would trigger it's destroy event. And in this event, you would increment the score and check the sprite.
Your click event would look like :
with (instance_position(mouse_x, mouse_y, obj_meteoriteLv3))
{
instance_destroy();
}
and in the meteorite destroy event, you would check the image_index and change the score accordingly.
EDIT : why the score doesn't change
I believe you didn't declare the score as a global variable, but as an instance variable. So when you write "score = ..." in an other object, it creates a new score variable, unrelated to the precedent.
You have 2 options :
1 - Declare the score a global variable in the create event of obj_score:
globalvar score;
score = //your starting score
Be aware that a global variable can't be set on it's initialisation line.
2 - Change the score through the score object :
whenever the score has to change :
obj_score.score = ...
I have a local sub that allows the user to move a row of a datagridview, triggered by a button click. The sub works fine in debugger but when it exits control is transfered to the calling form, i.e. the current form is closed. This also happens when no row is moved, i.e. when one of the abort conditions on entrance are met. Simply: exiting this sub will close the form!?!
Private Sub btnMove_Click(sender As Object, e As EventArgs) Handles btnMove.Click
Dim rowToGo As DataGridViewRow
Dim rtgIndex As Integer = 0
If (dgvAuftrag.RowCount <= 1) or (dgvAuftrag.CurrentRow Is Nothing) Then
Beep()
Exit Sub
End If
rowToGo = dgvAuftrag.CurrentRow
rtgIndex = rowToGo.Index + 1
If (rtgIndex >= dgvAuftrag.RowCount) Then rtgIndex = 0
Try
dgvAuftrag.Rows.Remove(rowToGo)
dgvAuftrag.Rows.Insert(rtgIndex, rowToGo)
Catch ex As Exception
IssueErrorMessage(ex)
End Try
End Sub
All other local subs and functions work normal, just this one behaves strange. Any ideas how to fix/avoid this bug?
This is not a solution of the problem but a functioning workaround based on the sugestion of Hans. I have introduced a global boolean var named OKtoExit which is intialized to false.
private OKtoExit as boolean = false
Then I have a new FormClose event handler that checks that var. If OKtoExit is false then e.Cancel = true and the handler exits. The regular Exit functions (Save and Quit) set OKtoExit to true, any other code leaves the values unchanged.
Private Sub Current_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If Not exitOK Then
e.Cancel = True
Exit Sub
End If
End Sub
As I said, this is just a workaround that has the same effect as a normal functioning VB-Code. I would appreciate if somebody could present a real solution!
After many months I discovered the true reason for the problem and I must give all credits to Hans Passant: I had a button on one of the first forms that had the Dialog Result property set to Cancel. This was a really beautyful button so many other buttons in the appliaction were a copy of this first button where I just modified the label. Thus they all led to the unwanted behavior that a form was closed as soon as a user clicked one of them no matter what the label said... After months I discovered that just by chance. Thanks to Hans again, I obviously overlooked his last hint "And look at the button's DialogResult property."!
So I was wondering how to change an image of character I've created depending on the key I've pressed/am pressing?
My ultimate going to to have a walking animation occuring when "d" (or any of the wasd keys) is pressed but then he stands still when the "d" key has just been pressed etc. All images have been created already.
I've tried this but it didn't work out:
function love.load()
if love.keyboard.isDown("a") then
hero = love.graphics.newImage("/hero/11.png")
elseif love.keyboard.isDown("d") then
hero = love.graphics.newImage("/hero/5.png")
elseif love.keyboard.isDown("s") then
hero = love.graphics.newImage("/hero/fstand.png")
elseif love.keyboard.isDown("w") then
hero = love.graphics.newImage("/hero/1.png")
end
function love.draw()
love.graphics.draw(background)
love.graphics.draw(hero, x, y)
end
You must understand how LÖVE works. It (very basically) does this:
love.load() -- invoke love.load just once, at the beginning
while true do -- loop that repeats the following "forever" (until game ends)
love.update(dt) -- call love.update()
love.draw() -- call love.draw()
end
This schema is so frequent that the loop itself has a name - it's called The Game Loop.
Your code does't work because you are using love.load() as if it was part of the game loop, but it isn't. It's called at the beginning, during the first millisecond or so of your program, and never again.
You want to use love.load do load the images, and love.update to change them:
function love.load()
heroLeft = love.graphics.newImage("/hero/11.png")
heroRight = love.graphics.newImage("/hero/5.png")
heroDown = love.graphics.newImage("/hero/fstand.png")
heroUp = love.graphics.newImage("/hero/1.png")
hero = heroLeft -- the player starts looking to the left
end
function love.update(dt)
if love.keyboard.isDown("a") then
hero = heroLeft
elseif love.keyboard.isDown("d") then
hero = heroRight
elseif love.keyboard.isDown("s") then
hero = heroDown
elseif love.keyboard.isDown("w") then
hero = heroUp
end
end
function love.draw()
love.graphics.draw(background)
love.graphics.draw(hero, x, y)
end
The code above has certain repetitiveness that can be factored out using tables, but I've left it simple on purpose.
You will also notice that I have included the dt parameter in the love.update function. This is important, since you will need it to make sure that animations work the same in all computers (the speed at which love.update is called depends on each computer, and dt allows you to cope with that)
Nevertheless, if you want to do animations, you will probably want to use this Animation Lib or my own.
I have a form with 2 text inputs and 2 span controls. Normally, when textbox A is changed an event is fired to change span A, and when textbox B is changed, an event is fired to change span B.
However, in one particualar case I would like a change either textbox A or textbox B to update both span A and B. I tried wiring the events up to the corresponding controls in this case, but it didn't work because there is much state that is set up in the event building code (not to mention each event calls 'this', which would make the logic use the wrong control if it were fired from a different one than it was intended).
To make things easy, it would be best to pass a string (representing the other text input id) to the event handler at the time it is created, and then calling the change() event manually on the second control. However, this puts things in an infinite loop of recursion. I thought of a way to get around the recursion, but it reqires a global variable.
Is there a better way than this, preferably one that doesn't require a global variable?
ml_inEvent = false;
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event) {
// Other processing happens here...
if (event.data.controlToFire != '') {
var $controlToFire = $('#' + event.data.controlToFire);
if ($controlToFire.length) {
// Use a global variable to ensure this event is not fired again
// as a result of calling the other one
if (!ml_inEvent) {
ml_inEvent = true;
$controlToFire.change();
ml_inEvent = false;
}
}
}
});
You can use the extraParameters argument on .trigger() to break out, for example:
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event, fire) {
// Other processing happens here...
if(fire !== false) $('#' + event.data.controlToFire).trigger('change', false);
});
You can give it a try here. What this does is the event handler callback not only receives the event object but also any other arguments you pass in, in this case we're just using a simple false and a !=== check this in important so undefined (the parameter not passed at all) still changes both controls. So for instance $("#control").change() would change both controls, but still not loop...you can test that here.