Game Types (bge.types)

Introduction

This module contains the classes that appear as instances in the Game Engine. A script must interact with these classes if it is to affect the behaviour of objects in a game.

The following example would move an object (i.e. an instance of KX_GameObject) one unit up.

# bge.types.SCA_PythonController
cont = bge.logic.getCurrentController()

# bge.types.KX_GameObject
obj = cont.owner
obj.worldPosition.z += 1

To run the code, it could be placed in a Blender text block and executed with a SCA_PythonController logic brick.

Types

class bge.types.PyObjectPlus

PyObjectPlus base class of most other types in the Game Engine.

invalid

Test if the object has been freed by the game engine and is no longer valid.

Normally this is not a problem but when storing game engine data in the GameLogic module, KX_Scenes or other KX_GameObjects its possible to hold a reference to invalid data. Calling an attribute or method on an invalid object will raise a SystemError.

The invalid attribute allows testing for this case without exception handling.

Type :boolean
class bge.types.CValue(PyObjectPlus)

This class is a basis for other classes.

name

The name of this CValue derived object (read-only).

Type :string
class bge.types.CPropValue(CValue)

This class has no python functions

class bge.types.SCA_ILogicBrick(CValue)

Base class for all logic bricks.

executePriority

This determines the order controllers are evaluated, and actuators are activated (lower priority is executed first).

Type :executePriority: int
owner

The game object this logic brick is attached to (read-only).

Type :KX_GameObject or None in exceptional cases.
name

The name of this logic brick (read-only).

Type :string
class bge.types.SCA_PythonKeyboard(PyObjectPlus)

The current keyboard.

events

A dictionary containing the status of each keyboard event or key. (read-only).

Type :dictionary {keycode:status, ...}
active_events

A dictionary containing the status of only the active keyboard events or keys. (read-only).

Type :dictionary {keycode:status, ...}
getClipboard()

Gets the clipboard text.

Return type:string
setClipboard(text)

Sets the clipboard text.

Parameters:text (string) – New clipboard text
class bge.types.SCA_PythonMouse(PyObjectPlus)

The current mouse.

events

a dictionary containing the status of each mouse event. (read-only).

Type :dictionary {keycode:status, ...}
active_events

a dictionary containing the status of only the active mouse events. (read-only).

Type :dictionary {keycode:status, ...}
position

The normalized x and y position of the mouse cursor.

Type :list [x, y]
visible

The visibility of the mouse cursor.

Type :boolean
class bge.types.SCA_PythonJoystick(PyObjectPlus)

A Python interface to a joystick.

name

The name assigned to the joystick by the operating system. (read-only)

Type :string
activeButtons

A list of active button values. (read-only)

Type :list
axisValues

The state of the joysticks axis as a list of values numAxis long. (read-only).

Type :list of ints.

Each specifying the value of an axis between -1.0 and 1.0 depending on how far the axis is pushed, 0 for nothing. The first 2 values are used by most joysticks and gamepads for directional control. 3rd and 4th values are only on some joysticks and can be used for arbitary controls.

  • left:[-1.0, 0.0, ...]
  • right:[1.0, 0.0, ...]
  • up:[0.0, -1.0, ...]
  • down:[0.0, 1.0, ...]
hatValues

The state of the joysticks hats as a list of values numHats long. (read-only).

Type :list of ints

Each specifying the direction of the hat from 1 to 12, 0 when inactive.

Hat directions are as follows...

  • 0:None
  • 1:Up
  • 2:Right
  • 4:Down
  • 8:Left
  • 3:Up - Right
  • 6:Down - Right
  • 12:Down - Left
  • 9:Up - Left
numAxis

The number of axes for the joystick at this index. (read-only).

Type :integer
numButtons

The number of buttons for the joystick at this index. (read-only).

Type :integer
numHats

The number of hats for the joystick at this index. (read-only).

Type :integer
class bge.types.SCA_IObject(CValue)

This class has no python functions

class bge.types.SCA_ISensor(SCA_ILogicBrick)

Base class for all sensor logic bricks.

usePosPulseMode

Flag to turn positive pulse mode on and off.

Type :boolean
useNegPulseMode

Flag to turn negative pulse mode on and off.

Type :boolean
frequency

The frequency for pulse mode sensors.

Type :integer
level

level Option whether to detect level or edge transition when entering a state. It makes a difference only in case of logic state transition (state actuator). A level detector will immediately generate a pulse, negative or positive depending on the sensor condition, as soon as the state is activated. A edge detector will wait for a state change before generating a pulse. note: mutually exclusive with tap, enabling will disable tap.

Type :boolean
tap

When enabled only sensors that are just activated will send a positive event, after this they will be detected as negative by the controllers. This will make a key thats held act as if its only tapped for an instant. note: mutually exclusive with level, enabling will disable level.

Type :boolean
invert

Flag to set if this sensor activates on positive or negative events.

Type :boolean
triggered

True if this sensor brick is in a positive state. (read-only).

Type :boolean
positive

True if this sensor brick is in a positive state. (read-only).

Type :boolean
pos_ticks

The number of ticks since the last positive pulse (read-only).

Type :int
neg_ticks

The number of ticks since the last negative pulse (read-only).

Type :int
status

The status of the sensor (read-only): can be one of these constants.

Type :int

Note

This convenient attribute combines the values of triggered and positive attributes.

reset()

Reset sensor internal state, effect depends on the type of sensor and settings.

The sensor is put in its initial state as if it was just activated.

class bge.types.SCA_IController(SCA_ILogicBrick)

Base class for all controller logic bricks.

state

The controllers state bitmask. This can be used with the GameObject’s state to test if the controller is active.

Type :int bitmask
sensors

A list of sensors linked to this controller.

Type :sequence supporting index/string lookups and iteration.

Note

The sensors are not necessarily owned by the same object.

Note

When objects are instanced in dupligroups links may be lost from objects outside the dupligroup.

actuators

A list of actuators linked to this controller.

Type :sequence supporting index/string lookups and iteration.

Note

The sensors are not necessarily owned by the same object.

Note

When objects are instanced in dupligroups links may be lost from objects outside the dupligroup.

useHighPriority

When set the controller executes always before all other controllers that dont have this set.

Type :boolen

Note

Order of execution between high priority controllers is not guaranteed.

class bge.types.SCA_IActuator(SCA_ILogicBrick)

Base class for all actuator logic bricks.

class bge.types.BL_ActionActuator(SCA_IActuator)

Action Actuators apply an action to an actor.

action

The name of the action to set as the current action.

Type :string
frameStart

Specifies the starting frame of the animation.

Type :float
frameEnd

Specifies the ending frame of the animation.

Type :float
blendIn

Specifies the number of frames of animation to generate when making transitions between actions.

Type :float
priority

Sets the priority of this actuator. Actuators will lower priority numbers will override actuators with higher numbers.

Type :integer
frame

Sets the current frame for the animation.

Type :float
propName

Sets the property to be used in FromProp playback mode.

Type :string
blendTime

Sets the internal frame timer. This property must be in the range from 0.0 to blendIn.

Type :float
mode

The operation mode of the actuator. Can be one of these constants.

Type :integer
useContinue

The actions continue option, True or False. When True, the action will always play from where last left off, otherwise negative events to this actuator will reset it to its start frame.

Type :boolean
framePropName

The name of the property that is set to the current frame number.

Type :string
class bge.types.BL_Shader(PyObjectPlus)

BL_Shader GLSL shaders.

TODO - Description

setUniformfv(name, fList)

Set a uniform with a list of float values

Parameters:
  • name (string) – the uniform name
  • fList (list[float]) – a list (2, 3 or 4 elements) of float values
delSource()

Clear the shader. Use this method before the source is changed with setSource.

getFragmentProg()

Returns the fragment program.

Returns:The fragment program.
Return type:string
getVertexProg()

Get the vertex program.

Returns:The vertex program.
Return type:string
isValid()

Check if the shader is valid.

Returns:True if the shader is valid
Return type:boolean
setAttrib(enum)

Set attribute location. (The parameter is ignored a.t.m. and the value of “tangent” is always used.)

Parameters:enum (integer) – attribute location value
setNumberOfPasses(max_pass)

Set the maximum number of passes. Not used a.t.m.

Parameters:max_pass (integer) – the maximum number of passes
setSampler(name, index)

Set uniform texture sample index.

Parameters:
  • name (string) – Uniform name
  • index (integer) – Texture sample index.
setSource(vertexProgram, fragmentProgram)

Set the vertex and fragment programs

Parameters:
  • vertexProgram (string) – Vertex program
  • fragmentProgram (string) – Fragment program
setUniform1f(name, fx)

Set a uniform with 1 float value.

Parameters:
  • name (string) – the uniform name
  • fx (float) – Uniform value
setUniform1i(name, ix)

Set a uniform with an integer value.

Parameters:
  • name (string) – the uniform name
  • ix (integer) – the uniform value
setUniform2f(name, fx, fy)

Set a uniform with 2 float values

Parameters:
  • name (string) – the uniform name
  • fx (float) – first float value
  • fy (float) – second float value
setUniform2i(name, ix, iy)

Set a uniform with 2 integer values

Parameters:
  • name (string) – the uniform name
  • ix (integer) – first integer value
  • iy (integer) – second integer value
setUniform3f(name, fx, fy, fz)

Set a uniform with 3 float values.

Parameters:
  • name (string) – the uniform name
  • fx (float) – first float value
  • fy (float) – second float value
  • fz (float) – third float value
setUniform3i(name, ix, iy, iz)

Set a uniform with 3 integer values

Parameters:
  • name (string) – the uniform name
  • ix (integer) – first integer value
  • iy (integer) – second integer value
  • iz (integer) – third integer value
setUniform4f(name, fx, fy, fz, fw)

Set a uniform with 4 float values.

Parameters:
  • name (string) – the uniform name
  • fx (float) – first float value
  • fy (float) – second float value
  • fz (float) – third float value
  • fw (float) – fourth float value
setUniform4i(name, ix, iy, iz, iw)

Set a uniform with 4 integer values

Parameters:
  • name (string) – the uniform name
  • ix (integer) – first integer value
  • iy (integer) – second integer value
  • iz (integer) – third integer value
  • iw (integer) – fourth integer value
setUniformDef(name, type)

Define a new uniform

Parameters:
  • name (string) – the uniform name
  • type (UNI_NONE, UNI_INT, UNI_FLOAT, UNI_INT2, UNI_FLOAT2, UNI_INT3, UNI_FLOAT3, UNI_INT4, UNI_FLOAT4, UNI_MAT3, UNI_MAT4, UNI_MAX) – uniform type
setUniformMatrix3(name, mat, transpose)

Set a uniform with a 3x3 matrix value

Parameters:
  • name (string) – the uniform name
  • mat (3x3 matrix) – A 3x3 matrix [[f, f, f], [f, f, f], [f, f, f]]
  • transpose (boolean) – set to True to transpose the matrix
