when i run this i get it printed twice but my intension was to print it only once. so what is the concept behind it
hello should be printed only once
but it is not!
Hello! Sensors have 4 triggered/input states:
If you don’t tell when you want to print hello, hello will be print once when the sensor is just activated, once per frame while the sensor is active, and once when the sensor is just released.
Your controller triggers twice. Any time a sensor triggers a controller, it will run the code. Sensors trigger for different reasons, but with keyboard / mouse sensors, when a key is pressed it sends a trigger and when it is released it sends a trigger. You can tell the first trigger from the second by the sensor state. The sensor is positive when the key is pressed, and negative when released:
def some_method(cont): sens = cont.sensors['Always'] if not sens.positive: return print("Hello")
You should use the controller in module mode. To do this, copy this code into a text file called “xxx.py”, where xxx is a name of your choosing, with no spaces or mathematical symbols etc… (a valid module name). In the Python controller, you would enter “xxx.some_method” into the module field (with mode set to module, not script), where xxx is as before, and some_method is the name of the function above.
This checks if a sensor called ‘Always’ is positive.
how to get the time or frame interval bw positive and negative pulse.
iin case of keyboard sensor
Either using a timer property and reading the successive times if the sensor is positive and if the sensor is negative (all of which can be done in logic bricks), or using the time module:
from time import monotonic def some_method(cont): own = cont.owner sens = cont.sensors['Mouse'] if sens.positive: own['pressed_time'] = monotonic() else: delta_time = monotonic() - own['pressed_time'] print(delta_time)