KX_GameObject(SCA_IObject)

base class — SCA_IObject

class bge.types.KX_GameObject(SCA_IObject)

All game objects are derived from this class.

Properties assigned to game objects are accessible as attributes of this class.

Note

Calling ANY method or attribute on an object that has been removed from a scene will raise a SystemError, if an object may have been removed since last accessing it use the invalid attribute to check.

KX_GameObject can be subclassed to extend functionality. For example:

import bge

class CustomGameObject(bge.types.KX_GameObject):
    RATE = 0.05

    def __init__(self, old_owner):
        # "old_owner" can just be ignored. At this point, "self" is
        # already the object in the scene, and "old_owner" has been
        # destroyed.

        # New attributes can be defined - but we could also use a game
        # property, like "self['rate']".
        self.rate = CustomGameObject.RATE

    def update(self):
        self.worldPosition.z += self.rate

        # switch direction
        if self.worldPosition.z > 1.0:
            self.rate = -CustomGameObject.RATE
        elif self.worldPosition.z < 0.0:
            self.rate = CustomGameObject.RATE

# Called first
def mutate(cont):
    old_object = cont.owner
    mutated_object = CustomGameObject(cont.owner)

    # After calling the constructor above, references to the old object
    # should not be used.
    assert(old_object is not mutated_object)
    assert(old_object.invalid)
    assert(mutated_object is cont.owner)

# Called later - note we are now working with the mutated object.
def update(cont):
    cont.owner.update()

When subclassing objects other than empties and meshes, the specific type should be used - e.g. inherit from BL_ArmatureObject when the object to mutate is an armature.

name

The object’s name. (read-only).

Type:string
mass

The object’s mass

Type:float

Note

The object must have a physics controller for the mass to be applied, otherwise the mass value will be returned as 0.0.

isSuspendDynamics

The object’s dynamic state (read-only).

Type:boolean

See also

suspendDynamics() and restoreDynamics() allow you to change the state.

linearDamping

The object’s linear damping, also known as translational damping. Can be set simultaneously with angular damping using the setDamping() method.

Type:float between 0 and 1 inclusive.

Note

The object must have a physics controller for the linear damping to be applied, otherwise the value will be returned as 0.0.

angularDamping

The object’s angular damping, also known as rotationation damping. Can be set simultaneously with linear damping using the setDamping() method.

Type:float between 0 and 1 inclusive.

Note

The object must have a physics controller for the angular damping to be applied, otherwise the value will be returned as 0.0.

linVelocityMin

Enforces the object keeps moving at a minimum velocity.

Type:float

Note

Applies to dynamic and rigid body objects only.

Note

A value of 0.0 disables this option.

Note

While objects are stationary the minimum velocity will not be applied.

linVelocityMax

Clamp the maximum linear velocity to prevent objects moving beyond a set speed.

Type:float

Note

Applies to dynamic and rigid body objects only.

Note

A value of 0.0 disables this option (rather than setting it stationary).

angularVelocityMin

Enforces the object keeps rotating at a minimum velocity. A value of 0.0 disables this.

Type:non-negative float

Note

Applies to dynamic and rigid body objects only. While objects are stationary the minimum velocity will not be applied.

angularVelocityMax

Clamp the maximum angular velocity to prevent objects rotating beyond a set speed. A value of 0.0 disables clamping; it does not stop rotation.

Type:non-negative float

Note

Applies to dynamic and rigid body objects only.

localInertia

the object’s inertia vector in local coordinates. Read only.

Type:Vector((ix, iy, iz))
parent

The object’s parent object. (read-only).

Type:KX_GameObject or None
groupMembers

Returns the list of group members if the object is a group object (dupli group instance), otherwise None is returned.

Type:CListValue of KX_GameObject or None
groupObject

Returns the group object (dupli group instance) that the object belongs to or None if the object is not part of a group.

Type:KX_GameObject or None
collisionGroup

The object’s collision group.

Type:bitfield
collisionMask

The object’s collision mask.

Type:bitfield
collisionCallbacks

A list of functions to be called when a collision occurs.

Type:list of functions and/or methods

