杰瑞科技汇

python blender bge

Of course! This is a fantastic topic. Let's break down how to use Python within the Blender Game Engine (BGE).

python blender bge-图1
(图片来源网络,侵删)

First, a crucial point of context:

The Blender Game Engine (BGE) has been officially removed from Blender as of version 2.80. It was replaced by Blender's new real-time engine, which is much more powerful and flexible.

So, when people talk about "Python in BGE" today, they usually mean one of two things:

  1. Legacy BGE: Working with older Blender versions (2.79b and earlier) or legacy projects. The principles are still valuable for understanding game logic in Blender.
  2. Modern Blender (2.80+): Using Python to control the new real-time engine, which is often used for creating games, architectural visualizations, simulations, and interactive applications.

I will cover both, starting with the classic BGE approach as it's a great foundation, and then moving to the modern way.

python blender bge-图2
(图片来源网络,侵删)

Part 1: The Classic Blender Game Engine (BGE) - Legacy

In the BGE, Python scripts are attached to Logic Bricks. The most common brick is the Python Controller. This controller runs a Python script every time its condition is met.

Key Concepts in Classic BGE Python

  • bge Module: This is your gateway to the entire BGE. You import it to access game objects, scenes, controllers, etc. import bge

  • Accessing Objects: You get a reference to a game object from the current scene. cont = bge.logic.getCurrentController() own = cont.owner # The object this script is attached to scene = bge.logic.getCurrentScene() obj = scene.objects["MyObjectName"]

  • Logic Bricks: The Python script is almost always used inside a "Python Controller" logic brick. This controller has a "Which" property that determines how often the script runs:

    • ALWAYS: Runs every frame.
    • SENSOR: Runs when the linked sensor (e.g., Keyboard, Mouse) is activated.
    • ACTIVATOR: Runs when the linked actuator (e.g., Motion, Action) is activated.
  • Common bge Classes:

    • KX_GameObject: Represents anything in the game world (a cube, a camera, a lamp). You can read/write its properties, play animations, apply forces, etc.
    • KX_Camera: A special type of KX_GameObject for the player's viewpoint.
    • KX_Scene: The collection of all objects in a game level.
    • KI_Actuator: An actuator that performs an action (move, play sound, spawn object).
    • KX_Sensor: A sensor that detects input or events (keyboard, mouse, collision).

Example 1: Make an object move when the 'W' key is pressed

This is a classic "first-person" movement script.

  1. Setup:

    • Add a cube. Name it Player.
    • Add a camera. Parent the camera to the Player cube (select camera, then shift-select cube, Ctrl+P -> "Object Parent").
    • Select the Player cube and go to the Logic Editor.
  2. Logic Bricks Setup:

    • Add a Keyboard sensor. Set its Key to W.
    • Add a And controller (to link the sensor to the script).
    • Add a Python controller.
    • Wire them: Keyboard -> And -> Python.
  3. Python Script:

    • Click the "Python" controller and click the "Script" button to open the text editor.
    • Paste this code:
    import bge
    def main():
        # Get the controller and the object this script is attached to
        cont = bge.logic.getCurrentController()
        own = cont.owner
        # Get the keyboard sensor linked to this controller
        # We name it 'Keyboard' in the Logic Editor, so we use that name.
        keyboard = cont.sensors['Keyboard']
        # If the 'W' key is pressed...
        if keyboard.positive:
            # ...move the object forward on its local Z axis
            # The (0, 0, 0.2) is the movement vector
            own.applyMovement([0, 0, 0.2], True)
    # Run the main function
    main()
    • Press P to play the game. Your cube (and camera) should now move forward when you press 'W'.

Example 2: Rotate an object with the mouse

  1. Setup:

    • Add a cube. Name it RotatingCube.
    • Select the RotatingCube and go to the Logic Editor.
  2. Logic Bricks Setup:

    • Add a Mouse sensor. Set Mouse Movement to X-Axis.
    • Add a Python controller.
    • Wire them: Mouse -> Python.
  3. Python Script:

    • Click the "Python" controller and add this script:
    import bge
    def main():
        cont = bge.logic.getCurrentController()
        own = cont.owner
        # Get the mouse sensor
        mouse = cont.sensors['Mouse']
        # The mouse sensor's 'movement' attribute gives the X and Y movement
        # We only care about the X movement for left/right rotation
        x_movement = mouse.movement[0]
        # Apply rotation around the local Z axis
        # The sensitivity can be adjusted by changing the 0.05 factor
        own.applyRotation([0, 0, x_movement * 0.05], True)
    main()
    • Press P to play. Move your mouse left and right to rotate the cube.

Part 2: The Modern Blender Engine (2.80+)

The new engine is more integrated with Blender's core Python API (bpy). While you can still use a "Scripting" logic brick, the modern approach is to use Python Drivers or Scripted Operators for more complex, frame-independent logic.

However, for real-time interaction (like in a game), you often still use logic bricks, but the Python code is slightly different. The bge module is gone. You now use bpy and the bpy.types module.

