#unity3d #atan2
#unity3d #atan2
Вопрос:
Я создаю контроллер персонажа от третьего лица в unity, у меня есть игрок, движущийся с направлением и анимацией. Мой вопрос: как мне сделать вращение движения относительно вращения камеры
ПРИМЕЧАНИЕ: я не использую transform.translate или любой подобный метод для перемещения игрока, я вычисляю вращение, используя входные векторы и atan2, затем перемещаю игрока с помощью анимации. Поэтому я не могу просто изменить направление x и направление y, я могу изменить только поворот y
мой текущий код просмотра плеера
Vector3 CalculateRotation(float H, float V)
{
IsTurning = IsMoving(H, V);
if (IsTurning) {
angle = Mathf.RoundToInt(Mathf.Atan2(V, -H) * Mathf.Rad2Deg);
IsTurned = false;
ani.SetBool("isWalking", true);
return new Vector3(0, Mathf.RoundToInt(angle), 0);
}
else
{
ani.SetBool("isWalking", false);
}
return new Vector3(0, Mathf.RoundToInt(CurrentRotation.y), 0);
}
void LookTorwards(Vector3 T_Angle)
{
NewRotation = T_Angle - CurrentRotation;
NewRotation.y = Mathf.Repeat(NewRotation.y 180f, 360f) - 180f;
if (NewRotation.y == 180)
{
NewRotation.y -= 1;
}
if (TargetRotation.y == CurrentRotation.y)
{
IsTurned = true;
return;
}
if (NewRotation.y > 0)
{
transform.Rotate(new Vector3(0, RotationSpeed, 0));
CurrentRotation.y = RotationSpeed;
}
else if (NewRotation.y < 0)
{
transform.Rotate(new Vector3(0, -RotationSpeed, 0));
CurrentRotation.y -= RotationSpeed;
}
}
Ответ №1:
В настоящее время у меня нет времени тестировать Unity, поэтому я даю вам некоторый псевдокод, который поможет вам решить вашу проблему
// Get the direction of where the player should ahead in world space
Vector3 hMoveDir = cameraTransform.right * movementHorizontal;;
Vector3 vMoveDir= cameraTransform.forward * movementVertical;
Vector3 moveDir = hMoveDir vMoveDir;
// Create the rotation we need according to moveDir
lookRotation = Quaternion.LookRotation(moveDir);
// Rotate player over time according to speed until we are in the required rotation
playerTransform.rotation = Quaternion.Slerp(playerTransform.rotation, lookRotation , Time.deltaTime * RotationSpeed);