Callbacks should either accept one argument (object), or three arguments (object, point, normal). For simplicity, per colliding object only the first collision point is reported.

# Function form
def callback_three(object, point, normal):
    print('Hit by %r at %s with normal %s' % (object.name, point, normal))

def callback_one(object):
    print('Hit by %r' % object.name)

def register_callback(controller):
    controller.owner.collisionCallbacks.append(callback_three)
    controller.owner.collisionCallbacks.append(callback_one)


# Method form
class YourGameEntity(bge.types.KX_GameObject):
    def __init__(self, old_owner):
        self.collisionCallbacks.append(self.on_collision_three)
        self.collisionCallbacks.append(self.on_collision_one)

    def on_collision_three(self, object, point, normal):
        print('Hit by %r at %s with normal %s' % (object.name, point, normal))

    def on_collision_one(self, object):
        print('Hit by %r' % object.name)

Note

For backward compatibility, a callback with variable number of arguments (using *args) will be passed only the object argument. Only when there is more than one fixed argument (not counting self for methods) will the three-argument form be used.

scene

The object’s scene. (read-only).

Type:KX_Scene or None
visible

visibility flag.

Type:boolean

Note

Game logic will still run for invisible objects.

record_animation

Record animation for this object.

Type:boolean
color

The object color of the object. [r, g, b, a]

Type:mathutils.Vector
occlusion

occlusion capability flag.

Type:boolean
position

The object’s position. [x, y, z] On write: local position, on read: world position

Deprecated since version use: localPosition and worldPosition.

Type:mathutils.Vector
orientation

The object’s orientation. 3x3 Matrix. You can also write a Quaternion or Euler vector. On write: local orientation, on read: world orientation

Deprecated since version use: localOrientation and worldOrientation.

Type:mathutils.Matrix
scaling

The object’s scaling factor. [sx, sy, sz] On write: local scaling, on read: world scaling

Deprecated since version use: localScale and worldScale.

Type:mathutils.Vector
localOrientation

The object’s local orientation. 3x3 Matrix. You can also write a Quaternion or Euler vector.

Type:mathutils.Matrix
worldOrientation

The object’s world orientation. 3x3 Matrix.

Type:mathutils.Matrix
localScale

The object’s local scaling factor. [sx, sy, sz]

Type:mathutils.Vector
worldScale

The object’s world scaling factor. [sx, sy, sz]

Type:mathutils.Vector
localPosition

The object’s local position. [x, y, z]

Type:mathutils.Vector
worldPosition

The object’s world position. [x, y, z]

Type:mathutils.Vector
localTransform

The object’s local space transform matrix. 4x4 Matrix.

Type:mathutils.Matrix
worldTransform

The object’s world space transform matrix. 4x4 Matrix.

Type:mathutils.Matrix
localLinearVelocity

The object’s local linear velocity. [x, y, z]

Type:mathutils.Vector
worldLinearVelocity

The object’s world linear velocity. [x, y, z]

Type:mathutils.Vector
localAngularVelocity

The object’s local angular velocity. [x, y, z]

Type:mathutils.Vector
worldAngularVelocity

The object’s world angular velocity. [x, y, z]

Type:mathutils.Vector
timeOffset

adjust the slowparent delay at runtime.

Type:float
state

the game object’s state bitmask, using the first 30 bits, one bit must always be set.

Type:int
meshes

a list meshes for this object.

Type:list of KX_MeshProxy

Note

Most objects use only 1 mesh.

Note

Changes to this list will not update the KX_GameObject.

sensors

a sequence of SCA_ISensor objects with string/index lookups and iterator support.

Type:list

Note

This attribute is experimental and may be removed (but probably wont be).

Note

Changes to this list will not update the KX_GameObject.

controllers

a sequence of SCA_IController objects with string/index lookups and iterator support.

Type:list of SCA_ISensor

Note

This attribute is experimental and may be removed (but probably wont be).

Note

Changes to this list will not update the KX_GameObject.

actuators

a list of SCA_IActuator with string/index lookups and iterator support.

Type:list

Note