Key Concepts in Modern Blender Engine Python

  • bpy Module: This is the standard Blender Python API. You use it to control almost everything. import bpy

  • Accessing the Scene and View Layer: You need to get the current scene and the "view layer" that holds the game objects. scene = bpy.context.scene view_layer = bpy.context.view_layer

  • Game Logic Bricks: The logic bricks still exist! The "Python" controller is now called a Script controller. When you click it, you can write Python code. The context inside this script is special.

  • The game Object: In a script controller, you have a special game object that gives you access to engine-specific things. own = game.objects['MyObjectName'] # The owner of the script cont = game.controllers['MyControllerName'] # The controller itself


Example 1: Modern Movement Script (Blender 2.80+)

  1. Setup: Same as before. A Player cube with a camera parented to it.

  2. Logic Bricks Setup:

    • Add a Keyboard sensor (Key = W).
    • Add a Script controller.
    • Wire them: Keyboard -> Script.
  3. Python Script (in the Script controller):

    • The code is much cleaner. You don't need to import bge or bpy because the context is already set up for you.
    # This code runs inside a Script controller
    # 'own' is a special variable that refers to the object this script is attached to
    # 'game' is a special variable that provides access to game engine functions
    # Get the keyboard sensor linked to this script
    keyboard = game.sensors['Keyboard']
    # If the 'W' key is pressed
    if keyboard.positive:
        # Get the owner object
        player = game.objects['Player']
        # Apply movement in local space
        # The list is [X, Y, Z]
        player.applyMovement([0, 0, 0.2], True)
    # Note: For more complex games, you'd use a state machine or a class-based
    # approach with a single "Game Logic" script that runs every frame.

The "Best Practice" for Modern Projects: A Single Game Logic Script

For anything beyond simple interactions, the best practice is to have one main Python script that runs every frame (ALWAYS controller) and manages all the game logic. This is often called a "Game Manager" or "Game Logic" script.

Example: A Simple Game Manager

  1. Setup:

    • Create an empty object. Name it GameManager.
    • Parent your Player cube and your camera to this GameManager empty. This makes the GameManager the root of your game world.
  2. Logic Bricks Setup (on GameManager):

    • Add an Always sensor. Check True Pulse.
    • Add a Script controller.
    • Wire them: Always -> Script.
  3. Python Script (game_logic.py):

    • Create a new text block in Blender (Text -> New) and name it game_logic.py. Paste this code into it.
    import bpy
    # A dictionary to store the state of all keys
    keys_pressed = {}
    class GameLogic:
        def __init__(self):
            # Get the main game objects
            self.player = bpy.data.objects.get("Player")
            self.scene = bpy.context.scene
            if not self.player:
                print("ERROR: Player object not found!")
                return
        def update(self):
            """This function is called every frame."""
            self.handle_player_movement()
        def handle_player_movement(self):
            """Handles all player movement."""
            if not self.player: return
            speed = 0.1
            movement = [0.0, 0.0, 0.0]
            # Check for W/S keys (Forward/Backward)
            if self.is_key_pressed('W'):
                movement[2] += speed
            if self.is_key_pressed('S'):
                movement[2] -= speed
            # Check for A/D keys (Strafe Left/Right)
            if self.is_key_pressed('A'):
                movement[0] -= speed
            if self.is_key_pressed('D'):
                movement[0] += speed
            # Apply the combined movement
            if any(movement):
                self.player.applyMovement(movement, True)
        def is_key_pressed(self, key_name):
            """Checks if a key is currently pressed."""
            # This is a simple way to check. For a real game, you'd use
            # the keyboard sensor or a more robust input manager.
            # For this example, we'll simulate it.
            # A better way is to use a Keyboard sensor and read its state.
            keyboard_sensor = game.sensors.get('Keyboard')
            if keyboard_sensor:
                # The sensor has a 'key_events' list
                for event in keyboard_sensor.key_events:
                    if event.key == key_name and event.status == 'JUST_ACTIVATED':
                        keys_pressed[key_name] = True
                    if event.key == key_name and event.status == 'JUST_RELEASED':
                        keys_pressed[key_name] = False
            return keys_pressed.get(key_name, False)
    # --- Main Execution ---
    # This part runs when the script is first loaded
    try:
        game_logic_instance
    except NameError:
        # If the variable doesn't exist, create it
        game_logic_instance = GameLogic()
    # This part runs every frame
    game_logic_instance.update()
    
  4. Logic Brick Setup for Input:

    • On the GameManager object, add a Keyboard sensor.
    • In the sensor's properties, click the button to add multiple keys: W, A, S, D.
    • Link this Keyboard sensor to the Script controller.

Now, when you press P, the game_logic.py script will run every frame, check for key presses, and move the player accordingly. This structure is much more scalable and organized.

Summary: BGE vs. Modern

Feature Classic BGE (Legacy) Modern Blender Engine (2.80+)
Python Module import bge No special import needed in script controllers; import bpy for other ops.
Accessing Owner cont = bge.logic.getCurrentController()
own = cont.owner
own = game.objects['ObjectName'] (in script controller)
Sensors/Controllers Accessed via cont.sensors['Name'] Accessed via game.sensors['Name'] (in script controller)
Main Script Often one-off scripts in individual Script controllers. Best Practice: A single, central GameLogic class that runs every frame.
Future Deprecated. Current Standard. Used for games, viz, and interactivity.

If you are starting a new project, use the modern approach with Blender 2.80+ and a central Game Logic script. If you are working on an old project or trying to understand legacy tutorials, the classic BGE knowledge is still very useful.

分享:
扫描分享到社交APP
上一篇
下一篇