setUniformMatrix4(name, mat, transpose)

Set a uniform with a 4x4 matrix value

Parameters:
  • name (string) – the uniform name
  • mat (4x4 matrix) – A 4x4 matrix [[f, f, f, f], [f, f, f, f], [f, f, f, f], [f, f, f, f]]
  • transpose (boolean) – set to True to transpose the matrix
setUniformiv(name, iList)

Set a uniform with a list of integer values

Parameters:
  • name (string) – the uniform name
  • iList (list[integer]) – a list (2, 3 or 4 elements) of integer values
validate()

Validate the shader object.

class bge.types.BL_ShapeActionActuator(SCA_IActuator)

ShapeAction Actuators apply an shape action to an mesh object.

action

The name of the action to set as the current shape action.

Type :string
frameStart

Specifies the starting frame of the shape animation.

Type :float
frameEnd

Specifies the ending frame of the shape animation.

Type :float
blendIn

Specifies the number of frames of animation to generate when making transitions between actions.

Type :float
priority

Sets the priority of this actuator. Actuators will lower priority numbers will override actuators with higher numbers.

Type :integer
frame

Sets the current frame for the animation.

Type :float
propName

Sets the property to be used in FromProp playback mode.

Type :string
blendTime

Sets the internal frame timer. This property must be in the range from 0.0 to blendin.

Type :float
mode

The operation mode of the actuator. Can be one of these constants.

Type :integer
framePropName

The name of the property that is set to the current frame number.

Type :string
class bge.types.KX_SteeringActuator(SCA_IActuator)

Steering Actuator for navigation.

behavior

The steering behavior to use.

Type :one of these constants
velocity

Velocity magnitude

Type :float
acceleration

Max acceleration

Type :float
turnspeed

Max turn speed

Type :float
distance

Relax distance

Type :float
target

Target object

Type :KX_GameObject
navmesh

Navigation mesh

Type :KX_GameObject
selfterminated

Terminate when target is reached

Type :boolean
enableVisualization

Enable debug visualization

Type :boolean
pathUpdatePeriod

Path update period

Type :int
class bge.types.CListValue(CPropValue)

This is a list like object used in the game engine internally that behaves similar to a python list in most ways.

As well as the normal index lookup (val= clist[i]), CListValue supports string lookups (val= scene.objects["Cube"])

Other operations such as len(clist), list(clist), clist[0:10] are also supported.

append(val)

Add an item to the list (like pythons append)

Warning

Appending values to the list can cause crashes when the list is used internally by the game engine.

count(val)

Count the number of instances of a value in the list.

Returns:number of instances
Return type:integer
index(val)

Return the index of a value in the list.

Returns:The index of the value in the list.
Return type:integer
reverse()

Reverse the order of the list.

get(key, default=None)

Return the value matching key, or the default value if its not found.

Returns:The key value or a default.
from_id(id)

This is a funtion especially for the game engine to return a value with a spesific id.

Since object names are not always unique, the id of an object can be used to get an object from the CValueList.

Example:

myObID=id(gameObject)
ob= scene.objects.from_id(myObID)

Where myObID is an int or long from the id function.

This has the advantage that you can store the id in places you could not store a gameObject.

Warning

The id is derived from a memory location and will be different each time the game engine starts.

Warning

The id can’t be stored as an integer in game object properties, as those only have a limited range that the id may not be contained in. Instead an id can be stored as a string game property and converted back to an integer for use in from_id lookups.

class bge.types.KX_BlenderMaterial(PyObjectPlus)

KX_BlenderMaterial

shader

The materials shader.

Type :BL_Shader
blending

Ints used for pixel blending, (src, dst), matching the setBlending method.

Type :(integer, integer)
material_index

The material’s index.

Type :integer
getShader()

Returns the material’s shader.

Returns:the material’s shader
Return type:BL_Shader
setBlending(src, dest)

Set the pixel color arithmetic functions.

Parameters:
  • src – Specifies how the red, green, blue, and alpha source blending factors are computed.
  • dest – Specifies how the red, green, blue, and alpha destination blending factors are computed.
getMaterialIndex()

Returns the material’s index.

Returns:the material’s index
Return type:integer
class bge.types.KX_CameraActuator(SCA_IActuator)

Applies changes to a camera.

damping

strength of of the camera following movement.

Type :float
axis

The camera axis (0, 1, 2) for positive XYZ, (3, 4, 5) for negative XYZ.

Type :int
min

minimum distance to the target object maintained by the actuator.

Type :float
max

maximum distance to stay from the target object.

Type :float
height

height to stay above the target object.

Type :float
object

the object this actuator tracks.

Type :KX_GameObject or None
class bge.types.KX_ConstraintActuator(SCA_IActuator)

A constraint actuator limits the position, rotation, distance or orientation of an object.

damp

Time constant of the constraint expressed in frame (not use by Force field constraint).

Type :integer
rotDamp

Time constant for the rotation expressed in frame (only for the distance constraint), 0 = use damp for rotation as well.

Type :integer
direction

The reference direction in world coordinate for the orientation constraint.

Type :3-tuple of float: (x, y, z)
option

Binary combination of these constants

Type :integer
time

activation time of the actuator. The actuator disables itself after this many frame. If set to 0, the actuator is not limited in time.

Type :integer
propName

the name of the property or material for the ray detection of the distance constraint.

Type :string
min

The lower bound of the constraint. For the rotation and orientation constraint, it represents radiant.

Type :float
distance

the target distance of the distance constraint.

Type :float
max

the upper bound of the constraint. For rotation and orientation constraints, it represents radiant.

Type :float
rayLength

the length of the ray of the distance constraint.

Type :float
limit

type of constraint. Use one of the these constants

Type :integer.
class bge.types.KX_ConstraintWrapper(PyObjectPlus)

KX_ConstraintWrapper

getConstraintId(val)

Returns the contraint’s ID

Returns:the constraint’s ID
Return type:integer
class bge.types.KX_GameActuator(SCA_IActuator)

The game actuator loads a new .blend file, restarts the current .blend file or quits the game.

fileName

the new .blend file to load.

Type :string
mode

The mode of this actuator. Can be on of these constants

Type :Int
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.

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 then setting it stationary).

localInertia

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

Type :list [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, otherwise None is returned.

Type :CListValue of KX_GameObject or None
groupObject

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

Type :KX_GameObject or None
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.

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 experemental 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 experemental 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 childrens 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
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 objects 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 centre 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:list [vx, vy, vz]
setLinearVelocity(velocity, local=False)

Sets the game object’s linear velocity.

This method sets game object’s velocity through it’s centre 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:list [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:list [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:list [fx, fy, fz]

Note

This is not implimented at the moment.

applyImpulse(point, impulse)

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 (the point to apply the impulse to (in world coordinates)) – the point to apply the impulse to (in world coordinates)
suspendDynamics()

Suspends physics for this object.

restoreDynamics()

Resumes physics for this object.

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)

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 paremeter 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.
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:

  • 3-tuple (KX_GameObject, 3-tuple (x, y, z), 3-tuple (nx, ny, nz))
  • or 4-tuple (KX_GameObject, 3-tuple (x, y, z), 3-tuple (nx, ny, nz), PolyProxy)
  • or 5-tuple (KX_GameObject, 3-tuple (x, y, z), 3-tuple (nx, ny, nz), PolyProxy, 2-tuple (u, v))

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 subsurf).

Warning

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

Warning

If the object is a part of a combound 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=ACT_MODE_PLAY, layer_weight=0.0, ipo_flags=0, speed=1.0)

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 (0 = add)
  • 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)
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
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
class bge.types.KX_IpoActuator(SCA_IActuator)

IPO actuator activates an animation.

frameStart

Start frame.

Type :float
frameEnd

End frame.

Type :float
propName

Use this property to define the Ipo position.

Type :string
framePropName

Assign this property this action current frame number.

Type :string
mode

Play mode for the ipo. Can be on of these constants

Type :integer
useIpoAsForce

Apply Ipo as a global or local force depending on the local option (dynamic objects only).

Type :boolean
useIpoAdd

Ipo is added to the current loc/rot/scale in global or local coordinate according to Local flag.

Type :boolean
useIpoLocal

Let the ipo acts in local coordinates, used in Force and Add mode.

Type :boolean
useChildren

Update IPO on all children Objects as well.

Type :boolean
class bge.types.KX_LibLoadStatus(PyObjectPlus)

An object providing information about a LibLoad() operation.

# Print a message when an async LibLoad is done
import bge

def finished_cb(status):
    print("Library (%s) loaded in %.2fms." % (status.libraryName, status.timeTaken))

bge.logic.LibLoad('myblend.blend', 'Scene', async=True).onFinish = finished_cb
onFinish

A callback that gets called when the lib load is done.

Type :callable
progress

The current progress of the lib load as a normalized value from 0.0 to 1.0.

Type :float
libraryName

The name of the library being loaded (the first argument to LibLoad).

Type :string
timeTaken

The amount of time, in seconds, the lib load took (0 until the operation is complete).

Type :float
class bge.types.KX_LightObject(KX_GameObject)

A Light object.

# Turn on a red alert light.
import bge

co = bge.logic.getCurrentController()
light = co.owner

light.energy = 1.0
light.color = [1.0, 0.0, 0.0]
SPOT

A spot light source. See attribute type

SUN

A point light source with no attenuation. See attribute type

NORMAL

A point light source. See attribute type

type

The type of light - must be SPOT, SUN or NORMAL

layer

The layer mask that this light affects object on.

Type :bitfield
energy

The brightness of this light.

Type :float
distance

The maximum distance this light can illuminate. (SPOT and NORMAL lights only).

Type :float
color

The color of this light. Black = [0.0, 0.0, 0.0], White = [1.0, 1.0, 1.0].

Type :list [r, g, b]
lin_attenuation

The linear component of this light’s attenuation. (SPOT and NORMAL lights only).

Type :float
quad_attenuation

The quadratic component of this light’s attenuation (SPOT and NORMAL lights only).

Type :float
spotsize

The cone angle of the spot light, in degrees (SPOT lights only).

Type :float in [0 - 180].
spotblend

Specifies the intensity distribution of the spot light (SPOT lights only).

Type :float in [0 - 1]

Note

Higher values result in a more focused light source.

class bge.types.KX_MeshProxy(SCA_IObject)

A mesh object.

You can only change the vertex properties of a mesh object, not the mesh topology.

