LibGDX Moving a Rotated Camera

前端 未结 1 895
刺人心
刺人心 2021-01-13 20:21

I\'ve come to a situation in my application, built using LibGDX, where I need the camera to be able to rotate, and also be moveable by the user, as well as being able to be

1条回答
  •  逝去的感伤
    2021-01-13 21:09

    I was dealing with similar problem today when I was programming orbit camera. I will try to describe you how I dealt with this issue.

    I wanted my orbit camera to be able to rotate around X and Y axis in the same time, but it was not working. I was able to rotate around this axes only respectively.

    The trick for me was:

    Vector3 target = Vector3.zero
    Vector3 right = new Vector().set(camera.direction).crs(camera.up).nor();
    
    // This angles usualy comes from touchDragged event in your input processor
    // class implementing the InputProcessor, where you do your calculations
    deltaAngleX = 1.1f;
    deltaAngleY = 1.9f;
    
    // Rotate around X axis
    camera.rotateAround(target, right, deltaAngleX);
    
    // Rotate around Y
    camera.updateRotation(Vector3.Y, deltaAngleY);
    

    When you are rotating around Y axis everything is fine because Y axis does not change depending on your X rotation. You always want to rotate around the world Y axis, not any local one.

    But when you are rotating around X you can not use Vector3.X because this axis will not be relative to your camera position and direction. So we need to calculate "local Y" axis of your camera. To do that we need to know what Cross product of two vectors is. Please see Cross product on wiki and crs() on libgdx class reference

    Following code fragment will return new Vector3, which will be pointing to the right axis relative to the current camera. Note the nor() call is present because we want to normalize that vector.

    Long story short:

    Vector3 right = new Vector().set(direction).crs(up).nor();
    

    Crs creates cross product vector from two vectors (in our case camera.direction and camera.up).

    I don't understand why in Vector3 the right member variable is not exposed or why right vector calculation method is not present, but this will do the trick anyway

    With few code edits you can move your player, camera or anything in the world around the axis you need. You just need to understand the basic Vector operations so I recommend you going trough them

    Last note:

    You must rotate around X axis first because rotating around Y changes your local X axis which will need to be recalculated (the right vector).

    0 讨论(0)
提交回复
热议问题