I found about 8 questions related to my question, but none of them solved my problem. I have a modified FirstPersonControl script attached to the typical first person setup, a.k.a. my player object. In my game I have ladders, and my player knows how to climb ladders when triggered to do so. When the player enters climb mode, I want to rotate the player around world.up so that it is facing the ladder head on. I tried all of the relevant posts that I found but none of them gave me the results that I want. I only want to rotate around world up. It’s a seemingly simple task that I just can’t get right. Quaternion.LookRotation causes unwanted tilt to my capsule, and I couldn’t get the code right to only grab the rotation around up, so I tried the below broken code. Can someone please tell me how to do this? Here’s the last incarnation of what I tried:
//--------------------------------------------------------------------------------------------------
//called from ladder script. In OnCollisionEnter this.gameObject is passed, in OnCollisionExit
//null is passed effectively detaching the ladder. Multiple ladders can be stacked to reach higher
//grounds
public void AttachLadder ( GameObject ladder )
{
m_currentRotation = 0f;
m_ladder = ladder;
if ( m_ladder )
{
++m_attachCount;
//going from one ladder to another?
if ( !m_climbMode )
{
m_animationAngle = -50f;
m_animationSpeed = -cameraTiltAnimationSpeed;
m_animateCameraTilt = true;
m_climbMode = true;
//attempt to rotate the player around the y axis (world up direction) to face the ladder headon
Vector3 wantedDir = -ladder.transform.forward;
Vector3 dir = Vector3.Project( ladder.transform.position - m_thisTransform.position, wantedDir );
dir.Normalize();
float sign = angleDirection( dir, wantedDir, Vector3.up );
float angle = Vector3.Angle( dir, wantedDir );
float camRotation = angle;
if ( sign == -1f )
{
camRotation = 360f - angle;
}
m_thisTransform.Rotate ( 0, camRotation, 0, Space.World );
m_nextDetachTime = Time.time + detachDelay;
}
}
else
{
--m_attachCount;
if ( m_attachCount == 0 )
{
m_climbMode = false;
m_animationAngle = 50f;
m_animationSpeed = cameraTiltAnimationSpeed;
m_animateCameraTilt = true;
}
}
}
//--------------------------------------------------------------------------------------------------
float angleDirection ( Vector3 fwd, Vector3 targetDir, Vector3 up )
{
Vector3 perp = Vector3.Cross ( fwd, targetDir );
float dir = Vector3.Dot ( perp, up );
if ( dir > 0f )
{
return 1f;
}
else if ( dir < 0f )
{
return -1f;
}
else
{
return 0f;
}
}
Thanks.