To use mesh objects effectively, you should know a bit about how the game engine handles them.

  1. Mesh Objects are converted from Blender at scene load.
  2. The Converter groups polygons by Material. This means they can be sent to the renderer efficiently. A material holds:
    1. The texture.
    2. The Blender material.
    3. The Tile properties
    4. The face properties - (From the “Texture Face” panel)
    5. Transparency & z sorting
    6. Light layer
    7. Polygon shape (triangle/quad)
    8. Game Object
  3. Vertices will be split by face if necessary. Vertices can only be shared between faces if:
    1. They are at the same position
    2. UV coordinates are the same
    3. Their normals are the same (both polygons are “Set Smooth”)
    4. They are the same color, for example: a cube has 24 vertices: 6 faces with 4 vertices per face.

The correct method of iterating over every KX_VertexProxy in a game object

from bge import logic

cont = logic.getCurrentController()
object = cont.owner

for mesh in object.meshes:
   for m_index in range(len(mesh.materials)):
      for v_index in range(mesh.getVertexArrayLength(m_index)):
         vertex = mesh.getVertex(m_index, v_index)
         # Do something with vertex here...
         # ... eg: color the vertex red.
         vertex.color = [1.0, 0.0, 0.0, 1.0]
materials
Type :list of KX_BlenderMaterial or KX_PolygonMaterial types
numPolygons
Type :integer
numMaterials
Type :integer
getMaterialName(matid)

Gets the name of the specified material.

Parameters:matid (integer) – the specified material.
Returns:the attached material name.
Return type:string
getTextureName(matid)

Gets the name of the specified material’s texture.

Parameters:matid (integer) – the specified material
Returns:the attached material’s texture name.
Return type:string
getVertexArrayLength(matid)

Gets the length of the vertex array associated with the specified material.

There is one vertex array for each material.

Parameters:matid (integer) – the specified material
Returns:the number of verticies in the vertex array.
Return type:integer
getVertex(matid, index)

Gets the specified vertex from the mesh object.

Parameters:
  • matid (integer) – the specified material
  • index (integer) – the index into the vertex array.
Returns:

a vertex object.

Return type:

KX_VertexProxy

getPolygon(index)

Gets the specified polygon from the mesh.

Parameters:index (integer) – polygon number
Returns:a polygon object.
Return type:PolyProxy
transform(matid, matrix)

Transforms the vertices of a mesh.

Parameters:
  • matid (integer) – material index, -1 transforms all.
  • matrix (4x4 matrix [[float]]) – transformation matrix.
transformUV(matid, matrix, uv_index=-1, uv_index_from=-1)

Transforms the vertices UV’s of a mesh.

Parameters:
  • matid (integer) – material index, -1 transforms all.
  • matrix (4x4 matrix [[float]]) – transformation matrix.
  • uv_index (integer) – optional uv index, -1 for all, otherwise 0 or 1.
  • uv_index_from (integer) – optional uv index to copy from, -1 to transform the current uv.
class bge.types.SCA_MouseSensor(SCA_ISensor)

Mouse Sensor logic brick.

position

current [x, y] coordinates of the mouse, in frame coordinates (pixels).

Type :[integer, interger]
mode

sensor mode.

Type :

integer

  • KX_MOUSESENSORMODE_LEFTBUTTON(1)
  • KX_MOUSESENSORMODE_MIDDLEBUTTON(2)
  • KX_MOUSESENSORMODE_RIGHTBUTTON(3)
  • KX_MOUSESENSORMODE_WHEELUP(4)
  • KX_MOUSESENSORMODE_WHEELDOWN(5)
  • KX_MOUSESENSORMODE_MOVEMENT(6)
getButtonStatus(button)

Get the mouse button status.

Parameters:button (int) – The code that represents the key you want to get the state of, use one of these constants
Returns:The state of the given key, can be one of these constants
Return type:int
class bge.types.KX_MouseFocusSensor(SCA_MouseSensor)

The mouse focus sensor detects when the mouse is over the current game object.

The mouse focus sensor works by transforming the mouse coordinates from 2d device space to 3d space then raycasting away from the camera.

raySource

The worldspace source of the ray (the view position).

Type :list (vector of 3 floats)
rayTarget

The worldspace target of the ray.

Type :list (vector of 3 floats)
rayDirection

The rayTarget - raySource normalized.

Type :list (normalized vector of 3 floats)
hitObject

the last object the mouse was over.

Type :KX_GameObject or None
hitPosition

The worldspace position of the ray intersecton.

Type :list (vector of 3 floats)
hitNormal

the worldspace normal from the face at point of intersection.

Type :list (normalized vector of 3 floats)
hitUV

the UV coordinates at the point of intersection.

Type :list (vector of 2 floats)

If the object has no UV mapping, it returns [0, 0].

The UV coordinates are not normalized, they can be < 0 or > 1 depending on the UV mapping.

usePulseFocus

When enabled, moving the mouse over a different object generates a pulse. (only used when the ‘Mouse Over Any’ sensor option is set).

Type :boolean
class bge.types.KX_TouchSensor(SCA_ISensor)

Touch sensor detects collisions between objects.

propName

The property or material to collide with.

Type :string
useMaterial

Determines if the sensor is looking for a property or material. KX_True = Find material; KX_False = Find property.

Type :boolean
usePulseCollision

When enabled, changes to the set of colliding objects generate a pulse.

Type :boolean
hitObject

The last collided object. (read-only).

Type :KX_GameObject or None
hitObjectList

A list of colliding objects. (read-only).

Type :CListValue of KX_GameObject
class bge.types.KX_NearSensor(KX_TouchSensor)

A near sensor is a specialised form of touch sensor.

distance

The near sensor activates when an object is within this distance.

Type :float
resetDistance

The near sensor deactivates when the object exceeds this distance.

Type :float
class bge.types.KX_NetworkMessageActuator(SCA_IActuator)

Message Actuator

propName

Messages will only be sent to objects with the given property name.

Type :string
subject

The subject field of the message.

Type :string
body

The body of the message.

Type :string
usePropBody

Send a property instead of a regular body message.

Type :boolean
class bge.types.KX_NetworkMessageSensor(SCA_ISensor)

The Message Sensor logic brick.

Currently only loopback (local) networks are supported.

subject

The subject the sensor is looking for.

Type :string
frameMessageCount

The number of messages received since the last frame. (read-only).

Type :integer
subjects

The list of message subjects received. (read-only).

Type :list of strings
bodies

The list of message bodies received. (read-only).

Type :list of strings
class bge.types.KX_FontObject(KX_GameObject)

TODO.

class bge.types.KX_NavMeshObject(KX_GameObject)

Python interface for using and controlling navigation meshes.

findPath(start, goal)

Finds the path from start to goal points.

Parameters:
  • start – the start point
  • start – 3D Vector
  • goal – the goal point
  • start – 3D Vector
Returns:

a path as a list of points

Return type:

list of points

raycast(start, goal)

Raycast from start to goal points.

Parameters:
  • start – the start point
  • start – 3D Vector
  • goal – the goal point
  • start – 3D Vector
Returns:

the hit factor

Return type:

float

draw(mode)

Draws a debug mesh for the navigation mesh.

Parameters:
Returns:

None

rebuild()

Rebuild the navigation mesh.

Returns:None
class bge.types.KX_ObjectActuator(SCA_IActuator)

The object actuator (“Motion Actuator”) applies force, torque, displacement, angular displacement, velocity, or angular velocity to an object. Servo control allows to regulate force to achieve a certain speed target.

force

The force applied by the actuator.

Type :list [x, y, z]
useLocalForce

A flag specifying if the force is local.

Type :boolean
torque

The torque applied by the actuator.

Type :list [x, y, z]
useLocalTorque

A flag specifying if the torque is local.

Type :boolean
dLoc

The displacement vector applied by the actuator.

Type :list [x, y, z]
useLocalDLoc

A flag specifying if the dLoc is local.

Type :boolean
dRot

The angular displacement vector applied by the actuator

Type :list [x, y, z]

Note

Since the displacement is applied every frame, you must adjust the displacement based on the frame rate, or you game experience will depend on the player’s computer speed.

useLocalDRot

A flag specifying if the dRot is local.

Type :boolean
linV

The linear velocity applied by the actuator.

Type :list [x, y, z]
useLocalLinV

A flag specifying if the linear velocity is local.

Type :boolean

Note

This is the target speed for servo controllers.

angV

The angular velocity applied by the actuator.

Type :list [x, y, z]
useLocalAngV

A flag specifying if the angular velocity is local.

Type :boolean
damping

The damping parameter of the servo controller.

Type :short
forceLimitX

The min/max force limit along the X axis and activates or deactivates the limits in the servo controller.

Type :list [min(float), max(float), bool]
forceLimitY

The min/max force limit along the Y axis and activates or deactivates the limits in the servo controller.

Type :list [min(float), max(float), bool]
forceLimitZ

The min/max force limit along the Z axis and activates or deactivates the limits in the servo controller.

Type :list [min(float), max(float), bool]
pid

The PID coefficients of the servo controller.

Type :list of floats [proportional, integral, derivate]
reference

The object that is used as reference to compute the velocity for the servo controller.

Type :KX_GameObject or None
class bge.types.KX_ParentActuator(SCA_IActuator)

The parent actuator can set or remove an objects parent object.

object

the object this actuator sets the parent too.

Type :KX_GameObject or None
mode

The mode of this actuator.

Type :integer from 0 to 1.
compound

Whether the object shape should be added to the parent compound shape when parenting.

Effective only if the parent is already a compound shape.

Type :boolean
ghost

Whether the object should be made ghost when parenting Effective only if the shape is not added to the parent compound shape.

Type :boolean
class bge.types.KX_PolyProxy(SCA_IObject)

A polygon holds the index of the vertex forming the poylgon.

Note: The polygon attributes are read-only, you need to retrieve the vertex proxy if you want to change the vertex settings.

material_name

The name of polygon material, empty if no material.

Type :string
material

The material of the polygon.

Type :KX_PolygonMaterial or KX_BlenderMaterial
texture_name

The texture name of the polygon.

Type :string
material_id

The material index of the polygon, use this to retrieve vertex proxy from mesh proxy.

Type :integer
v1

vertex index of the first vertex of the polygon, use this to retrieve vertex proxy from mesh proxy.

Type :integer
v2

vertex index of the second vertex of the polygon, use this to retrieve vertex proxy from mesh proxy.

Type :integer
v3

vertex index of the third vertex of the polygon, use this to retrieve vertex proxy from mesh proxy.

Type :integer
v4

Vertex index of the fourth vertex of the polygon, 0 if polygon has only 3 vertex Use this to retrieve vertex proxy from mesh proxy.

Type :integer
visible

visible state of the polygon: 1=visible, 0=invisible.

Type :integer
collide

collide state of the polygon: 1=receives collision, 0=collision free.

Type :integer
getMaterialName()

Returns the polygon material name with MA prefix

Returns:material name
Return type:string
getMaterial()
Returns:The polygon material
Return type:KX_PolygonMaterial or KX_BlenderMaterial
getTextureName()
Returns:The texture name
Return type:string
getMaterialIndex()