This attribute is experemental and may be removed (but probably wont be).

Note

Changes to this list will not update the KX_GameObject.

attrDict

get the objects internal python attribute dictionary for direct (faster) access.

Type:dict
children

direct children of this object, (read-only).

Type:CListValue of KX_GameObject‘s
childrenRecursive

all children of this object including children’s children, (read-only).

Type:CListValue of KX_GameObject‘s
life

The number of seconds until the object ends, assumes 50fps. (when added with an add object actuator), (read-only).

Type:float
debug

If true, the object’s debug properties will be displayed on screen.

Type:boolean
debugRecursive

If true, the object’s and children’s debug properties will be displayed on screen.

Type:boolean
currentLodLevel

The index of the level of detail (LOD) currently used by this object (read-only).

Type:int
endObject()

Delete this object, can be used in place of the EndObject Actuator.

The actual removal of the object from the scene is delayed.

replaceMesh(mesh, useDisplayMesh=True, usePhysicsMesh=False)

Replace the mesh of this object with a new mesh. This works the same was as the actuator.

Parameters:
  • mesh (MeshProxy or string) – mesh to replace or the meshes name.
  • useDisplayMesh (boolean) – when enabled the display mesh will be replaced (optional argument).
  • usePhysicsMesh (boolean) – when enabled the physics mesh will be replaced (optional argument).
setVisible(visible, recursive)

Sets the game object’s visible flag.

Parameters:
  • visible (boolean) – the visible state to set.
  • recursive (boolean) – optional argument to set all childrens visibility flag too.
setOcclusion(occlusion, recursive)

Sets the game object’s occlusion capability.

Parameters:
  • occlusion (boolean) – the state to set the occlusion to.
  • recursive (boolean) – optional argument to set all childrens occlusion flag too.
alignAxisToVect(vect, axis=2, factor=1.0)

Aligns any of the game object’s axis along the given vector.

Parameters:
  • vect (3D vector) – a vector to align the axis.
  • axis (integer) –

    The axis you want to align

    • 0: X axis
    • 1: Y axis
    • 2: Z axis
  • factor (float) – Only rotate a feaction of the distance to the target vector (0.0 - 1.0)
getAxisVect(vect)

Returns the axis vector rotates by the object’s worldspace orientation. This is the equivalent of multiplying the vector by the orientation matrix.

Parameters:vect (3D Vector) – a vector to align the axis.
Returns:The vector in relation to the objects rotation.
Return type:3d vector.
applyMovement(movement, local=False)

Sets the game object’s movement.

Parameters:
  • movement (3D Vector) – movement vector.
  • local
    • False: you get the “global” movement ie: relative to world orientation.
    • True: you get the “local” movement ie: relative to object orientation.
  • local – boolean
applyRotation(rotation, local=False)

Sets the game object’s rotation.

Parameters:
  • rotation (3D Vector) – rotation vector.
  • local
    • False: you get the “global” rotation ie: relative to world orientation.
    • True: you get the “local” rotation ie: relative to object orientation.
  • local – boolean
applyForce(force, local=False)

Sets the game object’s force.

This requires a dynamic object.

Parameters:
  • force (3D Vector) – force vector.
  • local (boolean) –
    • False: you get the “global” force ie: relative to world orientation.
    • True: you get the “local” force ie: relative to object orientation.
applyTorque(torque, local=False)

Sets the game object’s torque.

This requires a dynamic object.

Parameters:
  • torque (3D Vector) – torque vector.
  • local (boolean) –
    • False: you get the “global” torque ie: relative to world orientation.
    • True: you get the “local” torque ie: relative to object orientation.
getLinearVelocity(local=False)

Gets the game object’s linear velocity.

This method returns the game object’s velocity through it’s center of mass, ie no angular velocity component.

Parameters:local (boolean) –
  • False: you get the “global” velocity ie: relative to world orientation.
  • True: you get the “local” velocity ie: relative to object orientation.
Returns:the object’s linear velocity.
Return type:Vector((vx, vy, vz))
setLinearVelocity(velocity, local=False)

Sets the game object’s linear velocity.

