Unity3d 使玩家看到相对于摄影机的方向
我正在unity中制作一个第三人称角色控制器,我让玩家以一个方向和一个动画移动。我的问题是:如何使运动旋转相对于摄影机旋转 注: 我不是使用transform.translate或任何类似的方法来移动播放器,而是使用输入向量和atan2计算旋转,然后使用动画移动播放器。所以我不能只改变x方向和y方向,我只能改变y旋转 我当前的播放器外观代码Unity3d 使玩家看到相对于摄影机的方向,unity3d,atan2,Unity3d,Atan2,我正在unity中制作一个第三人称角色控制器,我让玩家以一个方向和一个动画移动。我的问题是:如何使运动旋转相对于摄影机旋转 注: 我不是使用transform.translate或任何类似的方法来移动播放器,而是使用输入向量和atan2计算旋转,然后使用动画移动播放器。所以我不能只改变x方向和y方向,我只能改变y旋转 我当前的播放器外观代码 Vector3 CalculateRotation(float H, float V) { IsTurning = IsMoving
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;
}
}
Vector3计算器操作(浮点H,浮点V)
{
IsTurning=IsMoving(H,V);
如果(正在旋转){
角度=Mathf.RoundToInt(Mathf.Atan2(V,-H)*Mathf.Rad2Deg);
IsTurned=false;
ani.SetBool(“isWalking”,真);
返回新矢量3(0,数学圆整(角度),0);
}
其他的
{
ani.SetBool(“isWalking”,假);
}
返回新矢量3(0,数学圆整输入(CurrentRotation.y),0);
}
向上看空(矢量3 T_角)
{
新旋转=T_角度-当前旋转;
NewRotation.y=Mathf.Repeat(NewRotation.y+180f,360f)-180f;
if(NewRotation.y==180)
{
NewRotation.y-=1;
}
if(TargetRotation.y==CurrentRotation.y)
{
IsTurned=true;
回来
}
如果(NewRotation.y>0)
{
旋转(新矢量3(0,旋转速度,0));
CurrentRotation.y+=旋转速度;
}
else if(NewRotation.y<0)
{
旋转(新矢量3(0,-旋转速度,0));
CurrentRotation.y-=旋转速度;
}
}
我目前没有时间测试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);