Returns the material bucket index of the polygon. This index and the ones returned by getVertexIndex() are needed to retrieve the vertex proxy from MeshProxy.

Returns:the material index in the mesh
Return type:integer
getNumVertex()

Returns the number of vertex of the polygon.

Returns:number of vertex, 3 or 4.
Return type:integer
isVisible()

Returns whether the polygon is visible or not

Returns:0=invisible, 1=visible
Return type:boolean
isCollider()

Returns whether the polygon is receives collision or not

Returns:0=collision free, 1=receives collision
Return type:integer
getVertexIndex(vertex)

Returns the mesh vertex index of a polygon vertex This index and the one returned by getMaterialIndex() are needed to retrieve the vertex proxy from MeshProxy.

Parameters:
  • vertex – index of the vertex in the polygon: 0->3
  • vertex – integer
Returns:

mesh vertex index

Return type:

integer

getMesh()

Returns a mesh proxy

Returns:mesh proxy
Return type:MeshProxy
class bge.types.KX_PolygonMaterial(PyObjectPlus)

This is the interface to materials in the game engine.

Materials define the render state to be applied to mesh objects.

Warning

Some of the methods/variables are CObjects. If you mix these up, you will crash blender.

from bge import logic

vertex_shader = """

void main(void)
{
   // original vertex position, no changes
   gl_Position = ftransform();
   // coordinate of the 1st texture channel
   gl_TexCoord[0] = gl_MultiTexCoord0;
   // coordinate of the 2nd texture channel
   gl_TexCoord[1] = gl_MultiTexCoord1;
}
"""

fragment_shader ="""

uniform sampler2D color_0;
uniform sampler2D color_1;
uniform float factor;

void main(void)
{
   vec4 color_0 = texture2D(color_0, gl_TexCoord[0].st);
   vec4 color_1 = texture2D(color_1, gl_TexCoord[1].st);
   gl_FragColor = mix(color_0, color_1, factor);
}
"""

object = logic.getCurrentController().owner
object = cont.owner
for mesh in object.meshes:
    for material in mesh.materials:
        shader = material.getShader()
        if shader != None:
            if not shader.isValid():
                shader.setSource(vertex_shader, fragment_shader, True)

            # get the first texture channel of the material
            shader.setSampler('color_0', 0)
            # get the second texture channel of the material
            shader.setSampler('color_1', 1)
            # pass another uniform to the shader
            shader.setUniform1f('factor', 0.3)
texture

Texture name.

Type :string (read-only)
gl_texture

