Search code examples
pythonloopscameraparentblender

Is it possible to parent to only one or two axes in Blender?


I'm in the process of creating a 2d platformer using the Blender Game Engine. I'm having trouble getting the camera to follow my character and keep him in the center of the screen. Initially, I tried simply parenting the camera to my character, but whenever my character turns (rotates around the Z-axis 180 degrees), so does my camera, making it face the back of the level. So, I was wondering if there was a way to "parent" only one or two axes of an object to another, or restrain an axes from moving even if it is parented. This way I could keep the camera from rotating, but still have it follow on the Y and Z axes. One thing I looked into was using Python code. I came up with...

import bpy
char = bpy.data.objects['HitBox']
obj = bpy.data.objects['Camera']
obj.location.x = 69.38762 # this is the set distance from the character to camera
obj.location.y = char.location.y
obj.location.z = char.location.z
bpy.data.scenes[0].update()

I realize I need a loop for this after assigning the 'char' variable, but I can't get any Python loops working that would run through the entire game, as 'while' loops crash the BGE. If you could help with either the parenting issue, or the Python code, I'd really appreciate it.


Solution

  • you just need to use the bge module, because it is for the game engine. So your problem is: you used blender python, but not bge python. Try to reach the camera with cam = bge.logic.getCurrentScene().active_camera. ... so this should work:

    import bge
    
    def main():
        cam = bge.logic.getCurrentScene().active_camera
        obj = bge.logic.getCurrentController().owner
        obj.worldPosition.y = cam.worldPosition.y
        obj.worldPosition.z = cam.worldPosition.z
    
    main()
    

    (Attach this script to your 'HitBox' with a true triggered always sensor so it can cycle forever.)

    Other solution: You can try to make vertex parent to your player.