2013-04-18 2 views
1

Я собрал собственный сценарий логики сверху вниз, основанный на сценарии Unity3D ThirdPersonCamera.js. Кажется, что все работает правильно, камера следует за целевым игроком на плоскости XZ и даже движется по оси Y, когда это необходимо, когда игрок прыгает.Unity3D - Top Down Camera Logic получает блокировку при использовании Transform.LookAt

Только камера не смотрит на плеер. Поэтому я попытался использовать Transform.LookAt() на cameraTransform, чтобы камера смотрела прямо на плеер. Это приводит к тому, что камера правильно смотрит прямо на плеер, но затем движение через WASD больше не работает. Игрок просто сидит там. Использование пробела для прыжков все еще работает.

Это не имеет для меня смысла, как должна быть направлена ​​ориентация преобразования камеры на движение объекта игрока?

Код для моего сценария ниже:

// The transform of the camera that we're manipulating 
var cameraTransform : Transform; 

// The postion that the camera is currently focused on 
var focusPosition = Vector3.zero; 

// The idle height we are aiming to be above the target when the target isn't moving 
var idleHeight = 7.0; 

// How long should it take the camera to focus on the target on the XZ plane 
var xzSmoothLag = 0.3; 

// How long should it take the camera to focus on the target vertically 
var heightSmoothLag = 0.3; 


private var _target : Transform; 
private var _controller : ThirdPersonController; 

private var _centerOffset = Vector3.zero; 
private var _headOffset = Vector3.zero; 
private var _footOffset = Vector3.zero; 

private var _xzVelocity = 0.0; 
private var _yVelocity = 0.0; 
private var _cameraHeightVelocity = 0.0; 


// ===== UTILITY FUNCTIONS ===== 

// Apply the camera logic to the camera with respect for the target 
function process() 
{ 
    // Early out if we don't have a target 
    if (!_controller) 
     return; 

    var targetCenter = _target.position + _centerOffset; 
    var targetHead = _target.position + _headOffset; 
    var targetFoot = _target.position + _footOffset; 

    // Determine the XZ offset of the focus position from the target foot 
    var xzOffset = Vector2(focusPosition.x, focusPosition.z) - Vector2(targetFoot.x, targetFoot.z); 

    // Determine the distance of the XZ offset 
    var xzDistance = xzOffset.magnitude; 

    // Determine the Y distance of the focus position from the target foot 
    var yDistance = focusPosition.y - targetFoot.y; 

    // Damp the XZ distance 
    xzDistance = Mathf.SmoothDamp(xzDistance, 0.0, _xzVelocity, xzSmoothLag); 

    // Damp the XZ offset 
    xzOffset *= xzDistance; 

    // Damp the Y distance 
    yDistance = Mathf.SmoothDamp(yDistance, 0.0, _yVelocity, heightSmoothLag); 

    // Reposition the focus position by the dampened distances 
    focusPosition.x = targetFoot.x + xzOffset.x; 
    focusPosition.y = targetFoot.y + yDistance; 
    focusPosition.z = targetFoot.z + xzOffset.y; 

    var minCameraHeight = targetHead.y; 
    var targetCameraHeight = minCameraHeight + idleHeight; 

    // Determine the current camera height with respect to the minimum camera height 
    var currentCameraHeight = Mathf.Max(cameraTransform.position.y, minCameraHeight); 

    // Damp the camera height 
    currentCameraHeight = Mathf.SmoothDamp(currentCameraHeight, targetCameraHeight, _cameraHeightVelocity, heightSmoothLag); 

    // Position the camera over the focus position 
    cameraTransform.position = focusPosition; 
    cameraTransform.position.y = currentCameraHeight; 

// PROBLEM CODE - BEGIN 

    // Have the camera look at the focus position 
    cameraTransform.LookAt(focusPosition, Vector3.forward); 

// PROBLEM CODE - END 

    Debug.Log("Camera Focus Position: " + focusPosition); 
    Debug.Log("Camera Transform Position: " + cameraTransform.position); 
} 

// ===== END UTILITY FUNCTIONS ===== 


// ===== UNITY FUNCTIONS ===== 

// Initialize the script 
function Awake() 
{ 
    // If the camera transform is unassigned and we have a main camera, 
    // set the camera transform to the main camera's transform 
    if (!cameraTransform && Camera.main) 
     cameraTransform = Camera.main.transform; 

    // If we don't have a camera transform, report an error 
    if (!cameraTransform) 
    { 
     Debug.Log("Please assign a camera to the TopDownThirdPersonCamera script."); 
     enabled = false;  
    } 

    // Set the target to the game object transform 
    _target = transform; 

    // If we have a target set the controller to the target's third person controller 
    if (_target) 
    { 
     _controller = _target.GetComponent(ThirdPersonController); 
    } 

    // If we have a controller, calculate the center offset and head offset 
    if (_controller) 
    { 
     var characterController : CharacterController = _target.collider; 
     _centerOffset = characterController.bounds.center - _target.position; 
     _headOffset = _centerOffset; 
     _headOffset.y = characterController.bounds.max.y - _target.position.y; 
     _footOffset = _centerOffset; 
     _footOffset.y = characterController.bounds.min.y - _target.position.y; 
    } 
    // If we don't have a controller, report an error 
    else 
     Debug.Log("Please assign a target to the camera that has a ThirdPersonController script attached."); 

    // Apply the camera logic to the camera 
    process(); 
} 

function LateUpdate() 
{ 
    // Apply the camera logic to the camera 
    process(); 
} 

// ===== END UNITY FUNCTIONS ===== 

Я пометил раздел кода проблемы с проблемных кодом комментариев. Если код проблемы удален, он позволяет WASD-движению снова работать, но затем камера больше не смотрит на цель.

Любое понимание этой проблемы очень ценится.

ответ

1

Я понял, проблема была в скрипте ThirdPersonController.js, который я использовал. В функции UpdateSmoothedMovementDirection(), ThirdPersonController использует cameraTransform для определения направления вперед вдоль плоскости XZ в зависимости от того, на что смотрит камера. При этом он нулирует ось Y и нормализует то, что осталось.

Вызов камерыTransform.LookAt(), выполняемый в моем пользовательском скрипте TopDownCamera.js, имеет камеру, смотрящую прямо вниз по оси Y. Поэтому, когда ThirdPersonController захватывает его и возвращает нуль по оси Y, я заканчиваю нулевым направлением вперед, что приводит к тому, что движение XZ не идет никуда.

Копирование ThirdPersonController.js и изменять код так, чтобы:

var forward = cameraTransform.TransformDirection(Vector3.forward); 
forward.y = 0; 
forward = forward.normalized; 

становится:

forward = Vector3.forward; 

зафиксировал проблему.

Смежные вопросы