OpenGL texture handle (eg for glBindTexture(GL_TEXTURE_2D, gl_texture).

Type :integer (read-only)
material

Material name.

Type :string (read-only)
tface

Texture face properties.

Type :CObject (read-only)
tile

Texture is tiling.

Type :boolean
tilexrep

Number of tile repetitions in x direction.

Type :integer
tileyrep

Number of tile repetitions in y direction.

Type :integer
drawingmode

Drawing mode for the material. - 2 (drawingmode & 4) Textured - 4 (drawingmode & 16) Light - 14 (drawingmode & 16384) 3d Polygon Text.

Type :bitfield
transparent

This material is transparent. All meshes with this material will be rendered after non transparent meshes from back to front.

Type :boolean
zsort

Transparent polygons in meshes with this material will be sorted back to front before rendering. Non-Transparent polygons will be sorted front to back before rendering.

Type :boolean
diffuse

The diffuse color of the material. black = [0.0, 0.0, 0.0] white = [1.0, 1.0, 1.0].

Type :list [r, g, b]
specular

The specular color of the material. black = [0.0, 0.0, 0.0] white = [1.0, 1.0, 1.0].

Type :list [r, g, b]
shininess

The shininess (specular exponent) of the material. 0.0 <= shininess <= 128.0.

Type :float
specularity

The amount of specular of the material. 0.0 <= specularity <= 1.0.

Type :float
updateTexture(tface, rasty)

Updates a realtime animation.

Parameters:
  • tface (CObject) – Texture face (eg mat.tface)
  • rasty (CObject) – Rasterizer
setTexture(tface)

Sets texture render state.

Parameters:tface (CObject) – Texture face
mat.setTexture(mat.tface)
activate(rasty, cachingInfo)

Sets material parameters for this object for rendering.

Material Parameters set:

  1. Texture
  2. Backface culling
  3. Line drawing
  4. Specular Colour
  5. Shininess
  6. Diffuse Colour
  7. Polygon Offset.
Parameters:
  • rasty (CObject) – Rasterizer instance.
  • cachingInfo (CObject) – Material cache instance.
setCustomMaterial(material)

Sets the material state setup object.

Using this method, you can extend or completely replace the gameengine material to do your own advanced multipass effects.

Use this method to register your material class. Instead of the normal material, your class’s activate method will be called just before rendering the mesh. This should setup the texture, material, and any other state you would like. It should return True to render the mesh, or False if you are finished. You should clean up any state Blender does not set before returning False.

Activate Method Definition:

def activate(self, rasty, cachingInfo, material):
Parameters:material (instance) – The material object.
class PyMaterial:
  def __init__(self):
    self.pass_no = -1

  def activate(self, rasty, cachingInfo, material):
    # Activate the material here.
    #
    # The activate method will be called until it returns False.
    # Every time the activate method returns True the mesh will
    # be rendered.
    #
    # rasty is a CObject for passing to material.updateTexture()
    #       and material.activate()
    # cachingInfo is a CObject for passing to material.activate()
    # material is the KX_PolygonMaterial instance this material
    #          was added to

    # default material properties:
    self.pass_no += 1
    if self.pass_no == 0:
      material.activate(rasty, cachingInfo)
      # Return True to do this pass
      return True

    # clean up and return False to finish.
    self.pass_no = -1
    return False

# Create a new Python Material and pass it to the renderer.
mat.setCustomMaterial(PyMaterial())
class bge.types.KX_RadarSensor(KX_NearSensor)

Radar sensor is a near sensor with a conical sensor object.

coneOrigin

The origin of the cone with which to test. The origin is in the middle of the cone. (read-only).

Type :list of floats [x, y, z]
coneTarget

The center of the bottom face of the cone with which to test. (read-only).

Type :list of floats [x, y, z]
distance

The height of the cone with which to test.

Type :float
angle

The angle of the cone (in degrees) with which to test.

Type :float
axis

The axis on which the radar cone is cast.

Type :integer from 0 to 5

KX_RADAR_AXIS_POS_X, KX_RADAR_AXIS_POS_Y, KX_RADAR_AXIS_POS_Z, KX_RADAR_AXIS_NEG_X, KX_RADAR_AXIS_NEG_Y, KX_RADAR_AXIS_NEG_Z

class bge.types.KX_RaySensor(SCA_ISensor)

A ray sensor detects the first object in a given direction.

propName

The property the ray is looking for.

Type :string
range

The distance of the ray.

Type :float
useMaterial

Whether or not to look for a material (false = property).

Type :boolean
useXRay

Whether or not to use XRay.

Type :boolean
hitObject

The game object that was hit by the ray. (read-only).

Type :KX_GameObject
hitPosition

The position (in worldcoordinates) where the object was hit by the ray. (read-only).

Type :list [x, y, z]
hitNormal

The normal (in worldcoordinates) of the object at the location where the object was hit by the ray. (read-only).

Type :list [x, y, z]
rayDirection

The direction from the ray (in worldcoordinates). (read-only).

Type :list [x, y, z]
axis

The axis the ray is pointing on.

Type :integer from 0 to 5
  • KX_RAY_AXIS_POS_X
  • KX_RAY_AXIS_POS_Y
  • KX_RAY_AXIS_POS_Z
  • KX_RAY_AXIS_NEG_X
  • KX_RAY_AXIS_NEG_Y
  • KX_RAY_AXIS_NEG_Z
class bge.types.KX_SCA_AddObjectActuator(SCA_IActuator)

Edit Object Actuator (in Add Object Mode)

Warning

An Add Object actuator will be ignored if at game start, the linked object doesn’t exist (or is empty) or the linked object is in an active layer.

Error: GameObject 'Name' has a AddObjectActuator 'ActuatorName' without object (in 'nonactive' layer)
object

the object this actuator adds.

Type :KX_GameObject or None
objectLastCreated

the last added object from this actuator (read-only).

Type :KX_GameObject or None
time

the lifetime of added objects, in frames. Set to 0 to disable automatic deletion.

Type :integer
linearVelocity

the initial linear velocity of added objects.

Type :list [vx, vy, vz]
angularVelocity

the initial angular velocity of added objects.

Type :list [vx, vy, vz]
instantAddObject()

adds the object without needing to calling SCA_PythonController.activate()

Note

Use objectLastCreated to get the newly created object.

class bge.types.KX_SCA_DynamicActuator(SCA_IActuator)

Dynamic Actuator.

mode
Type :integer

the type of operation of the actuator, 0-4

  • KX_DYN_RESTORE_DYNAMICS(0)
  • KX_DYN_DISABLE_DYNAMICS(1)
  • KX_DYN_ENABLE_RIGID_BODY(2)
  • KX_DYN_DISABLE_RIGID_BODY(3)
  • KX_DYN_SET_MASS(4)
mass

the mass value for the KX_DYN_SET_MASS operation.

Type :float
class bge.types.KX_SCA_EndObjectActuator(SCA_IActuator)

Edit Object Actuator (in End Object mode)

This actuator has no python methods.

class bge.types.KX_SCA_ReplaceMeshActuator(SCA_IActuator)

Edit Object actuator, in Replace Mesh mode.

Warning

Replace mesh actuators will be ignored if at game start, the named mesh doesn’t exist.

This will generate a warning in the console

Error: GameObject 'Name' ReplaceMeshActuator 'ActuatorName' without object
# Level-of-detail
# Switch a game object's mesh based on its depth in the camera view.
# +----------+     +-----------+     +-------------------------------------+
# | Always   +-----+ Python    +-----+ Edit Object (Replace Mesh) LOD.Mesh |
# +----------+     +-----------+     +-------------------------------------+
from bge import logic

# List detail meshes here
# Mesh (name, near, far)
# Meshes overlap so that they don't 'pop' when on the edge of the distance.
meshes = ((".Hi", 0.0, -20.0),
      (".Med", -15.0, -50.0),
      (".Lo", -40.0, -100.0)
    )

cont = logic.getCurrentController()
object = cont.owner
actuator = cont.actuators["LOD." + obj.name]
camera = logic.getCurrentScene().active_camera

def Depth(pos, plane):
  return pos[0]*plane[0] + pos[1]*plane[1] + pos[2]*plane[2] + plane[3]

# Depth is negative and decreasing further from the camera
depth = Depth(object.position, camera.world_to_camera[2])

newmesh = None
curmesh = None
# Find the lowest detail mesh for depth
for mesh in meshes:
  if depth < mesh[1] and depth > mesh[2]:
    newmesh = mesh
  if "ME" + object.name + mesh[0] == actuator.getMesh():
      curmesh = mesh

if newmesh != None and "ME" + object.name + newmesh[0] != actuator.mesh:
  # The mesh is a different mesh - switch it.
  # Check the current mesh is not a better fit.
  if curmesh == None or curmesh[1] < depth or curmesh[2] > depth:
    actuator.mesh = object.name + newmesh[0]
    cont.activate(actuator)
mesh

MeshProxy or the name of the mesh that will replace the current one.

Set to None to disable actuator.

Type :MeshProxy or None if no mesh is set
useDisplayMesh

when true the displayed mesh is replaced.

Type :boolean
usePhysicsMesh

when true the physics mesh is replaced.

Type :boolean
instantReplaceMesh()

Immediately replace mesh without delay.

class bge.types.KX_Scene(PyObjectPlus)

An active scene that gives access to objects, cameras, lights and scene attributes.

The activity culling stuff is supposed to disable logic bricks when their owner gets too far from the active camera. It was taken from some code lurking at the back of KX_Scene - who knows what it does!

from bge import logic

# get the scene
scene = logic.getCurrentScene()

# print all the objects in the scene
for object in scene.objects:
   print(object.name)

# get an object named 'Cube'
object = scene.objects["Cube"]

# get the first object in the scene.
object = scene.objects[0]
# Get the depth of an object in the camera view.
from bge import logic

object = logic.getCurrentController().owner
cam = logic.getCurrentScene().active_camera

# Depth is negative and decreasing further from the camera
depth = object.position[0]*cam.world_to_camera[2][0] + object.position[1]*cam.world_to_camera[2][1] + object.position[2]*cam.world_to_camera[2][2] + cam.world_to_camera[2][3]

@bug: All attributes are read only at the moment.

name

The scene’s name, (read-only).

Type :string
objects

A list of objects in the scene, (read-only).

Type :CListValue of KX_GameObject
objectsInactive

A list of objects on background layers (used for the addObject actuator), (read-only).

Type :CListValue of KX_GameObject
lights

A list of lights in the scene, (read-only).

Type :CListValue of KX_LightObject
cameras

A list of cameras in the scene, (read-only).

Type :CListValue of KX_Camera
active_camera

The current active camera.

Type :KX_Camera

Note

This can be set directly from python to avoid using the KX_SceneActuator.

suspended

True if the scene is suspended, (read-only).

Type :boolean
activity_culling

True if the scene is activity culling.

Type :boolean
activity_culling_radius

The distance outside which to do activity culling. Measured in manhattan distance.

Type :float
dbvt_culling

True when Dynamic Bounding box Volume Tree is set (read-only).

Type :boolean
pre_draw

A list of callables to be run before the render step.

Type :list
post_draw

A list of callables to be run after the render step.

Type :list
gravity

The scene gravity using the world x, y and z axis.

Type :list [fx, fy, fz]
addObject(object, other, time=0)

Adds an object to the scene like the Add Object Actuator would.

Parameters:
  • object (KX_GameObject or string) – The object to add
  • other (KX_GameObject or string) – The object’s center to use when adding the object
  • time (integer) – The lifetime of the added object, in frames. A time of 0 means the object will last forever.
Returns:

The newly added object.

Return type:

KX_GameObject

end()

Removes the scene from the game.

restart()

Restarts the scene.

replace(scene)

Replaces this scene with another one.

Parameters:scene (string) – The name of the scene to replace this scene with.
suspend()

Suspends this scene.

resume()

Resume this scene.

get(key, default=None)

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

drawObstacleSimulation()

Draw debug visualization of obstacle simulation.

class bge.types.KX_SceneActuator(SCA_IActuator)

Scene Actuator logic brick.

Warning

Scene actuators that use a scene name will be ignored if at game start, the named scene doesn’t exist or is empty

This will generate a warning in the console:

Error: GameObject 'Name' has a SceneActuator 'ActuatorName' (SetScene) without scene
scene

the name of the scene to change to/overlay/underlay/remove/suspend/resume.

Type :string
camera

the camera to change to.

Type :KX_Camera on read, string or KX_Camera on write

Note

When setting the attribute, you can use either a KX_Camera or the name of the camera.

useRestart

Set flag to True to restart the sene.

Type :boolean
mode

The mode of the actuator.

Type :integer from 0 to 5.
class bge.types.KX_SoundActuator(SCA_IActuator)

Sound Actuator.

The startSound, pauseSound and stopSound do not require the actuator to be activated - they act instantly provided that the actuator has been activated once at least.

volume

The volume (gain) of the sound.

Type :float
time

The current position in the audio stream (in seconds).

Type :float
pitch

The pitch of the sound.

Type :float
mode

The operation mode of the actuator. Can be one of these constants

Type :integer
sound

The sound the actuator should play.

Type :Audaspace factory
is3D

Whether or not the actuator should be using 3D sound. (read-only)

Type :boolean
volume_maximum

The maximum gain of the sound, no matter how near it is.

Type :float
volume_minimum

The minimum gain of the sound, no matter how far it is away.

Type :float
distance_reference

The distance where the sound has a gain of 1.0.

Type :float
distance_maximum

The maximum distance at which you can hear the sound.

Type :float
attenuation

The influence factor on volume depending on distance.

Type :float
cone_angle_inner

The angle of the inner cone.

Type :float
cone_angle_outer

The angle of the outer cone.

Type :float
cone_volume_outer

The gain outside the outer cone (the gain in the outer cone will be interpolated between this value and the normal gain in the inner cone).

Type :float
startSound()

Starts the sound.

Returns:None
pauseSound()

Pauses the sound.

Returns:None
stopSound()

Stops the sound.

Returns:None
class bge.types.KX_StateActuator(SCA_IActuator)

State actuator changes the state mask of parent object.

operation

Type of bit operation to be applied on object state mask.

You can use one of these constants

Type :integer
mask

Value that defines the bits that will be modified by the operation.

The bits that are 1 in the mask will be updated in the object state.

The bits that are 0 are will be left unmodified expect for the Copy operation which copies the mask to the object state.

Type :integer
class bge.types.KX_TrackToActuator(SCA_IActuator)

Edit Object actuator in Track To mode.

Warning

Track To Actuators will be ignored if at game start, the object to track to is invalid.

This will generate a warning in the console:

GameObject 'Name' no object in EditObjectActuator 'ActuatorName'
object

the object this actuator tracks.

Type :KX_GameObject or None
time

the time in frames with which to delay the tracking motion.

Type :integer
use3D

the tracking motion to use 3D.

Type :boolean
class bge.types.KX_VehicleWrapper(PyObjectPlus)

KX_VehicleWrapper

TODO - description

addWheel(wheel, attachPos, attachDir, axleDir, suspensionRestLength, wheelRadius, hasSteering)

Add a wheel to the vehicle

Parameters:
  • wheel (KX_GameObject or a KX_GameObject name) – The object to use as a wheel.
  • attachPos (vector of 3 floats) – The position that this wheel will attach to.
  • attachDir (vector of 3 floats) – The direction this wheel points.
  • axleDir (vector of 3 floats) – The direction of this wheels axle.
  • suspensionRestLength (float) – TODO - Description
  • wheelRadius (float) – The size of the wheel.
applyBraking(force, wheelIndex)

Apply a braking force to the specified wheel

Parameters:
  • force (float) – the brake force
  • wheelIndex (integer) – index of the wheel where the force needs to be applied
applyEngineForce(force, wheelIndex)

Apply an engine force to the specified wheel

Parameters:
  • force (float) – the engine force
  • wheelIndex (integer) – index of the wheel where the force needs to be applied
getConstraintId()

Get the constraint ID

Returns:the constraint id
Return type:integer
getConstraintType()

Returns the constraint type.

Returns:constraint type
Return type:integer
getNumWheels()

Returns the number of wheels.

Returns:the number of wheels for this vehicle
Return type:integer
getWheelOrientationQuaternion(wheelIndex)

Returns the wheel orientation as a quaternion.

Parameters:wheelIndex (integer) – the wheel index
Returns:TODO Description
Return type:TODO - type should be quat as per method name but from the code it looks like a matrix
getWheelPosition(wheelIndex)

Returns the position of the specified wheel

Parameters:wheelIndex (integer) – the wheel index
Returns:position vector
Return type:list[x, y, z]
getWheelRotation(wheelIndex)

Returns the rotation of the specified wheel

Parameters:wheelIndex (integer) – the wheel index
Returns:the wheel rotation
Return type:float
setRollInfluence(rollInfluece, wheelIndex)

Set the specified wheel’s roll influence. The higher the roll influence the more the vehicle will tend to roll over in corners.

Parameters:
  • rollInfluece (float) – the wheel roll influence
  • wheelIndex (integer) – the wheel index
setSteeringValue(steering, wheelIndex)

Set the specified wheel’s steering

Parameters:
  • steering (float) – the wheel steering
  • wheelIndex (integer) – the wheel index
setSuspensionCompression(compression, wheelIndex)

Set the specified wheel’s compression

Parameters:
  • compression (float) – the wheel compression
  • wheelIndex (integer) – the wheel index
setSuspensionDamping(damping, wheelIndex)

Set the specified wheel’s damping

Parameters:
  • damping (float) – the wheel damping
  • wheelIndex (integer) – the wheel index
setSuspensionStiffness(stiffness, wheelIndex)

Set the specified wheel’s stiffness

Parameters:
  • stiffness (float) – the wheel stiffness
  • wheelIndex (integer) – the wheel index
setTyreFriction(friction, wheelIndex)

Set the specified wheel’s tyre friction

Parameters:
  • friction (float) – the tyre friction
  • wheelIndex (integer) – the wheel index
class bge.types.KX_CharacterWrapper(PyObjectPlus)

A wrapper to expose character physics options.

onGround

Whether or not the character is on the ground. (read-only)

Type :boolean
gravity

The gravity value used for the character.

Type :float
maxJumps

The maximum number of jumps a character can perform before having to touch the ground. By default this is set to 1. 2 allows for a double jump, etc.

Type :int
jumpCount

The current jump count. This can be used to have different logic for a single jump versus a double jump. For example, a different animation for the second jump.

Type :int
jump()

The character jumps based on it’s jump speed.

class bge.types.KX_VertexProxy(SCA_IObject)

A vertex holds position, UV, color and normal information.

Note: The physics simulation is NOT currently updated - physics will not respond to changes in the vertex position.

XYZ

The position of the vertex.

Type :list [x, y, z]
UV

The texture coordinates of the vertex.

Type :list [u, v]
normal

The normal of the vertex.

Type :list [nx, ny, nz]
color

The color of the vertex.

Type :list [r, g, b, a]

Black = [0.0, 0.0, 0.0, 1.0], White = [1.0, 1.0, 1.0, 1.0]

x

The x coordinate of the vertex.

Type :float
y

The y coordinate of the vertex.

Type :float
z

The z coordinate of the vertex.

Type :float
u

The u texture coordinate of the vertex.

Type :float
v

The v texture coordinate of the vertex.

Type :float
u2

The second u texture coordinate of the vertex.

Type :float
v2

The second v texture coordinate of the vertex.

Type :float
r

The red component of the vertex color. 0.0 <= r <= 1.0.

Type :float
g

The green component of the vertex color. 0.0 <= g <= 1.0.

Type :float
b

The blue component of the vertex color. 0.0 <= b <= 1.0.

Type :float
a

The alpha component of the vertex color. 0.0 <= a <= 1.0.

Type :float
getXYZ()

Gets the position of this vertex.

Returns:this vertexes position in local coordinates.
Return type:list [x, y, z]
setXYZ(pos)

Sets the position of this vertex.

Type :list [x, y, z]
Parameters:pos – the new position for this vertex in local coordinates.
getUV()

Gets the UV (texture) coordinates of this vertex.

Returns:this vertexes UV (texture) coordinates.
Return type:list [u, v]
setUV(uv)

Sets the UV (texture) coordinates of this vertex.

Type :list [u, v]
getUV2()

Gets the 2nd UV (texture) coordinates of this vertex.

Returns:this vertexes UV (texture) coordinates.
Return type:list [u, v]
setUV2(uv, unit)

Sets the 2nd UV (texture) coordinates of this vertex.

Type :

list [u, v]

Parameters:
  • unit – optional argument, FLAT==1, SECOND_UV==2, defaults to SECOND_UV
  • unit – integer
getRGBA()

Gets the color of this vertex.

The color is represented as four bytes packed into an integer value. The color is packed as RGBA.

Since Python offers no way to get each byte without shifting, you must use the struct module to access color in an machine independent way.

Because of this, it is suggested you use the r, g, b and a attributes or the color attribute instead.

import struct;
col = struct.unpack('4B', struct.pack('I', v.getRGBA()))
# col = (r, g, b, a)
# black = (  0, 0, 0, 255)
# white = (255, 255, 255, 255)
Returns:packed color. 4 byte integer with one byte per color channel in RGBA format.
Return type:integer
setRGBA(col)

Sets the color of this vertex.

See getRGBA() for the format of col, and its relevant problems. Use the r, g, b and a attributes or the color attribute instead.

setRGBA() also accepts a four component list as argument col. The list represents the color as [r, g, b, a] with black = [0.0, 0.0, 0.0, 1.0] and white = [1.0, 1.0, 1.0, 1.0]

v.setRGBA(0xff0000ff) # Red
v.setRGBA(0xff00ff00) # Green on little endian, transparent purple on big endian
v.setRGBA([1.0, 0.0, 0.0, 1.0]) # Red
v.setRGBA([0.0, 1.0, 0.0, 1.0]) # Green on all platforms.
Parameters:col (integer or list [r, g, b, a]) – the new color of this vertex in packed RGBA format.
getNormal()

Gets the normal vector of this vertex.

Returns:normalized normal vector.
Return type:list [nx, ny, nz]
setNormal(normal)

Sets the normal vector of this vertex.

Type :sequence of floats [r, g, b]
Parameters:normal – the new normal of this vertex.
class bge.types.KX_VisibilityActuator(SCA_IActuator)

Visibility Actuator.

visibility

whether the actuator makes its parent object visible or invisible.

Type :boolean
useOcclusion

whether the actuator makes its parent object an occluder or not.

Type :boolean
useRecursion

whether the visibility/occlusion should be propagated to all children of the object.

Type :boolean
class bge.types.SCA_2DFilterActuator(SCA_IActuator)

Create, enable and disable 2D filters

The following properties don’t have an immediate effect. You must active the actuator to get the result. The actuator is not persistent: it automatically stops itself after setting up the filter but the filter remains active. To stop a filter you must activate the actuator with ‘type’ set to RAS_2DFILTER_DISABLED or RAS_2DFILTER_NOFILTER.

shaderText

shader source code for custom shader.

Type :string
disableMotionBlur

action on motion blur: 0=enable, 1=disable.

Type :integer
mode

Type of 2D filter, use one of these constants

Type :integer
passNumber

order number of filter in the stack of 2D filters. Filters are executed in increasing order of passNb.

Only be one filter can be defined per passNb.

Type :integer (0-100)
value

argument for motion blur filter.

Type :float (0.0-100.0)
class bge.types.SCA_ANDController(SCA_IController)

An AND controller activates only when all linked sensors are activated.

There are no special python methods for this controller.

class bge.types.SCA_ActuatorSensor(SCA_ISensor)

Actuator sensor detect change in actuator state of the parent object. It generates a positive pulse if the corresponding actuator is activated and a negative pulse if the actuator is deactivated.

actuator

the name of the actuator that the sensor is monitoring.

Type :string
class bge.types.SCA_AlwaysSensor(SCA_ISensor)

This sensor is always activated.

class bge.types.SCA_DelaySensor(SCA_ISensor)

The Delay sensor generates positive and negative triggers at precise time, expressed in number of frames. The delay parameter defines the length of the initial OFF period. A positive trigger is generated at the end of this period.

The duration parameter defines the length of the ON period following the OFF period. There is a negative trigger at the end of the ON period. If duration is 0, the sensor stays ON and there is no negative trigger.

The sensor runs the OFF-ON cycle once unless the repeat option is set: the OFF-ON cycle repeats indefinately (or the OFF cycle if duration is 0).

Use SCA_ISensor.reset at any time to restart sensor.

delay

length of the initial OFF period as number of frame, 0 for immediate trigger.

Type :integer.
duration

length of the ON period in number of frame after the initial OFF period.

If duration is greater than 0, a negative trigger is sent at the end of the ON pulse.

Type :integer
repeat

1 if the OFF-ON cycle should be repeated indefinately, 0 if it should run once.

Type :integer
class bge.types.SCA_JoystickSensor(SCA_ISensor)

This sensor detects player joystick events.

axisValues

The state of the joysticks axis as a list of values numAxis long. (read-only).

Type :list of ints.

Each specifying the value of an axis between -32767 and 32767 depending on how far the axis is pushed, 0 for nothing. The first 2 values are used by most joysticks and gamepads for directional control. 3rd and 4th values are only on some joysticks and can be used for arbitary controls.

  • left:[-32767, 0, ...]
  • right:[32767, 0, ...]
  • up:[0, -32767, ...]
  • down:[0, 32767, ...]
axisSingle

like axisValues but returns a single axis value that is set by the sensor. (read-only).

Type :integer

Note

Only use this for “Single Axis” type sensors otherwise it will raise an error.

hatValues

The state of the joysticks hats as a list of values numHats long. (read-only).

Type :list of ints

Each specifying the direction of the hat from 1 to 12, 0 when inactive.

Hat directions are as follows...

  • 0:None
  • 1:Up
  • 2:Right
  • 4:Down
  • 8:Left
  • 3:Up - Right
  • 6:Down - Right
  • 12:Down - Left
  • 9:Up - Left
hatSingle

Like hatValues but returns a single hat direction value that is set by the sensor. (read-only).

Type :integer
numAxis

The number of axes for the joystick at this index. (read-only).

Type :integer
numButtons

The number of buttons for the joystick at this index. (read-only).

Type :integer
numHats

The number of hats for the joystick at this index. (read-only).

Type :integer
connected

True if a joystick is connected at this joysticks index. (read-only).

Type :boolean
index

The joystick index to use (from 0 to 7). The first joystick is always 0.

Type :integer
threshold

Axis threshold. Joystick axis motion below this threshold wont trigger an event. Use values between (0 and 32767), lower values are more sensitive.

Type :integer
button

The button index the sensor reacts to (first button = 0). When the “All Events” toggle is set, this option has no effect.

Type :integer
axis

The axis this sensor reacts to, as a list of two values [axisIndex, axisDirection]

  • axisIndex: the axis index to use when detecting axis movement, 1=primary directional control, 2=secondary directional control.
  • axisDirection: 0=right, 1=up, 2=left, 3=down.
Type :[integer, integer]
hat

The hat the sensor reacts to, as a list of two values: [hatIndex, hatDirection]

  • hatIndex: the hat index to use when detecting hat movement, 1=primary hat, 2=secondary hat (4 max).
  • hatDirection: 1-12.
Type :[integer, integer]
getButtonActiveList()
Returns:A list containing the indicies of the currently pressed buttons.
Return type:list
getButtonStatus(buttonIndex)
Parameters:buttonIndex (integer) – the button index, 0=first button
Returns:The current pressed state of the specified button.
Return type:boolean
class bge.types.SCA_KeyboardSensor(SCA_ISensor)

A keyboard sensor detects player key presses.

See module bge.keys for keycode values.

key

The key code this sensor is looking for.

Type :keycode from bge.keys module
hold1

The key code for the first modifier this sensor is looking for.

Type :keycode from bge.keys module
hold2

The key code for the second modifier this sensor is looking for.

Type :keycode from bge.keys module
toggleProperty

The name of the property that indicates whether or not to log keystrokes as a string.

Type :string
targetProperty

The name of the property that receives keystrokes in case in case a string is logged.

Type :string
useAllKeys

Flag to determine whether or not to accept all keys.

Type :boolean
events

a list of pressed keys that have either been pressed, or just released, or are active this frame. (read-only).

Type :list [[keycode, status], ...]
getKeyStatus(keycode)

Get the status of a key.

Parameters:keycode (integer) – The code that represents the key you want to get the state of, use one of these constants
Returns:The state of the given key, can be one of these constants
Return type:int
class bge.types.SCA_NANDController(SCA_IController)

An NAND controller activates when all linked sensors are not active.

There are no special python methods for this controller.

class bge.types.SCA_NORController(SCA_IController)

An NOR controller activates only when all linked sensors are de-activated.

There are no special python methods for this controller.

class bge.types.SCA_ORController(SCA_IController)

An OR controller activates when any connected sensor activates.

There are no special python methods for this controller.

class bge.types.SCA_PropertyActuator(SCA_IActuator)

Property Actuator

propName

the property on which to operate.

Type :string
value

the value with which the actuator operates.

Type :string
mode

TODO - add constants to game logic dict!.

Type :integer
class bge.types.SCA_PropertySensor(SCA_ISensor)

Activates when the game object property matches.

mode

Type of check on the property. Can be one of these constants

Type :integer.
propName

the property the sensor operates.

Type :string
value

the value with which the sensor compares to the value of the property.

Type :string
min

the minimum value of the range used to evaluate the property when in interval mode.

Type :string
max

the maximum value of the range used to evaluate the property when in interval mode.

Type :string
class bge.types.SCA_PythonController(SCA_IController)

A Python controller uses a Python script to activate it’s actuators, based on it’s sensors.

script

The value of this variable depends on the execution methid.

  • When ‘Script’ execution mode is set this value contains the entire python script as a single string (not the script name as you might expect) which can be modified to run different scripts.
  • When ‘Module’ execution mode is set this value will contain a single line string - module name and function “module.func” or “package.modile.func” where the module names are python textblocks or external scripts.
Type :string

Note

Once this is set the script name given for warnings will remain unchanged.

mode

the execution mode for this controller (read-only).

  • Script: 0, Execite the script as a python code.
  • Module: 1, Execite the script as a module and function.
Type :integer
activate(actuator)

Activates an actuator attached to this controller.

Parameters:actuator (actuator or the actuator name as a string) – The actuator to operate on.
deactivate(actuator)

Deactivates an actuator attached to this controller.

Parameters:actuator (actuator or the actuator name as a string) – The actuator to operate on.
class bge.types.SCA_RandomActuator(SCA_IActuator)

Random Actuator

seed

Seed of the random number generator.

Type :integer.

Equal seeds produce equal series. If the seed is 0, the generator will produce the same value on every call.

para1

the first parameter of the active distribution.

Type :float, read-only.

Refer to the documentation of the generator types for the meaning of this value.

para2

the second parameter of the active distribution.

Type :float, read-only

Refer to the documentation of the generator types for the meaning of this value.

distribution

Distribution type. (read-only). Can be one of these constants

Type :integer
propName

the name of the property to set with the random value.

Type :string

If the generator and property types do not match, the assignment is ignored.

setBoolConst(value)

Sets this generator to produce a constant boolean value.

Parameters:value (boolean) – The value to return.
setBoolUniform()

Sets this generator to produce a uniform boolean distribution.

The generator will generate True or False with 50% chance.

setBoolBernouilli(value)

Sets this generator to produce a Bernouilli distribution.

Parameters:value (float) –

Specifies the proportion of False values to produce.

  • 0.0: Always generate True
  • 1.0: Always generate False
setIntConst(value)

Sets this generator to always produce the given value.

Parameters:value (integer) – the value this generator produces.
setIntUniform(lower_bound, upper_bound)

Sets this generator to produce a random value between the given lower and upper bounds (inclusive).

setIntPoisson(value)

Generate a Poisson-distributed number.

This performs a series of Bernouilli tests with parameter value. It returns the number of tries needed to achieve succes.

setFloatConst(value)

Always generate the given value.

setFloatUniform(lower_bound, upper_bound)

Generates a random float between lower_bound and upper_bound with a uniform distribution.

setFloatNormal(mean, standard_deviation)

Generates a random float from the given normal distribution.

Parameters:
  • mean (float) – The mean (average) value of the generated numbers
  • standard_deviation (float) – The standard deviation of the generated numbers.
setFloatNegativeExponential(half_life)

Generate negative-exponentially distributed numbers.

The half-life ‘time’ is characterized by half_life.

class bge.types.SCA_RandomSensor(SCA_ISensor)

This sensor activates randomly.

lastDraw

The seed of the random number generator.

Type :integer
seed

The seed of the random number generator.

Type :integer
class bge.types.SCA_XNORController(SCA_IController)

An XNOR controller activates when all linked sensors are the same (activated or inative).

There are no special python methods for this controller.

class bge.types.SCA_XORController(SCA_IController)

An XOR controller activates when there is the input is mixed, but not when all are on or off.

There are no special python methods for this controller.

class bge.types.KX_Camera(KX_GameObject)

A Camera object.

INSIDE

See sphereInsideFrustum and boxInsideFrustum

INTERSECT

See sphereInsideFrustum and boxInsideFrustum

OUTSIDE

See sphereInsideFrustum and boxInsideFrustum

lens

The camera’s lens value.

Type :float
ortho_scale

The camera’s view scale when in orthographic mode.

Type :float
near

The camera’s near clip distance.

Type :float
far

The camera’s far clip distance.

Type :float
perspective

True if this camera has a perspective transform, False for an orthographic projection.

Type :boolean
frustum_culling

True if this camera is frustum culling.

Type :boolean
projection_matrix

This camera’s 4x4 projection matrix.

Note

This is the identity matrix prior to rendering the first frame (any Python done on frame 1).

Type :4x4 Matrix [[float]]
modelview_matrix

This camera’s 4x4 model view matrix. (read-only).

Type :4x4 Matrix [[float]]

Note

This matrix is regenerated every frame from the camera’s position and orientation. Also, this is the identity matrix prior to rendering the first frame (any Python done on frame 1).

camera_to_world

This camera’s camera to world transform. (read-only).

Type :4x4 Matrix [[float]]

Note

This matrix is regenerated every frame from the camera’s position and orientation.

world_to_camera

This camera’s world to camera transform. (read-only).

Type :4x4 Matrix [[float]]

Note

Regenerated every frame from the camera’s position and orientation.

Note

This is camera_to_world inverted.

useViewport

True when the camera is used as a viewport, set True to enable a viewport for this camera.

Type :boolean
sphereInsideFrustum(centre, radius)

Tests the given sphere against the view frustum.

Parameters:
  • centre (list [x, y, z]) – The centre of the sphere (in world coordinates.)
  • radius (float) – the radius of the sphere
Returns:

INSIDE, OUTSIDE or INTERSECT

Return type:

integer

Note

When the camera is first initialized the result will be invalid because the projection matrix has not been set.

from bge import logic
cont = logic.getCurrentController()
cam = cont.owner

# A sphere of radius 4.0 located at [x, y, z] = [1.0, 1.0, 1.0]
if (cam.sphereInsideFrustum([1.0, 1.0, 1.0], 4) != cam.OUTSIDE):
    # Sphere is inside frustum !
    # Do something useful !
else:
    # Sphere is outside frustum
boxInsideFrustum(box)

Tests the given box against the view frustum.

Parameters:box (list of lists) – Eight (8) corner points of the box (in world coordinates.)
Returns:INSIDE, OUTSIDE or INTERSECT

Note

When the camera is first initialized the result will be invalid because the projection matrix has not been set.

from bge import logic
cont = logic.getCurrentController()
cam = cont.owner

# Box to test...
box = []
box.append([-1.0, -1.0, -1.0])
box.append([-1.0, -1.0,  1.0])
box.append([-1.0,  1.0, -1.0])
box.append([-1.0,  1.0,  1.0])
box.append([ 1.0, -1.0, -1.0])
box.append([ 1.0, -1.0,  1.0])
box.append([ 1.0,  1.0, -1.0])
box.append([ 1.0,  1.0,  1.0])

if (cam.boxInsideFrustum(box) != cam.OUTSIDE):
  # Box is inside/intersects frustum !
  # Do something useful !
else:
  # Box is outside the frustum !
pointInsideFrustum(point)

Tests the given point against the view frustum.

Parameters:point (3D Vector) – The point to test (in world coordinates.)
Returns:True if the given point is inside this camera’s viewing frustum.
Return type:boolean

Note

When the camera is first initialized the result will be invalid because the projection matrix has not been set.

from bge import logic
cont = logic.getCurrentController()
cam = cont.owner

# Test point [0.0, 0.0, 0.0]
if (cam.pointInsideFrustum([0.0, 0.0, 0.0])):
  # Point is inside frustum !
  # Do something useful !
else:
  # Box is outside the frustum !
getCameraToWorld()

Returns the camera-to-world transform.

Returns:the camera-to-world transform matrix.
Return type:matrix (4x4 list)
getWorldToCamera()

Returns the world-to-camera transform.

This returns the inverse matrix of getCameraToWorld().

Returns:the world-to-camera transform matrix.
Return type:matrix (4x4 list)
setOnTop()

Set this cameras viewport ontop of all other viewport.

setViewport(left, bottom, right, top)

Sets the region of this viewport on the screen in pixels.

Use bge.render.getWindowHeight and bge.render.getWindowWidth to calculate values relative to the entire display.

Parameters:
  • left (integer) – left pixel coordinate of this viewport
  • bottom (integer) – bottom pixel coordinate of this viewport
  • right (integer) – right pixel coordinate of this viewport
  • top (integer) – top pixel coordinate of this viewport
getScreenPosition(object)

Gets the position of an object projected on screen space.

# For an object in the middle of the screen, coord = [0.5, 0.5]
coord = camera.getScreenPosition(object)
Parameters:object (KX_GameObject or 3D Vector) – object name or list [x, y, z]
Returns:the object’s position in screen coordinates.
Return type:list [x, y]
getScreenVect(x, y)

Gets the vector from the camera position in the screen coordinate direction.

Parameters:
  • x (float) – X Axis
  • y (float) – Y Axis
Return type:

3D Vector

Returns:

The vector from screen coordinate.

# Gets the vector of the camera front direction:
m_vect = camera.getScreenVect(0.5, 0.5)
getScreenRay(x, y, dist=inf, property=None)

Look towards a screen coordinate (x, y) and find first object hit within dist that matches prop. The ray is similar to KX_GameObject->rayCastTo.

Parameters:
  • x (float) – X Axis
  • y (float) – Y Axis
  • dist (float) – max distance to look (can be negative => look behind); 0 or omitted => detect up to other
  • property (string) – property name that object must have; can be omitted => detect any object
Return type:

KX_GameObject

Returns:

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

# Gets an object with a property "wall" in front of the camera within a distance of 100:
target = camera.getScreenRay(0.5, 0.5, 100, "wall")
class bge.types.BL_ArmatureObject(KX_GameObject)

An armature object.

constraints

The list of armature constraint defined on this armature. Elements of the list can be accessed by index or string. The key format for string access is ‘<bone_name>:<constraint_name>’.

Type :list of BL_ArmatureConstraint
channels

The list of armature channels. Elements of the list can be accessed by index or name the bone.

Type :list of BL_ArmatureChannel
update()

Ensures that the armature will be updated on next graphic frame.

This action is unecessary if a KX_ArmatureActuator with mode run is active or if an action is playing. Use this function in other cases. It must be called on each frame to ensure that the armature is updated continously.

class bge.types.BL_ArmatureActuator(SCA_IActuator)

Armature Actuators change constraint condition on armatures.

type

The type of action that the actuator executes when it is active.

Can be one of these constants

Type :integer
constraint

The constraint object this actuator is controlling.

Type :BL_ArmatureConstraint
target

The object that this actuator will set as primary target to the constraint it controls.

Type :KX_GameObject
subtarget

The object that this actuator will set as secondary target to the constraint it controls.

Type :KX_GameObject.

Note

Currently, the only secondary target is the pole target for IK constraint.

weight

The weight this actuator will set on the constraint it controls.

Type :float.

Note

Currently only the IK constraint has a weight. It must be a value between 0 and 1.

Note

A weight of 0 disables a constraint while still updating constraint runtime values (see BL_ArmatureConstraint)

influence

The influence this actuator will set on the constraint it controls.

Type :float.
class bge.types.KX_ArmatureSensor(SCA_ISensor)

Armature sensor detect conditions on armatures.

type

The type of measurement that the sensor make when it is active.

Can be one of these constants

Type :integer.
constraint

The constraint object this sensor is watching.

Type :BL_ArmatureConstraint
value

The threshold used in the comparison with the constraint error The linear error is only updated on CopyPose/Distance IK constraint with iTaSC solver The rotation error is only updated on CopyPose+rotation IK constraint with iTaSC solver The linear error on CopyPose is always >= 0: it is the norm of the distance between the target and the bone The rotation error on CopyPose is always >= 0: it is the norm of the equivalent rotation vector between the bone and the target orientations The linear error on Distance can be positive if the distance between the bone and the target is greater than the desired distance, and negative if the distance is smaller.

Type :float
class bge.types.BL_ArmatureConstraint(PyObjectPlus)

Proxy to Armature Constraint. Allows to change constraint on the fly. Obtained through BL_ArmatureObject.constraints.

Note

Not all armature constraints are supported in the GE.

type

Type of constraint, (read-only).

Use one of these constants.

Type :integer, one of CONSTRAINT_TYPE_* constants
name

Name of constraint constructed as <bone_name>:<constraint_name>. constraints list.

Type :string

This name is also the key subscript on BL_ArmatureObject.

enforce

fraction of constraint effect that is enforced. Between 0 and 1.

Type :float
headtail

Position of target between head and tail of the target bone: 0=head, 1=tail.

Type :float.

Note

Only used if the target is a bone (i.e target object is an armature.

lin_error

runtime linear error (in Blender units) on constraint at the current frame.

This is a runtime value updated on each frame by the IK solver. Only available on IK constraint and iTaSC solver.

Type :float
rot_error

Runtime rotation error (in radiant) on constraint at the current frame.

Type :float.

This is a runtime value updated on each frame by the IK solver. Only available on IK constraint and iTaSC solver.

It is only set if the constraint has a rotation part, for example, a CopyPose+Rotation IK constraint.

target

Primary target object for the constraint. The position of this object in the GE will be used as target for the constraint.

Type :KX_GameObject.
subtarget

Secondary target object for the constraint. The position of this object in the GE will be used as secondary target for the constraint.

Type :KX_GameObject.

Currently this is only used for pole target on IK constraint.

active

True if the constraint is active.

Type :boolean

Note

An inactive constraint does not update lin_error and rot_error.

ik_weight

Weight of the IK constraint between 0 and 1.

Only defined for IK constraint.

Type :float
ik_type

Type of IK constraint, (read-only).

Use one of these constants.

Type :integer.
ik_flag

Combination of IK constraint option flags, read-only.

Use one of these constants.

Type :integer
ik_dist

Distance the constraint is trying to maintain with target, only used when ik_type=CONSTRAINT_IK_DISTANCE.

Type :float
ik_mode

Use one of these constants.

Additional mode for IK constraint. Currently only used for Distance constraint:

Type :integer
class bge.types.BL_ArmatureChannel(PyObjectPlus)

Proxy to armature pose channel. Allows to read and set armature pose. The attributes are identical to RNA attributes, but mostly in read-only mode.

name

channel name (=bone name), read-only.

Type :string
bone

return the bone object corresponding to this pose channel, read-only.

Type :BL_ArmatureBone
parent

return the parent channel object, None if root channel, read-only.

Type :BL_ArmatureChannel
has_ik

true if the bone is part of an active IK chain, read-only. This flag is not set when an IK constraint is defined but not enabled (miss target information for example).

Type :boolean
ik_dof_x

true if the bone is free to rotation in the X axis, read-only.

Type :boolean
ik_dof_y

true if the bone is free to rotation in the Y axis, read-only.

Type :boolean
ik_dof_z

true if the bone is free to rotation in the Z axis, read-only.

Type :boolean
ik_limit_x

true if a limit is imposed on X rotation, read-only.

Type :boolean
ik_limit_y

true if a limit is imposed on Y rotation, read-only.

Type :boolean
ik_limit_z

true if a limit is imposed on Z rotation, read-only.

Type :boolean
ik_rot_control

true if channel rotation should applied as IK constraint, read-only.

Type :boolean
ik_lin_control

true if channel size should applied as IK constraint, read-only.

Type :boolean
location

displacement of the bone head in armature local space, read-write.

Type :vector [X, Y, Z].

Note

You can only move a bone if it is unconnected to its parent. An action playing on the armature may change the value. An IK chain does not update this value, see joint_rotation.

Note

Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see BL_ArmatureObject.update).

scale

scale of the bone relative to its parent, read-write.

Type :vector [sizeX, sizeY, sizeZ].

Note

An action playing on the armature may change the value. An IK chain does not update this value, see joint_rotation.

Note

Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see BL_ArmatureObject.update)

rotation_quaternion

rotation of the bone relative to its parent expressed as a quaternion, read-write.

Type :vector [qr, qi, qj, qk].

Note

This field is only used if rotation_mode is 0. An action playing on the armature may change the value. An IK chain does not update this value, see joint_rotation.

Note

Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see BL_ArmatureObject.update)

rotation_euler

rotation of the bone relative to its parent expressed as a set of euler angles, read-write.

Type :vector [X, Y, Z].

Note

This field is only used if rotation_mode is > 0. You must always pass the angles in [X, Y, Z] order; the order of applying the angles to the bone depends on rotation_mode. An action playing on the armature may change this field. An IK chain does not update this value, see joint_rotation.

Note

Changing this field has no immediate effect, the pose is updated when the armature is updated during the graphic render (see BL_ArmatureObject.update)

rotation_mode

Method of updating the bone rotation, read-write.

Type :integer (one of these constants)
channel_matrix

pose matrix in bone space (deformation of the bone due to action, constraint, etc), Read-only. This field is updated after the graphic render, it represents the current pose.

Type :matrix [4][4]
pose_matrix

pose matrix in armature space, read-only, This field is updated after the graphic render, it represents the current pose.

Type :matrix [4][4]
pose_head

position of bone head in armature space, read-only.

Type :vector [x, y, z]
pose_tail

position of bone tail in armature space, read-only.

Type :vector [x, y, z]
ik_min_x

minimum value of X rotation in degree (<= 0) when X rotation is limited (see ik_limit_x), read-only.

Type :float
ik_max_x

maximum value of X rotation in degree (>= 0) when X rotation is limited (see ik_limit_x), read-only.

Type :float
ik_min_y

minimum value of Y rotation in degree (<= 0) when Y rotation is limited (see ik_limit_y), read-only.

Type :float
ik_max_y

maximum value of Y rotation in degree (>= 0) when Y rotation is limited (see ik_limit_y), read-only.

Type :float
ik_min_z

minimum value of Z rotation in degree (<= 0) when Z rotation is limited (see ik_limit_z), read-only.

Type :float
ik_max_z

maximum value of Z rotation in degree (>= 0) when Z rotation is limited (see ik_limit_z), read-only.

Type :float
ik_stiffness_x

bone rotation stiffness in X axis, read-only.

Type :float between 0 and 1
ik_stiffness_y

bone rotation stiffness in Y axis, read-only.

Type :float between 0 and 1
ik_stiffness_z

bone rotation stiffness in Z axis, read-only.

Type :float between 0 and 1
ik_stretch

ratio of scale change that is allowed, 0=bone can’t change size, read-only.