This method sets game object’s velocity through it’s center of mass, ie no angular velocity component.

This requires a dynamic object.

Parameters:
  • velocity (3D Vector) – linear velocity vector.
  • local (boolean) –
    • False: you get the “global” velocity ie: relative to world orientation.
    • True: you get the “local” velocity ie: relative to object orientation.
getAngularVelocity(local=False)

Gets the game object’s angular velocity.

Parameters:local (boolean) –
  • False: you get the “global” velocity ie: relative to world orientation.
  • True: you get the “local” velocity ie: relative to object orientation.
Returns:the object’s angular velocity.
Return type:Vector((vx, vy, vz))
setAngularVelocity(velocity, local=False)

Sets the game object’s angular velocity.

This requires a dynamic object.

Parameters:
  • velocity (boolean) – angular velocity vector.
  • local
    • False: you get the “global” velocity ie: relative to world orientation.
    • True: you get the “local” velocity ie: relative to object orientation.
getVelocity(point=(0, 0, 0))

Gets the game object’s velocity at the specified point.

Gets the game object’s velocity at the specified point, including angular components.

Parameters:point (3D Vector) – optional point to return the velocity for, in local coordinates.
Returns:the velocity at the specified point.
Return type:Vector((vx, vy, vz))
getReactionForce()

Gets the game object’s reaction force.

The reaction force is the force applied to this object over the last simulation timestep. This also includes impulses, eg from collisions.

Returns:the reaction force of this object.
Return type:Vector((fx, fy, fz))

Note

This is not implimented at the moment.

applyImpulse(point, impulse, local=False)

Applies an impulse to the game object.

This will apply the specified impulse to the game object at the specified point. If point != position, applyImpulse will also change the object’s angular momentum. Otherwise, only linear momentum will change.

Parameters:
  • point (point [ix, iy, iz] the point to apply the impulse to (in world or local coordinates)) – the point to apply the impulse to (in world or local coordinates)
  • impulse (3D Vector) – impulse vector.
  • local (boolean) –
    • False: you get the “global” impulse ie: relative to world coordinates with world orientation.
    • True: you get the “local” impulse ie: relative to local coordinates with object orientation.
setDamping(linear_damping, angular_damping)

Sets both the linearDamping and angularDamping simultaneously. This is more efficient than setting both properties individually.

Parameters:
  • linear_damping (float ∈ [0, 1]) – Linear (“translational”) damping factor.
  • angular_damping (float ∈ [0, 1]) – Angular (“rotational”) damping factor.
suspendDynamics([ghost])

Suspends physics for this object.

Parameters:ghost (bool) – When set to True, collisions with the object will be ignored, similar to the “ghost” checkbox in Blender. When False (the default), the object becomes static but still collide with other objects.

See also

isSuspendDynamics allows you to inspect whether the object is in a suspended state.

restoreDynamics()

Resumes physics for this object. Also reinstates collisions; the object will no longer be a ghost.

Note

The objects linear velocity will be applied from when the dynamics were suspended.

enableRigidBody()

Enables rigid body physics for this object.

Rigid body physics allows the object to roll on collisions.

disableRigidBody()

Disables rigid body physics for this object.

setParent(parent, compound=True, ghost=True)

Sets this object’s parent. Control the shape status with the optional compound and ghost parameters:

In that case you can control if it should be ghost or not:

Parameters:
  • parent (KX_GameObject) – new parent object.
  • compound (boolean) –

    whether the shape should be added to the parent compound shape.

    • True: the object shape should be added to the parent compound shape.
    • False: the object should keep its individual shape.
  • ghost (boolean) –

    whether the object should be ghost while parented.

    • True: if the object should be made ghost while parented.
    • False: if the object should be solid while parented.

Note

If the object type is sensor, it stays ghost regardless of ghost parameter

removeParent()

Removes this objects parent.

getPhysicsId()

Returns the user data object associated with this game object’s physics controller.

getPropertyNames()

Gets a list of all property names.

Returns:All property names for this object.
Return type:list
getDistanceTo(other)
Parameters:other (KX_GameObject or list [x, y, z]) – a point or another KX_GameObject to measure the distance to.
Returns:distance to another object or point.
Return type:float
getVectTo(other)

