Skip to content

Instantly share code, notes, and snippets.

@nbrew
Created May 8, 2014 21:45
Show Gist options
  • Select an option

  • Save nbrew/52df13e93e3170f73080 to your computer and use it in GitHub Desktop.

Select an option

Save nbrew/52df13e93e3170f73080 to your computer and use it in GitHub Desktop.
Unity Headbobber.js to C#
using UnityEngine;
using System.Collections;
public class Headbobber : MonoBehaviour {
private float timer = 0.0f;
public float bobbingSpeed = 0.18f;
public float bobbingAmount = 0.2f;
public float midpoint = 2.0f;
void Update () {
float waveslice = 0.0f;
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
if (Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0) {
timer = 0.0f;
} else {
waveslice = Mathf.Sin(timer);
timer = timer + bobbingSpeed;
if (timer > Mathf.PI * 2) {
timer = timer - (Mathf.PI * 2);
}
}
Vector3 v3T = transform.localPosition;
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;
v3T.y = midpoint + translateChange;
} else {
v3T.y = midpoint;
}
transform.localPosition = v3T;
}
}
@abulat189
Copy link
Copy Markdown

abulat189 commented Oct 11, 2020

nice
it helped me a lot tysm

@veksha
Copy link
Copy Markdown

veksha commented Oct 2, 2025

helped me. thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment