Как мне плавно поворачивать 3D-камеру Unity вокруг объекта на заданном расстоянии, чтобы смотреть на объект в направлениC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Как мне плавно поворачивать 3D-камеру Unity вокруг объекта на заданном расстоянии, чтобы смотреть на объект в направлени

Сообщение Anonymous »

Я знаком с Cinemachine, но не нашел ничего, что могло бы выполнить то, что я пытаюсь сделать. Я работаю над автомобильной игрой, хотя конкретная концепция игры не имеет отношения к проблеме. Прямо сейчас я создаю основу для плавного поворота камеры вокруг игрока в зависимости от горизонтальной скорости автомобиля (игнорируя любую скорость по оси Y). Например, если автомобиль движется вперед, а камера еще не расположена позади него на указанном расстоянии, камера должна плавно поворачиваться по кратчайшему пути, чтобы достичь этого положения.
I исправили функцию для получения правильного положения трансформации относительно автомобиля, за которым она следует
вот новая функция:
public Vector3 GetFollowOffsetPosition(Vector3 followerPosition, Vector3 followObjectPosition, Vector3 followObjectVelocity, float followDistance)
{
// If the followed object is stationary, just return the current position (no offset).
Vector3 noYVelocity = new Vector3(followObjectVelocity.x, 0f, followObjectVelocity.z);
if (noYVelocity.magnitude < minSpeedThreshold)
{
return defaultCamPosition; // No significant velocity, return current follower position.
}

// Get the direction of the followed object's velocity (ignoring y component for horizontal following).
Vector3 velocityDirection = noYVelocity.normalized;

// Calculate the offset position: followObject's position minus the offset along the velocity direction.
Vector3 offsetPosition = new Vector3(-Mathf.Sign(velocityDirection.z) * velocityDirection.x, 0f, velocityDirection.z) * followDistance;

offsetPosition.y = defaultCamPosition.y;

// Return the calculated offset position.
return offsetPosition;
}

Камера теперь не поворачивается плавно вокруг автомобиля, она просто сильно дергается. Get Follow Angle получает разницу углов между целевой позицией и текущей позицией следящего объекта. Предполагается, что функция поворота будет использовать это для поворота из текущего положения в целевое. но он очень нервничает и не поддерживает расстояние, заданное целевой позицией, он просто плавно поворачивается вокруг автомобиля от текущего положения к целевому по эллиптической траектории.
частная поворотная камера Vector3(Vector3 currentPos, Vector3 targetPosition, float RotationAngle, float SemiMajorAxis, float SemiMinorAxis)
{
//Vector3 Direction = new Vector3(currentPos.x - targetPosition.x, 0f, Mathf.Abs (currentPos.z) - Mathf.Abs(targetPosition.z));
Направление Vector3 = new Vector3(currentPos.x - targetPosition.x, 0f, currentPos.z - targetPosition.z);
if (direction.magnitude < Mathf.Epsilon)
{
Debug.LogError("Direction vector is too small, cannot normalize!");
return currentPos; // Return the current position if there's no valid direction
}

// Normalize the direction (unit length)
direction = direction.normalized;

// Ensure the sign of the original direction is maintained while scaling
direction.x *= semiMinorAxis; // Use the absolute value of the semiMinorAxis (side-to-side)
direction.z *= semiMajorAxis; // Use the absolute value of the semiMajorAxis (forward-backward)

Debug.Log(direction.z);

Quaternion rotation = Quaternion.Euler(0, rotationAngle, 0); // Rotate by the specified angle around Y-axis
Vector3 rotatedDirection = rotation * direction;

// Step 5: Calculate the new camera position by adding the rotated direction to the target position
Vector3 newPosition = targetPosition + rotatedDirection;

// Step 6: Return the new position of the camera
return newPosition;
}

private float GetSwivelAngleDifference(Vector3 currentSwivelPos, Vector3 targetSwivelPos, Vector3 followObjectPos)
{
Vector3 currentSwivelVector = currentSwivelPos - followObjectPos;
Vector3 targetSwivelVector = targetSwivelPos - followObjectPos;

currentSwivelVector.y = 0;
targetSwivelVector.y = 0;

if (currentSwivelVector.magnitude < Mathf.Epsilon || targetSwivelVector.magnitude < Mathf.Epsilon)
{
Debug.LogError("Swivel vectors are too small to normalize.");
return 0f;
}

currentSwivelVector.Normalize();
targetSwivelVector.Normalize();

// Standard dot product calculation (no need for z-axis check).
float dotProduct = Vector3.Dot(currentSwivelVector, targetSwivelVector);

dotProduct = Mathf.Clamp(dotProduct, -1f, 1f);

float angle = Mathf.Acos(dotProduct) * Mathf.Rad2Deg;

// Cross product to determine the sign of the angle.
Vector3 crossProduct = Vector3.Cross(currentSwivelVector, targetSwivelVector);
if (crossProduct.y < 0)
{
angle = -angle;
}

return angle;
}


Подробнее здесь: https://stackoverflow.com/questions/790 ... ven-distan
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»