I want to add a visual headbob to my script for when my character jumps in game. Make…
- User
I want to add a visual headbob to my script for when my character jumps in game. Make sure that there is no camera snapping by resetting positions instantly and so on. private void HandleJump() { if (shouldJump && !isCrouching && currentStamina >= jumpStaminaLoss) { int layerMask = (-1) - (1 << LayerMask.NameToLayer("Player")); if (Physics.Raycast(playerCamera.transform.position, Vector3.down, out RaycastHit hit, 3, layerMask)) { switch (hit.collider.tag) { case "Footsteps/GRASS": jumpAudioSource.PlayOneShot(grassJumpClips[UnityEngine.Random.Range(0, grassJumpClips.Length - 1)]); break; case "Footsteps/WOOD": jumpAudioSource.PlayOneShot(woodJumpClips[UnityEngine.Random.Range(0, woodJumpClips.Length - 1)]); break; case "Footsteps/METAL": jumpAudioSource.PlayOneShot(metalJumpClips[UnityEngine.Random.Range(0, metalJumpClips.Length - 1)]); break; case "Footsteps/GRAVEL": jumpAudioSource.PlayOneShot(gravelJumpClips[UnityEngine.Random.Range(0, gravelJumpClips.Length - 1)]); break; case "Footsteps/CONCRETE": jumpAudioSource.PlayOneShot(concreteJumpClips[UnityEngine.Random.Range(0, concreteJumpClips.Length - 1)]); break; default: jumpAudioSource.PlayOneShot(concreteJumpClips[UnityEngine.Random.Range(0, concreteJumpClips.Length - 1)]); break; } } moveDirection.y = jumpForce; } HandleLanding(); }
- Assistant
To implement a visual headbob when the character jumps, you can create a coroutine that adjusts the camera's position based on a curve. Here's how you can modify your script to include the headbob and properly handle jumping and landing without snapping:
private void HandleJump() { if (shouldJump && !isCrouching && currentStamina >= jumpStaminaLoss) { int layerMask = (-1) - (1 << LayerMask.NameToLayer("Player")); if (Physics.Raycast(playerCamera.transform.position, Vector3.down, out RaycastHit hit, 3, layerMask)) { // Existing code for playing footstep sounds moveDirection.y = jumpForce; // Start the headbob coroutine for jumping StartCoroutine(JumpHeadBob()); } } HandleLanding(); } private IEnumerator JumpHeadBob() { float headBobDuration = 0.5f; // Adjust this value for desired headbob duration float timeElapsed = 0; Vector3 initialCameraPosition = playerCamera.transform.localPosition; while (timeElapsed < headBobDuration) { float yOffset = Mathf.Sin(timeElapsed / headBobDuration * Mathf.PI) * 0.1f; // 0.1f is the amplitude, adjust it for desired headbob height playerCamera.transform.localPosition = new Vector3(initialCameraPosition.x, initialCameraPosition.y + yOffset, initialCameraPosition.z); timeElapsed += Time.deltaTime; yield return null; } playerCamera.transform.localPosition = initialCameraPosition; } private void HandleLanding() { // Existing landing logic }This code adds a coroutine called
JumpHeadBobthat moves the camera up and down using a sine curve during the jump. This smooth motion will create a natural headbob effect without any sudden snapping. Feel free to adjust the duration and amplitude values to achieve the desired headbobbing effect. - User
Can you add rotation to that script that would mimic the real life rotation of head mid jump?
- Assistant
Certainly! You can add the head rotation to the
JumpHeadBobcoroutine to mimic the real-life rotation of the head during the jump. Here's the modifiedJumpHeadBobcoroutine with rotation added:private IEnumerator JumpHeadBob() { float headBobDuration = 0.5f; // Adjust this value for desired headbob duration float timeElapsed = 0; Vector3 initialCameraPosition = playerCamera.transform.localPosition; Quaternion initialCameraRotation = playerCamera.transform.localRotation; while (timeElapsed < headBobDuration) { float yOffset = Mathf.Sin(timeElapsed / headBobDuration * Mathf.PI) * 0.1f; // 0.1f is the amplitude, adjust it for desired headbob height playerCamera.transform.localPosition = new Vector3(initialCameraPosition.x, initialCameraPosition.y + yOffset, initialCameraPosition.z); float zRotation = Mathf.Sin(timeElapsed / headBobDuration * Mathf.PI * 2) * 3; // 3 is the amplitude, adjust it for desired head rotation playerCamera.transform.localRotation = initialCameraRotation * Quaternion.Euler(0, 0, zRotation); timeElapsed += Time.deltaTime; yield return null; } playerCamera.transform.localPosition = initialCameraPosition; playerCamera.transform.localRotation = initialCameraRotation; }This code adds head rotation to the
JumpHeadBobusing a sine function, making it smoothly rotate around the Z axis. You can adjust the rotation amplitude to achieve the desired effect.Remember that you need to update the
HandleJumpmethod to includeStartCoroutine(JumpHeadBob());in order to start the headbob effect. - User
Okay the script is PERFECT. Keep it the way it is. However, One issue is that I can't look up and down mid jump, only left and right.
- Assistant
To allow free camera movement on the X (vertical) axis while maintaining the headbob effect, you can modify the script to update only the Y and Z rotation. The rotation for looking up and down should come from another part of your script where you handle the input from the mouse. I assume you are updating the rotation with your mouse input elsewhere in your code.
Here's the modified JumpHeadBob coroutine that allows you to look up and down during the jump:
private IEnumerator JumpHeadBob() { float headBobDuration = 0.5f; // Adjust this value for desired headbob duration float timeElapsed = 0; Vector3 initialCameraPosition = playerCamera.transform.localPosition; while (timeElapsed < headBobDuration) { float yOffset = Mathf.Sin(timeElapsed / headBobDuration * Mathf.PI) * 0.1f; // 0.1f is the amplitude, adjust it for desired headbob height playerCamera.transform.localPosition = new Vector3(initialCameraPosition.x, initialCameraPosition.y + yOffset, initialCameraPosition.z); float zRotation = Mathf.Sin(timeElapsed / headBobDuration * Mathf.PI * 2) * 3; // 3 is the amplitude, adjust it for desired head rotation // Get the current X rotation of the camera. float xRotation = playerCamera.transform.localRotation.eulerAngles.x; // Apply the updated rotation. playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0, zRotation); timeElapsed += Time.deltaTime; yield return null; } playerCamera.transform.localPosition = initialCameraPosition; }This code retrieves the current X axis rotation of the camera and only updates the Z axis rotation for headbob, allowing you to maintain control over the vertical look angle during the jump.
- User
Perfect, Now can you make headBobDuration, the amplitude for headbob height and the the amplitude for head rotation separate variables that I can edit in the inspector.
- Assistant
Sure! You can define them as SerializedFields to make them editable from the Inspector in Unity. Here's the modified script:
[Header("Headbob Settings")] [SerializeField] private float headBobDuration = 0.5f; [SerializeField] private float headBobHeightAmplitude = 0.1f; [SerializeField] private float headBobRotationAmplitude = 3f; private IEnumerator JumpHeadBob() { float timeElapsed = 0; Vector3 initialCameraPosition = playerCamera.transform.localPosition; while (timeElapsed < headBobDuration) { float yOffset = Mathf.Sin(timeElapsed / headBobDuration * Mathf.PI) * headBobHeightAmplitude; playerCamera.transform.localPosition = new Vector3(initialCameraPosition.x, initialCameraPosition.y + yOffset, initialCameraPosition.z); float zRotation = Mathf.Sin(timeElapsed / headBobDuration * Mathf.PI * 2) * headBobRotationAmplitude; // Get the current X rotation of the camera. float xRotation = playerCamera.transform.localRotation.eulerAngles.x; // Apply the updated rotation. playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0, zRotation); timeElapsed += Time.deltaTime; yield return null; } playerCamera.transform.localPosition = initialCameraPosition; }Now, the
headBobDuration,headBobHeightAmplitude, andheadBobRotationAmplitudevariables can be edited directly from the Inspector in Unity. - User
Is there a way to make the headers more organised in the inspector, maybe make them collapsible if possible? I have a few headers.
- Assistant
Unfortunately, Unity doesn't support collapsible headers out of the box. However, you can achieve collapsible sections by using custom Editor scripting. We can create a custom editor script to organize your headers and make them collapsible.
Here's an example of how to create a custom editor script for your MonoBehaviour:
- First, create a new C# script named "MyMonobehaviourEditor" and put the following code inside it:
using UnityEngine; using UnityEditor; [CustomEditor(typeof(MyMonobehaviour))] public class MyMonobehaviourEditor : Editor { private bool showHeadbobSettings = true; public override void OnInspectorGUI() { MyMonobehaviour myScript = (MyMonobehaviour)target; // Draw default inspector properties. DrawDefaultInspector(); // Add collapsible Headbob Settings header. showHeadbobSettings = EditorGUILayout.Foldout(showHeadbobSettings, "Headbob Settings"); if (showHeadbobSettings) { EditorGUI.indentLevel++; myScript.headBobDuration = EditorGUILayout.FloatField("Headbob Duration", myScript.headBobDuration); myScript.headBobHeightAmplitude = EditorGUILayout.FloatField("Headbob Height Amplitude", myScript.headBobHeightAmplitude); myScript.headBobRotationAmplitude = EditorGUILayout.FloatField("Headbob Rotation Amplitude", myScript.headBobRotationAmplitude); EditorGUI.indentLevel--; } } }Make sure to replace "MyMonobehaviour" with the name of the script that contains your headbob variables.
- In your original MonoBehaviour script, remove the
[Header("Headbob Settings")]line and make the variablespublicinstead of[SerializeField].
public float headBobDuration = 0.5f; public float headBobHeightAmplitude = 0.1f; public float headBobRotationAmplitude = 3f;Now, the "Headbob Settings" header will be collapsible in the Inspector.
You can apply the same concept to create more collapsible headers. Add more variables and sections as needed inside
OnInspectorGUI()and useEditorGUILayout.Foldout()for collapsible headers. Make sure to update variable accessors in the MonoBehaviour script accordingly. - User
Okay but is there a way to make it more modular so I can do it to all of my headers on the fly?
- Assistant
To make it more modular and reusable, you can create a separate static class for custom Editor utilities. This class will contain a generic method to handle collapsible headers for any script.
- Create a new C# script called "EditorUtilities" and place the following code inside it:
using UnityEngine; using UnityEditor; public static class EditorUtilities { public static bool DrawCollapsibleHeader(string title, bool foldout) { GUIStyle headerStyle = new GUIStyle(EditorStyles.foldout); headerStyle.fontSize = 14; headerStyle.fontStyle = FontStyle.Bold; EditorGUILayout.BeginHorizontal(); foldout = EditorGUILayout.Foldout(foldout, title, true, headerStyle); EditorGUILayout.EndHorizontal(); return foldout; } }This static class has a method
DrawCollapsibleHeaderwhich allows you to create collapsible headers that can be used in any custom Editor script.- Next, modify your custom Editor script (e.g., MyMonobehaviourEditor) to use the reusable
DrawCollapsibleHeaderfunction:
using UnityEngine; using UnityEditor; [CustomEditor(typeof(MyMonobehaviour))] public class MyMonobehaviourEditor : Editor { private bool showHeadbobSettings = true; public override void OnInspectorGUI() { MyMonobehaviour myScript = (MyMonobehaviour)target; // Draw default inspector properties. DrawDefaultInspector(); // Add collapsible Headbob Settings header. showHeadbobSettings = EditorUtilities.DrawCollapsibleHeader("Headbob Settings", showHeadbobSettings); if (showHeadbobSettings) { EditorGUI.indentLevel++; myScript.headBobDuration = EditorGUILayout.FloatField("Headbob Duration", myScript.headBobDuration); myScript.headBobHeightAmplitude = EditorGUILayout.FloatField("Headbob Height Amplitude", myScript.headBobHeightAmplitude); myScript.headBobRotationAmplitude = EditorGUILayout.FloatField("Headbob Rotation Amplitude", myScript.headBobRotationAmplitude); EditorGUI.indentLevel--; } } }Now, if you want to create collapsible headers in any custom Editor script, you can simply call the
EditorUtilities.DrawCollapsibleHeadermethod. This makes it easier to handle multiple headers and keep your code organized.