How to set object's state in python?

I’m struggling with this and I’ve tried several ways and nothing worked so far.
Basically, I want to set an object’s state through python.
I have this script:

collision = cont.sensors['dynamics']
    
    if collision.positive:
        
        objects_list = collision.hitObjectList
        
        if objects_list:
            
            for obj in objects_list:
                
                obj.suspendDynamics()
                obj.state = 16 #this is where I want to change the object's state

WHy don’t youwant to use logic bricks, just add a collision sensor, set it to true, click the 2 quotation marks that are upwards. the add a state actuator and change it to the state yourself. It is easier to do with logic bricks.

Because this collision is for many instances of several objects with the same property name.
This way it’s way cleaner.

So you want to set the sixteenth or fifth state? Remember that it’s a bitmask.

0b01 == 1 -> first state
0b10 == 2 -> second state
0b11 == 3 -> first and second

Each individual state is a power of two. 2 ** n where n is the (1 + n)th state; Zero is first and twenty-nine is thirtieth.

obj.state = 2 ** 16 = 65536 = 0b10000000000000000
obj.state = 2 ** 4  = 16    = 0b00000000000010000

But if you wanted to set the fifth state then your code is correct. If the state was never set then something else is wrong.

1 Like

Oh, that’s why it activated the state I didn’t wanted.
Is there a list of what should I write for states or just write: 2 ** 1, 2 ** 2, 2 ** 3 and so on?

print([2**i for i in range(30)]) to see all possible (non-combined) values.

Ok, thank you, I’ll try that.

So basically, for a state 16 it’s number 32768.
That’s how it works?
It seems that 2 ** 15 works the same.
What’s better to use? 32768 or 2 ** 15?

Using a constant instead of calculating it every single time should be cheaper, though it is very much a minimal optimization. Just like multiplying by 0.5 is supposedly faster than dividing by 2 it’s not something that’ll really come into play until you’re doing it a fairly large number of times (say above the range of a few hundred thousand per frame).

If you’re interested in more precisely benchmarking performance on these kinds of things, time it. Untested code, but it goes along the lines of:

import time

num_iterations = 100;
bench          = [0.0 for i in range(num_iterations)]

for i in range(len(bench)):
    start = time.time();

    #operations to test go here

    end = time.time();
    bench[i] = end - start;

print("Average execution time: %f"%(sum(bench) / num_iterations))

1 Like