i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want.
This is the camera rotation i want:
![alt text][1]
This is rotation of character my script is attached to:
![alt text][2]
And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternion LOL!
this is the script:
public class ScreenCharacterController : MonoBehaviour
{
#region Fields
private Camera mainCamera;
private CharacterController character;
private int leftFingerID = -1;
private int rightFingerID = -1;
private Vector2 leftFingerInput;
private Vector2 rightFingerInput;
private float xAxisRotation;
private float yAxisRotation;
[SerializeField] private float minXRotation;
[SerializeField] private float maxXRotation;
[SerializeField] private float minYRotation = -25f;
[SerializeField] private float maxYRotation = 25f;
[SerializeField] private float cameraRotationSpeed = 20f;
#endregion
#region Unity Methods
void Start()
{
mainCamera = Camera.main;
}
void Update()
{
//for touch
TouchInput();
//for calculating rotation vaues
CalculateAndClampRotation();
RotateCamera();
}
#endregion
#region Private Methods
void TouchInput()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
//Left Touch
if (touch.position.x < Screen.width / 2)
{
leftFingerID = touch.fingerId;
}
//Right touch
else
{
rightFingerID = touch.fingerId;
}
}
else if (touch.phase == TouchPhase.Moved)
{
//Left Touch
if (touch.position.x < Screen.width / 2)
{
if (leftFingerID == touch.fingerId)
{
}
}
//Right touch
else
{
if (rightFingerID == touch.fingerId)
{
rightFingerInput = touch.deltaPosition * Time.smoothDeltaTime;
}
}
}
else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
if (touch.fingerId == leftFingerID)
{
leftFingerID = -1;
}
else if (touch.fingerId == rightFingerID)
{
rightFingerID = -1;
rightFingerInput = new Vector2(0, 0);
}
}
}
}
void RotateCamera()
{
Quaternion currentRotation = mainCamera.transform.localRotation;
Quaternion targetRotation = Quaternion.identity;
targetRotation = Quaternion.Euler((mainCamera.transform.localRotation.x - yAxisRotation),
-(mainCamera.transform.localRotation.y - xAxisRotation), 0f);
mainCamera.transform.localRotation = Quaternion.Slerp(currentRotation, targetRotation, 0.5f);
}
void CalculateAndClampRotation()
{
xAxisRotation += rightFingerInput.x * cameraRotationSpeed;
yAxisRotation += rightFingerInput.y * cameraRotationSpeed;
xAxisRotation = Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation);
yAxisRotation = Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation);
}
#endregion
}
[1]: /storage/temp/146908-screenshot-78.png
[2]: /storage/temp/146909-screenshot-79.png
↧