one action for many objects

Help and examples in this topic, there is free and extended help on BGE.

Hi there.
This is a simple code that passes the speed to the object.

import bge

def main():

    cont = bge.logic.getCurrentController()
    own = cont.owner

    coll = cont.sensors['coll']
    vel = own.getLinearVelocity(True)
    
    if coll.positive:
        obj = coll.hitObject
        obj.setLinearVelocity(vel)
    
    if own["dir"] == True:
        own.applyMovement([0.0, 0.06, 0.0], True)
    else:
        own.applyMovement([0.0, -0.06, 0.0], True)
               
main()

Only this affects one object (the first one that touched). How can I make that the speed of the platform is transferred to all the objects that are on it?

Thank you for attention.


import bge

controller = bge.logic.getCurrentController()
owner = cont.owner

collisionSensor = cont.sensors['coll']
velocity = own.getLinearVelocity(True)

    
if collisionSensor.positive:
    for hitObject in collisionSensor.hitObjectList:
        hitObject.setLinearVelocity(velocity)

    # this has nothing to do with the hit objects
    if owner["dir"]:
        owner.applyMovement([0.0, 0.06, 0.0], True)
    else:
        owner.applyMovement([0.0, -0.06, 0.0], True)
               

Basically you do not just look at the single result (hitObject) but all results (hitObjectList) and iterate over it.

Remarks:

  • no need to wrap the code inside a function (especially as the function name does not serve any additional information)
  • renamed the abbreviations to more descriptive names for better comprehension
  • “if booleanValue == True:” is a double check. The “if” expects a boolean expression. The expession is a boolean expression already. Shortened to “if booleanValue:”
  • I do not understand, are you the cleverest here? I’m even shocked … :evilgrin: did you leave a error specially?
    Thank you for the exhaustive answer! Many objects on the platform already …

I’m surely not the cleverest. This is just something I needed pretty often already. I haven’t tested the code. There might be typos or indentation errors.

I see: I forgot to rename some “cont” to “controller”

  • come on, I’m joking - everything is normal, man!:yes: