Git: https://github.com/oshcherbyna/blender-module-system
- main.py
- module_keyconfig.py
- module_keyconfig_operators.py
- module_player.py
Blend: player_wasd_moving_v1.0.blend
Thanks to keyconfig, Blender allows us to register the keyboard keys and mouse buttons necessary for the game.
- First, we need to init the player’s props - boolean flags that reflect the state of movement: forward, backward, right, left. Each of them can have only two states True/False.
- The Blender operators work on the internal blender loop, so they track the pressing and releasing of the keys immediately after registration. They do not require frame animation of the scene. Since there can be a lot of keyconfig operators, I put them in a separate file module_keyconfig_operators.py. Here I added operators that change the state of the corresponding motion flag (separately on, separately off for each flag).
module_keyconfig_operators.py
import bpy
#player = bpy.data.objects['Cube']
player = bpy.context.scene["player"]
class MoveLeftOn(bpy.types.Operator):
'''
Move Left on-state
'''
bl_idname = "player.move_left_on"
bl_label = "Move Left On"
def execute(self, context):
player["moveLeft"] = True
print('player["moveLeft"] =', player["moveLeft"])
return {'FINISHED'}
class MoveLeftOff(bpy.types.Operator):
'''
Move Left off-state
'''
bl_idname = "player.move_left_off"
bl_label = "Move Left Off"
def execute(self, context):
player["moveLeft"] = False
print('player["moveLeft"] =', player["moveLeft"])
return {'FINISHED'}
- The module_keyconfig.py file contains the binding of the necessary keyboard keys in the PRESS (activated) and RELEASE (not activated) states with the corresponding operators.
addon_keymaps = []
game_keys = {
'Move Up On': ('3D View', 'player.move_up_on', 'W', 'PRESS'), # WASD-Moving
'Move Up Off': ('3D View', 'player.move_up_off', 'W', 'RELEASE'),
..
The keys are added to the addon keyconfig, as recommended by the Blender documentation. This allows you to place custom keys above the default ones, thereby overriding their action. However, the keys should be added to the keyconfig sections where the keys you want to replace are located… in my case, it is ‘3D View’ for W, D and ‘Object Mode’ for A, S.
-
I put the mechanics of changing the position and orientation of the object in module_player.py, where the initialization of the motion flags is also located.
-
The only thing left to do is to add the update(player) method to the game loop and enable the scene frame animation.
-
For ground snapping, I use the Shrinkwrap constraint.