Returns the vector and the distance to another object or point. The vector is normalized unless the distance is 0, in which a zero length vector is returned.

Parameters:other (KX_GameObject or list [x, y, z]) – a point or another KX_GameObject to get the vector and distance to.
Returns:(distance, globalVector(3), localVector(3))
Return type:3-tuple (float, 3-tuple (x, y, z), 3-tuple (x, y, z))
rayCastTo(other, dist, prop)

Look towards another point/object and find first object hit within dist that matches prop.

The ray is always casted from the center of the object, ignoring the object itself. The ray is casted towards the center of another object or an explicit [x, y, z] point. Use rayCast() if you need to retrieve the hit point

Parameters:
  • other (KX_GameObject or 3-tuple) – [x, y, z] or object towards which the ray is casted
  • dist (float) – max distance to look (can be negative => look behind); 0 or omitted => detect up to other
  • prop (string) – property name that object must have; can be omitted => detect any object
Returns:

the first object hit or None if no object or object does not match prop

Return type:

KX_GameObject

rayCast(objto, objfrom, dist, prop, face, xray, poly, mask)

Look from a point/object to another point/object and find first object hit within dist that matches prop. if poly is 0, returns a 3-tuple with object reference, hit point and hit normal or (None, None, None) if no hit. if poly is 1, returns a 4-tuple with in addition a KX_PolyProxy as 4th element. if poly is 2, returns a 5-tuple with in addition a 2D vector with the UV mapping of the hit point as 5th element.

# shoot along the axis gun-gunAim (gunAim should be collision-free)
obj, point, normal = gun.rayCast(gunAim, None, 50)
if obj:
   # do something
   pass

The face parameter determines the orientation of the normal.

  • 0 => hit normal is always oriented towards the ray origin (as if you casted the ray from outside)
  • 1 => hit normal is the real face normal (only for mesh object, otherwise face has no effect)

The ray has X-Ray capability if xray parameter is 1, otherwise the first object hit (other than self object) stops the ray. The prop and xray parameters interact as follow.

  • prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray.
  • prop off, xray on : idem.
  • prop on, xray off: return closest hit if it matches prop, no hit otherwise.
  • prop on, xray on : return closest hit matching prop or no hit if there is no object matching prop on the full extend of the ray.

The KX_PolyProxy 4th element of the return tuple when poly=1 allows to retrieve information on the polygon hit by the ray. If there is no hit or the hit object is not a static mesh, None is returned as 4th element.

The ray ignores collision-free objects and faces that dont have the collision flag enabled, you can however use ghost objects.

Parameters:
  • objto (KX_GameObject or 3-tuple) – [x, y, z] or object to which the ray is casted
  • objfrom (KX_GameObject or 3-tuple or None) – [x, y, z] or object from which the ray is casted; None or omitted => use self object center
  • dist (float) – max distance to look (can be negative => look behind); 0 or omitted => detect up to to
  • prop (string) – property name that object must have; can be omitted or “” => detect any object
  • face (integer) – normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin
  • xray (integer) – X-ray option: 1=>skip objects that don’t match prop; 0 or omitted => stop on first object
  • poly (integer) –

    polygon option: 0, 1 or 2 to return a 3-, 4- or 5-tuple with information on the face hit.

    • 0 or omitted: return value is a 3-tuple (object, hitpoint, hitnormal) or (None, None, None) if no hit
    • 1: return value is a 4-tuple and the 4th element is a KX_PolyProxy or None if no hit or the object doesn’t use a mesh collision shape.
    • 2: return value is a 5-tuple and the 5th element is a 2-tuple (u, v) with the UV mapping of the hit point or None if no hit, or the object doesn’t use a mesh collision shape, or doesn’t have a UV mapping.
  • mask (bitfield) – collision mask: The collision mask (16 layers mapped to a 16-bit integer) is combined with each object’s collision group, to hit only a subset of the objects in the scene. Only those objects for which collisionGroup & mask is true can be hit.
