How to work out object speed in game?

Speed.py:


try:
  from Mathutils import Vector
except ImportError:
  from mathutils import Vector
 
def speedToValue(cont):
  if not onePositive(cont):
    return
 
  own = cont.owner
  speedVector = Vector(own.getLinearVelocity())
  speed = speedVector.magnitude
 
  for actuator in cont.actuators:
    try:
      actuator.value = str(speed)
    except AttributeError:
      continue
    cont.activate(actuator)
 
def onePositive(cont):
  for sensor in cont.sensors:
    if sensor.positive:
      return True
  return False

use a sensor of your choice (e.g. an Always sensor)
connected to
a Python controller in Module Mode: Speed.speedToValue
connected to any number of actuators

  • if it is an Property actuator the value field will be filled with the speed and the actuator will be activated. The property actuator will copy the new value to the configured property (dependent on the mode). All other actuators will be ignored.

Example:

Property (any type): Speed

Always sensor TRUE Pulse
—> Python Module: Speed.speedToValue
-------> Property actuator Mode: Assign Prop: Speed Value: empty
if you switch on proeprty debug, you can see the speed in the debup overlay ;).

I hope it helps
Monster