Type :float
ik_rot_weight

weight of rotation constraint when ik_rot_control is set, read-write.

Type :float between 0 and 1
ik_lin_weight

weight of size constraint when ik_lin_control is set, read-write.

Type :float between 0 and 1
joint_rotation

Control bone rotation in term of joint angle (for robotic applications), read-write.

When writing to this attribute, you pass a [x, y, z] vector and an appropriate set of euler angles or quaternion is calculated according to the rotation_mode.

When you read this attribute, the current pose matrix is converted into a [x, y, z] vector representing the joint angles.

The value and the meaning of the x, y, z depends on the ik_dof_x/ik_dof_y/ik_dof_z attributes:

  • 1DoF joint X, Y or Z: the corresponding x, y, or z value is used an a joint angle in radiant
  • 2DoF joint X+Y or Z+Y: treated as 2 successive 1DoF joints: first X or Z, then Y. The x or z value is used as a joint angle in radiant along the X or Z axis, followed by a rotation along the new Y axis of y radiants.
  • 2DoF joint X+Z: treated as a 2DoF joint with rotation axis on the X/Z plane. The x and z values are used as the coordinates of the rotation vector in the X/Z plane.
  • 3DoF joint X+Y+Z: treated as a revolute joint. The [x, y, z] vector represents the equivalent rotation vector to bring the joint from the rest pose to the new pose.
Type :vector [x, y, z]

Note

The bone must be part of an IK chain if you want to set the ik_dof_x/ik_dof_y/ik_dof_z attributes via the UI, but this will interfere with this attribute since the IK solver will overwrite the pose. You can stay in control of the armature if you create an IK constraint but do not finalize it (e.g. don’t set a target) the IK solver will not run but the IK panel will show up on the UI for each bone in the chain.

Note

[0, 0, 0] always corresponds to the rest pose.

Note

You must request the armature pose to update and wait for the next graphic frame to see the effect of setting this attribute (see BL_ArmatureObject.update).

Note

You can read the result of the calculation in rotation or euler_rotation attributes after setting this attribute.

class bge.types.BL_ArmatureBone(PyObjectPlus)

Proxy to Blender bone structure. All fields are read-only and comply to RNA names. All space attribute correspond to the rest pose.

name

bone name.

Type :string
connected

true when the bone head is struck to the parent’s tail.

Type :boolean
hinge

true when bone doesn’t inherit rotation or scale from parent bone.

Type :boolean
inherit_scale

true when bone inherits scaling from parent bone.

Type :boolean
bbone_segments

number of B-bone segments.

Type :integer
roll

bone rotation around head-tail axis.

Type :float
head

location of head end of the bone in parent bone space.

Type :vector [x, y, z]
tail

location of head end of the bone in parent bone space.

Type :vector [x, y, z]
length

bone length.

Type :float
arm_head

location of head end of the bone in armature space.

Type :vector [x, y, z]
arm_tail

location of tail end of the bone in armature space.

Type :vector [x, y, z]
arm_mat

matrix of the bone head in armature space.

Type :matrix [4][4]

Note

This matrix has no scale part.

bone_mat

rotation matrix of the bone in parent bone space.

Type :matrix [3][3]
parent

parent bone, or None for root bone.

Type :BL_ArmatureBone
children

list of bone’s children.

Type :list of BL_ArmatureBone

Table Of Contents

Previous topic

BMesh Module (bmesh)

Next topic

Game Logic (bge.logic)