# BGE - Calculate Acceleration from Velocity

I need to calculate acceleration of my rigid-body object in Blender Game Engine. What I did now is:

from bge import logic
from mathutils import Vector

if not "prevspeed" in own:
own["prevspeed"] = Vector((0, 0, 0))
speed = ob.localLinearVelocity
acceleration = speed - own["prevspeed"] * logic.getAverageFrameRate()
own["prevspeed"] = ob.localLinearVelocity.copy()


However, this doesn't seem to work. I need to know how to make it work correctly.

• Be aware speed is not velocity (as mentioned in your code). Velocity is a vector (direction and length). Speed is the length of Velocity. – Monster Mar 8 '16 at 13:55

"I need to know how to make it work correctly."

that will take some work on your script.

First off, there are many problems with your script. The most obvious being a syntax error. you should have another ) after Vector((0, 0, 0). Second, you do not define own or ob. But the worst error, is you can not define a vector on a game property. There is no property type called vector The five property types are Boolean, Integer, Float, String, and Timer. If you try to assign a vector to a game property, the only one that would come close to working is the String property, and that wouldn't do much in the realm of usefulness.

I would not actually use the method you are trying to use. I would calculate Acceleration like this:

import bge
from mathutils import Vector

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

previous_velocity = Vector(obj.worldLinearVelocity)

def main():
global previous_velocity

current_velocity = Vector(obj.worldLinearVelocity)

acceleration = (current_velocity - previous_velocity) * bge.logic.getAverageFrameRate()
print(acceleration)

previous_velocity = current_velocity


Also, you must reference this bit of python by calling it from a module controller, not a script controller.

• This script is not directly copied from the game code. In game code I store previouse speed in a class. Oh, and if you define property in python, it can be anything, because KX_GameObject is actually a dictionary that you can manipulate freely(try print obj). However, it doesn't work for me this way. – Adrians Netlis Mar 8 '16 at 18:43
• Oh, and the end of the script - it wouldn't work without copy(). IDK why, but it just wouldn't. – Adrians Netlis Mar 8 '16 at 19:30
• OK! My problem was where I execute everything. I have fixed all now. I'll check your answer as correct anyways as it at least includes rightm math. – Adrians Netlis Mar 8 '16 at 19:34
• Some corrections: Since 2.49 you can store any object in a game property. A KX_GameObject is a class not a dictionary. – Monster Mar 9 '16 at 5:05