Returns:

(object, hitpoint, hitnormal) or (object, hitpoint, hitnormal, polygon) or (object, hitpoint, hitnormal, polygon, hituv).

  • object, hitpoint and hitnormal are None if no hit.
  • polygon is valid only if the object is valid and is a static object, a dynamic object using mesh collision shape or a soft body object, otherwise it is None
  • hituv is valid only if polygon is valid and the object has a UV mapping, otherwise it is None

Return type:

Note

The ray ignores the object on which the method is called. It is casted from/to object center or explicit [x, y, z] points.

setCollisionMargin(margin)

Set the objects collision margin.

Parameters:margin (float) – the collision margin distance in blender units.

Note

If this object has no physics controller (a physics ID of zero), this function will raise RuntimeError.

sendMessage(subject, body="", to="")

Sends a message.

Parameters:
  • subject (string) – The subject of the message
  • body (string) – The body of the message (optional)
  • to (string) – The name of the object to send the message to (optional)
reinstancePhysicsMesh(gameObject, meshObject)

Updates the physics system with the changed mesh.

If no arguments are given the physics mesh will be re-created from the first mesh assigned to the game object.

Parameters:
  • gameObject (string, KX_GameObject or None) – optional argument, set the physics shape from this gameObjets mesh.
  • meshObject (string, MeshProxy or None) – optional argument, set the physics shape from this mesh.
Returns:

True if reinstance succeeded, False if it failed.

Return type:

boolean

Note

If this object has instances the other instances will be updated too.

Note

The gameObject argument has an advantage that it can convert from a mesh with modifiers applied (such as the Subdivision Surface modifier).

Warning

Only triangle mesh type objects are supported currently (not convex hull)

Warning

If the object is a part of a compound object it will fail (parent or child)

Warning

Rebuilding the physics mesh can be slow, running many times per second will give a performance hit.

get(key, default=None)

Return the value matching key, or the default value if its not found. :return: The key value or a default.

playAction(name, start_frame, end_frame, layer=0, priority=0, blendin=0, play_mode=KX_ACTION_MODE_PLAY, layer_weight=0.0, ipo_flags=0, speed=1.0, blend_mode=KX_ACTION_BLEND_BLEND)

Plays an action.

Parameters:
  • name (string) – the name of the action
  • start (float) – the start frame of the action
  • end (float) – the end frame of the action
  • layer (integer) – the layer the action will play in (actions in different layers are added/blended together)
  • priority (integer) – only play this action if there isn’t an action currently playing in this layer with a higher (lower number) priority
  • blendin (float) – the amount of blending between this animation and the previous one on this layer
  • play_mode (one of these constants) – the play mode
  • layer_weight (float) – how much of the previous layer to use for blending
  • ipo_flags (int bitfield) – flags for the old IPO behaviors (force, etc)
  • speed (float) – the playback speed of the action as a factor (1.0 = normal speed, 2.0 = 2x speed, etc)
  • blend_mode (one of these constants) – how to blend this layer with previous layers
stopAction(layer=0)

Stop playing the action on the given layer.

Parameters:layer (integer) – The layer to stop playing.
getActionFrame(layer=0)

Gets the current frame of the action playing in the supplied layer.

Parameters:layer (integer) – The layer that you want to get the frame from.
Returns:The current frame of the action
Return type:float
getActionName(layer=0)

Gets the name of the current action playing in the supplied layer.

Parameters:layer (integer) – The layer that you want to get the action name from.
Returns:The name of the current action
Return type:string
setActionFrame(frame, layer=0)

Set the current frame of the action playing in the supplied layer.

Parameters:
  • layer (integer) – The layer where you want to set the frame
  • frame (float) – The frame to set the action to
isPlayingAction(layer=0)

Checks to see if there is an action playing in the given layer.

Parameters:layer (integer) – The layer to check for a playing action.
Returns:Whether or not the action is playing
Return type:boolean
addDebugProperty(name, debug = True)

Adds a single debug property to the debug list.

Parameters:
  • name (string) – name of the property that added to the debug list.
  • debug (boolean) – the debug state.