- Home /
How to make a gun bob
How to I make it so my gun bobs up and down as i move around?
Don't put the below code in Update put it in FixedUpdate, else you can get unexpected speed variations.
Answer by unluckyBastard · Aug 23, 2011 at 05:52 PM
#pragma strict
private var timer : float = 0.0;
public var bobbingSpeed : float = 0.18;
public var bobbingAmount : float = 0.2;
public var midpoint : float = 2.0;
private var waveslice : float;
private var horizontal : float;
private var vertical : float;
private var totalAxes : float;
private var translateChange : float;
function Update () {
waveslice = 0.0;
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
if (Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0) {
timer = 0.0;
}
else {
waveslice = Mathf.Sin(timer);
timer = timer + bobbingSpeed;
if (timer > Mathf.PI * 2) {
timer = timer - (Mathf.PI * 2);
}
}
if (waveslice != 0) {
translateChange = waveslice * bobbingAmount;
totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
totalAxes = Mathf.Clamp (totalAxes, 0.0, 1.0);
translateChange = totalAxes * translateChange;
transform.localPosition.y = midpoint + translateChange;
}
else {
transform.localPosition.y = midpoint;
}
}
unify wikis HeadBobber script can be used
Don't put the code in Update put it in FixedUpdate, else you can get unexpected speed variations.
https://www.youtube.com/user/elitegames2 He is talking scripts and clai$$anonymous$$g there his. He used it in a "tutorial" and said it was his.
I have attached the script to my weapon (It's a group of 2 objects {I think it's called a parent?}), but now it just dissapears. Any Ideas why? I have also attached the script to the 2 childs individually.
For those who would rather a c# solution here's a working conversion: http://answers.unity3d.com/questions/283086/headbobber-script-in-c.html
@Planet$$anonymous$$aner if your weapon 'disappears' it's probably because its position is off camera, i.e. the midpoint variable is too large. $$anonymous$$ake this and the bobbingSpeed and bobbingAmount variables public and you can tweaks things during runtime. With my model I found that the midpoint offset could stay at zero.
Your answer
![](https://koobas.hobune.stream/wayback/20220612190532im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Help with Lerp 0 Answers
Gun not smoothly following player,How to make gun smoothly follow player 1 Answer
Making A Gun "Bob" While Moving 1 Answer
Sample Assets FP bobbing 0 Answers
Smooth gun movement? 0 Answers