Simple Python

Why does my object keep moving even when I am not holding down the key? Very simple python that I can’t seem to do.

Here is the sample blend, if anyone could have a quick look that would be great!

http://www.box.net/shared/iizpoa1yvn#pythontest

Keys, W, A, D, S

Blender is a little weird on this issue:

Sensors fire 2 kinds of pulses, True and False. For example, a keyboard sensor, by default and when pressed, fires 1 True pulse when it is pressed and then 1 False pulse when it is released. If the little button in the top left (tooltip reads “Activate TRUE level triggering (pulse mode)”) then it sends a pulse every logic tic while the keyboard button is pressed (ie it fires more than 1 pulse).

Some actuators will only fire when they receive “True” pulses. The Property actuator is an example of this… 1 true pulse with an actuator that increments a property by 1 will only increment that property by 1. If you sent it multiple pulses, it would increment by 1 for each pulse.

However, some actuators, like the motion actuator, will activate when it gets a True pulse and then continue to be active UNTIL it gets a False pulse. It doesn’t matter if there aren’t any True pulses getting through, if it hasn’t gotten a False pulse then it keeps going.

The python command “GameLogic.addActiveActuator(dir, 1)” basically sends a True pulse to the motion actuator. However, there’s nothing in the script to give a False pulse to the actuator, so it keeps on going.

One way to handle this would be to do a check to see if none of your keyboard sensors are active, and if they’re not, use GameLogic.addActiveActuator(dir, 0). 0 will send a False pulse. However, it’s much easier to just set the motion actuator to do nothing.

Here’s the code as I would recommend it:


cont = GameLogic.getCurrentController()
own = cont.getOwner()

dir = cont.getActuator("Move")
fwd = cont.getSensor("Forward")
bck = cont.getSensor("Back")
lft = cont.getSensor("Left")
rht = cont.getSensor("Right")

if own.walk == 1:
    F = 0
    B = 0
    R = 0
    L = 0

    if fwd.isPositive():
        F  = .4

    if bck.isPositive():
        B = -.4

    if lft.isPositive():
        L = -.4

    if rht.isPositive():
        R = .4

    dir.setDLoc(L+R, F+B, 0.0, 1)
    GameLogic.addActiveActuator(dir, 1)

Note: If you copy and paste this code, make sure you change the spaces into the appropriate tabs.

This also will allow you to move in more than 1 direction at once. You can see that when none of the keys are pressed, F B L and R are all 0. Even if none of the keys are being pressed, the motion actuator’s values are being set.

Hope that helps!

-Sam

Yes, do what TheSambassador showed. That is pretty close to how I handle my movement scripts.

I see, your using properties to control the script. Thanks so much for the large explaining, I would have been stuck on this issue for years!