- Home /
Question by
SoMir1 · Aug 30, 2020 at 02:43 PM ·
movementfps controllerdiagonalheadbob
Head bobbing is faster diagonally
I am making a game for a game jam and I'm writing my own FPS controller, however, the movement was faster diagonally because I am using Horizontal and Vertical axis. I fixed it using Vector3.ClampMagnitude, but my head bobbing script on the camera still bobbs faster when I move diagonally. How can I fix this? Here is my script:
private float timer = 0.0f;
public float bobbingSpeed = 0.18f;
public float bobbingAmount = 0.2f;
public float midpoint = 2.0f;
private bool bPos = true;
public AudioSource audioSource;
public AudioClip[] stepSounds;
public PlayerMovement playerMovement;
void Start()
{
if(playerMovement == null)
playerMovement = transform.parent.GetComponent<PlayerMovement>();
if(audioSource == null)
audioSource = GetComponent<AudioSource>();
}
void Update ()
{
if(playerMovement.isGrounded == false)
return;
float waveslice = 0.0f;
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
float bobbingFactor = horizontal * horizontal + vertical * vertical;
if(Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0)
{
timer = 0.0f;
}
else
{
waveslice = Mathf.Sin(timer);
float footfall = Mathf.Cos(timer);
if(footfall < 0 && bPos)
{
audioSource.clip = stepSounds[Random.Range(0, stepSounds.Length)];
audioSource.Play();
}
bPos = footfall >= 0;
timer = timer + bobbingSpeed * bobbingFactor * Time.deltaTime;
if (timer > Mathf.PI * 2)
{
timer = timer - (Mathf.PI * 2);
}
}
if(waveslice != 0)
{
float translateChange = waveslice * bobbingAmount;
float totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
totalAxes = Mathf.Clamp(totalAxes, 0.0f, 1.0f);
translateChange = totalAxes * translateChange;
Vector3 temp = Vector3.zero;
temp.y = transform.localPosition.y;
temp.y = midpoint + translateChange;
transform.localPosition = temp;
}
else
{
Vector3 temp = Vector3.zero;
temp.y = transform.localPosition.y;
temp.y = midpoint;
transform.localPosition = temp;
}
}
Comment