Separate State Machine per class instance?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
lowercasename
Prole
Posts: 2
Joined: Tue Sep 21, 2021 11:46 pm

Separate State Machine per class instance?

Post by lowercasename »

I'm a novice at Lua, so forgive me if the answe to this is very obvious! I'm using the delightful lua-state-machine (https://github.com/kyleconroy/lua-state-machine) and the hump.class (https://github.com/vrld/hump) libraries, although I tried the same code with a different class library and it did the same thing so I suspect the issue is not necessarily down to a library, but to how I'm combining them.

I create a class:

Code: Select all

Actor = Class {
  x = 0,
  y = 0,
  state = machine.create( ... )
}

actors = {}
cow = Actor()
moon = Actor()
table.insert(actors, cow)
table.insert(actors, moon)
I then change the state of one of the instances in my love.mousepressed() function:

Code: Select all

for i,actor in ipairs(actors)
  if actor.x == mouseX and actorY == mouseY then
    actor.state:jump()
  end
then
At this point, both instances switch to the state 'jumping', even though only one of them was clicked. Is this due to some sort of interaction between the state machine and the class, or is it an issue in my for loop? Can I have a separate state machine per instance?
grump
Party member
Posts: 817
Joined: Sat Jul 22, 2017 7:43 pm

Re: Separate State Machine per class instance?

Post by grump »

That's because you create only one state machine and put it in the class. You need to create one per instance and put it in each instance instead. The constructor is a good place to do that.

Code: Select all

Actor = Class {
  init = function(self, x, y)
    self.x, self.y = x or 0, y or 0
    self.state = machine.create(...)
  end,
}

cow = Actor(1, 2)
moon = Actor(5, 6)
lowercasename
Prole
Posts: 2
Joined: Tue Sep 21, 2021 11:46 pm

Re: Separate State Machine per class instance?

Post by lowercasename »

Ah thank you so much, it seems so obvious now it isn't 1 in the morning!
Post Reply

Who is online

Users browsing this forum: No registered users and 12 guests