integrate bunny hopping to get on speed when jumping left and ride:
using Mirror;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Random = UnityEngine.Random;
namespace MarsFPSKit
{
///
/// Helper class for Footsteps
///
[Serializable]
public class Footstep
{
///
/// Sounds for this footstep material
///
public AudioClip[] clips;
///
/// Max audio distance for this footstep material
///
public float maxDistance = 20f;
///
/// Audio rolloff for this footstep material
///
public AnimationCurve rollOff = AnimationCurve.EaseInOut(0f, 1f, 20f, 0f);
}
code
[Serializable]
public class StringFootstepDictionary : SerializableDictionary<string, Footstep> { }
[Serializable]
public class NestedSound
{
public AudioClip[] clips;
}
[CreateAssetMenu(menuName = "MarsFPSKit/Movement/Boots on ground")]
public class Kit_Movement_BootsOnGround : Kit_MovementBase
{
[Header("Stats")]
[Tooltip("Sprinting speed")]
public float sprintSpeed = 6f;
[Tooltip("Normal walk speed")]
public float walkSpeed = 6f;
[Tooltip("Crouch walk speed")]
public float crouchSpeed = 6f;
/// <summary>
/// If this is set to true, we can move while we are not grounded
/// </summary>
public bool airControlEnabled = false;
/// <summary>
/// Air control can control sprint?
/// </summary>
public bool airControlSprintControl = true;
[Tooltip("Multiplier that is applied to Physics.gravity for the character controller")]
/// <summary>
/// Multiplier for Physics.gravity
/// </summary>
public float gravityMultiplier = 1f;
[Tooltip("The speed that is applied when you try to jump")]
public float jumpSpeed = 8f;
/// <summary>
/// How many times can we jump
/// </summary>
[Tooltip("How many times can we jump?")]
public int jumpMaxCount = 1;
[Tooltip("How much stamina does the jump cost?")]
/// <summary>
/// How much stamina does the jump cost?
/// </summary>
public float jumpStaminaCost = 10f;
/// <summary>
/// Which jump animation to play for a certain jump count?
/// </summary>
public string[] jumpAnimations;
/// <summary>
/// Which jump sound to play for a certain jump?
/// </summary>
public NestedSound[] jumpSound;
/// <summary>
/// Which land sound to play for a certain jump?
/// </summary>
public NestedSound[] jumpLandSound;
[Header("Character Heights")]
public float standHeight = 1.8f; //State 0 height
public float crouchHeight = 1.2f; //State 1 height
[Header("Camera Positions")]
public float camPosSmoothSpeed = 6f; //The lerp speed of changing the camera position
public Vector3 camPosStand = new Vector3(0, 1.65f, 0f);
public Vector3 camPosCrouch = new Vector3(0, 1.05f, 0f);
[Header("Fall Damage")]
/// <summary>
/// After how many units of falling will we take damage?
/// </summary>
public float fallDamageThreshold = 10;
/// <summary>
/// With which value will the fall damage be multiplied with?
/// </summary>
public float fallDamageMultiplier = 5f;
[Header("Others")]
[Tooltip("How many units should we be moved down by default? To be able to walk down stairs properly")]
public float defaultYmove = -2f; //How many units should we be moved down by default? To be able to walk down stairs properly
[Header("Footsteps")]
public float footstepsRunTime = 0.25f; //Time between footsteps when we're running
public float footstepsWalkTime = 0.4f; //Time between footsteps when we're standing
public float footstepsCrouchTime = 0.7f; //Time between footsteps when we're crouching
public float footstepsRunVolume = 0.8f; //Volume for footsteps when we're running
public float footstepsWalkVolume = 0.4f; //Volume for footsteps when we're walking
public float footstepsCrouchVolume = 0.1f; //Volume for footsteps when we're crouching
public StringFootstepDictionary allFootsteps; //All footstep materials
[Header("Fall Down effect")]
public float fallDownAmount = 10.0f;
public float fallDownMinOffset = -6.0f;
public float fallDownMaxoffset = 6.0f;
public float fallDownTime = 0.3f;
public float fallDownReturnSpeed = 1f;
/// <summary>
/// Is stamina enabled?
/// </summary>
[Header("Stamina")]
public bool staminaSystemEnabled = true;
/// <summary>
/// How fast will stamina decrease when we are running?
/// </summary>
public float staminaDecreaseRate = 5f;
/// <summary>
/// How fast will stamina increase when we are not running?=
/// </summary>
public float staminaIncreaseRate = 3f;
/// <summary>
/// How long until regen starts when stamina was not depleted?
/// </summary>
public float staminaPauseRateNotEmpty = 2f;
/// <summary>
/// How long until regen starts when stamina was depleted?
/// </summary>
public float staminaPauseRateEmpty = 5f;
/// <summary>
/// How long will sprinting be blocked if stamina was depleted
/// </summary>
public float staminaDepletedSprintBlockTime = 7f;
/// <summary>
/// Sounds that will play when stamina was depleted
/// </summary>
public AudioClip[] staminaExhaustedSound;
/// <summary>
/// How fast do we swim?
/// </summary>
[Header("Swimming")]
public float swimmingSpeed = 4f;
/// <summary>
/// How fast does it react to our input?
/// </summary>
public float swimmingInputLerpSpeed = 1f;
/// <summary>
/// Swimming height
/// </summary>
public float swimmingHeight = 0.6f;
/// <summary>
/// Weapon to select when swimming!
/// </summary>
public Weapons.Kit_WeaponBase swimmingWeapon;
/// <summary>
/// Should we be able to drown?
/// </summary>
public bool swimmingEnableDrowning;
/// <summary>
/// How long does it take to drown?
/// </summary>
public float swimmingDrowningTime = 5f;
/// <summary>
/// How quickly do we recover air?
/// </summary>
public float swimmingDrowningRecoveryTime = 5f;
/// <summary>
/// How much time between drowning
/// </summary>
public Vector2 swimmingDrowningDamageTimes = new Vector2(1, 3);
/// <summary>
/// Damage we take when drowning
/// </summary>
public Vector2 swimmingDrowningDamage = new Vector2(10, 20f);
[Header("Authorative Correction")]
public float history = 1f;
public float deltaMultiplier = 1;
public float teleportDistance = 2f;
public override void InitializeServer(Kit_PlayerBehaviour pb)
{
GameObject data = Instantiate(networkData, Vector3.zero, Quaternion.identity);
Kit_Movement_BootsOnGroundNetworkData nData = data.GetComponent<Kit_Movement_BootsOnGroundNetworkData>();
pb.movementNetworkData = nData;
nData.ownerPlayerNetworkId = pb.netId;
if (pb.isBot)
NetworkServer.Spawn(data);
else
NetworkServer.Spawn(data, pb.gameObject);
}
public override void InitializeClient(Kit_PlayerBehaviour pb)
{
if (!pb.movementNetworkData)
{
//Find ours
pb.movementNetworkData = FindObjectsOfType<Kit_Movement_BootsOnGroundNetworkData>().Where(x => x.ownerPlayerNetworkId == pb.netId).FirstOrDefault();
}
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
bogrd.amountOfSnapShots = Mathf.CeilToInt(history / Time.fixedDeltaTime);
bogrd.historicalPositions = new List<Vector3>(bogrd.amountOfSnapShots);
for (int i = 0; i < bogrd.amountOfSnapShots; i++)
{
bogrd.historicalPositions.Add(pb.transform.position);
}
bogrd.serverPosition = pb.transform.position;
bogrd.serverRotation = pb.transform.rotation;
}
public override void NotControllerUpdate(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Manually sync
pb.transform.position = Vector3.Lerp(pb.transform.position, bogrd.serverPosition, Time.deltaTime * 20f);
pb.transform.rotation = Quaternion.Slerp(pb.transform.rotation, bogrd.serverRotation, Time.deltaTime * 20f);
}
public override void AuthorativeInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta, double revertTime)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Swim logic
if (data.isSwimming)
{
//Reset "ground" bools
data.isGrounded = false;
data.isJumping = false;
data.isSprinting = false;
data.falling = false;
//Adjust CC
pb.cc.height = swimmingHeight; //Set height
pb.cc.center = new Vector3(0f, swimmingHeight / 1.3f, 0f); //Set center
#region Main Input
//Only get input if the cursor is locked
if (pb.canControlPlayer)
{
//Check if we want to move
if (data.isGrounded && data.desiredMoveDirection.sqrMagnitude > 0.005f)
{
//Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
}
if (Mathf.Abs(input.ver) > 0.05f)
{
data.desiredMoveDirection.x = 0f;
data.desiredMoveDirection.y = 0f;
data.desiredMoveDirection.z = input.ver;
//Transform
data.desiredMoveDirection = pb.playerCameraTransform.TransformDirection(data.desiredMoveDirection * swimmingSpeed);
//Add that
data.swimmingWorldMoveDirection += data.desiredMoveDirection * delta * swimmingInputLerpSpeed;
data.swimmingWorldMoveDirection = Vector3.ClampMagnitude(data.swimmingWorldMoveDirection, swimmingSpeed);
}
if (Mathf.Abs(input.hor) > 0.05f)
{
data.desiredMoveDirection.x = input.hor;
data.desiredMoveDirection.y = 0f;
data.desiredMoveDirection.z = 0f;
//Transform
data.desiredMoveDirection = pb.playerCameraTransform.TransformDirection(data.desiredMoveDirection * swimmingSpeed);
//Add that
data.swimmingWorldMoveDirection += data.desiredMoveDirection * delta * swimmingInputLerpSpeed;
data.swimmingWorldMoveDirection = Vector3.ClampMagnitude(data.swimmingWorldMoveDirection, swimmingSpeed);
}
if (Mathf.Abs(input.ver) < 0.05f && Mathf.Abs(input.hor) < 0.05f)
{
data.swimmingWorldMoveDirection = Vector3.Lerp(data.swimmingWorldMoveDirection, Vector3.zero, delta * swimmingInputLerpSpeed);
}
}
//If not, don't move
else
{
data.swimmingWorldMoveDirection = Vector3.Lerp(data.swimmingWorldMoveDirection, Vector3.zero, delta * swimmingInputLerpSpeed);
}
//Move
pb.cc.Move(data.swimmingWorldMoveDirection * delta);
data.moveDirection = pb.cc.velocity;
//Get local movement direction
data.localMoveDirection = pb.playerCameraTransform.InverseTransformDirection(data.moveDirection);
//Velocity
data.velocity = pb.cc.velocity;
#endregion
if (data.isUnderwater)
{
//Check if drowning is enabled
if (swimmingEnableDrowning)
{
if (data.airLeft > 0)
{
data.airLeft -= (100 / swimmingDrowningTime) * delta;
}
else
{
if (Time.time > data.nextAirDamageAppliedAt)
{
if (pb.isServer)
{
//Apply damage
pb.ServerDamage(Random.Range(swimmingDrowningDamage.x, swimmingDrowningDamage.y), "Water", pb.transform.position, Vector3.zero, 0f, pb.transform.position, 0, pb.isBot, pb.id);
}
//Set time
data.nextAirDamageAppliedAt = Time.time + Random.Range(swimmingDrowningDamageTimes.x, swimmingDrowningDamageTimes.y);
}
}
}
}
else
{
if (swimmingEnableDrowning)
{
if (data.airLeft < 100f)
{
data.airLeft += (100 / swimmingDrowningRecoveryTime) * delta;
}
}
}
}
else
{
if (pb.cc.isGrounded || airControlEnabled && !data.wasSwimming)
{
float yMovement = data.moveDirection.y;
#region Main Input
//Only get input if the cursor is locked
if (pb.canControlPlayer)
{
//Calculate move direction based on input
data.moveDirection.x = input.hor;
//if (pb.cc.isGrounded)
data.moveDirection.y = 0f;
data.moveDirection.z = input.ver;
//Check if we want to move
if (data.isGrounded && data.moveDirection.sqrMagnitude > 0.005f)
{
//Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
}
//Correct strafe
data.moveDirection = Vector3.ClampMagnitude(data.moveDirection, 1f);
if (pb.cc.isGrounded)
{
data.moveDirection.y = defaultYmove;
}
else
{
data.moveDirection.y = 0f;
}
if (airControlSprintControl || data.isGrounded)
{
//Get sprinting input
if (input.sprint && data.moveDirection.z > 0.3f && pb.weaponManager.CanRun(pb))
{
//Check if we can sprint
if (data.state == 0 && (!staminaSystemEnabled || staminaSystemEnabled && data.staminaLeft >= 0f && Time.time > data.staminaDepletedSprintingBlock))
{
data.isSprinting = true;
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= delta * staminaDecreaseRate;
if (data.staminaLeft <= 0f)
{
//Stamina is now depleted. Set times
data.staminaRegenerationTime = Time.time + staminaPauseRateEmpty;
data.staminaDepletedSprintingBlock = Time.time + staminaDepletedSprintBlockTime;
//Play sound.
if (staminaExhaustedSound.Length > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(0, 0, Random.Range(0, staminaExhaustedSound.Length));
}
}
}
else
{
//Set time for regen
data.staminaRegenerationTime = Time.time + staminaPauseRateNotEmpty;
}
}
}
//We cannot sprint
else
{
data.isSprinting = false;
}
}
else
{
//We are not sprinting
data.isSprinting = false;
}
}
}
//If not, don't move
else
{
//Reset move direction
data.moveDirection = new Vector3(0f, defaultYmove, 0f);
//Reset sprinting
data.isSprinting = false;
}
#endregion
//Take rotation in consideration (local to world)
data.moveDirection = pb.transform.TransformDirection(data.moveDirection);
//Apply speed based on state
//Standing
if (data.state == 0)
{
//Sprinting
if (data.isSprinting)
{
data.moveDirection *= sprintSpeed;
}
//Not sprinting
else
{
data.moveDirection *= walkSpeed;
}
}
//Crouching
else if (data.state == 1)
{
data.moveDirection *= crouchSpeed;
}
if (!pb.cc.isGrounded)
{
data.moveDirection.y = yMovement;
}
else
{
//Mouse Look multiplier
data.moveDirection *= pb.looking.GetSpeedMultiplier(pb);
//Weapon multiplier
data.moveDirection *= pb.weaponManager.CurrentMovementMultiplier(pb); //Retrive from weapon manager
//Should play slow animation?
data.playSlowWalkAnimation = pb.weaponManager.IsAiming(pb); //Retrive from weapon manager
}
}
//Air recovery
if (swimmingEnableDrowning)
{
if (data.airLeft < 100f)
{
data.airLeft += (100 / swimmingDrowningRecoveryTime) * delta;
}
}
if (pb.cc.isGrounded)
{
#region Fall Damage
if (data.falling)
{
//Calculate distance we have fallen
data.fallDistance = data.fallHighestPoint - pb.transform.position.y;
data.falling = false;
if (data.fallDistance > fallDamageThreshold)
{
//Apply Fall distance multiplied with the multiplier (=Fall Damage)
pb.ApplyFallDamage(data.fallDistance * fallDamageMultiplier);
if (pb.isFirstPersonActive)
{
Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.Kick(pb.playerCameraFallDownTransform, new Vector3(fallDownAmount, Random.Range(fallDownMinOffset, fallDownMaxoffset), 0), fallDownTime));
//Tell weapon manager
pb.weaponManager.FallDownEffect(pb, true);
}
}
else if (data.fallDistance > 0.1f)
{
if (pb.isFirstPersonActive)
{
Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.Kick(pb.playerCameraFallDownTransform, new Vector3(fallDownAmount / 3, Random.Range(fallDownMinOffset, fallDownMaxoffset) / 2, 0), fallDownTime));
//Tell weapon manager
pb.weaponManager.FallDownEffect(pb, false);
}
}
}
#endregion
#region Crouch Input
if (pb.canControlPlayer)
{
if (Kit_GameSettings.isCrouchToggle)
{
if (data.lastCrouch != input.crouch)
{
data.lastCrouch = input.crouch;
//Get crouch input
if (input.crouch)
{
//Change state
if (data.state == 0)
{
//We are standing, crouch
data.state = 1;
}
else if (data.state == 1)
{
//We are crouching, stand up
data.state = 0;
}
}
}
}
else
{
if (input.crouch)
{
data.state = 1;
}
else
{
data.state = 0;
}
data.lastCrouch = input.crouch;
}
}
#endregion
#region Jump
//Reset jump counter
if (data.jumpCount > 0)
{
if (pb.isServer)
{
//We Landed
pb.RpcMovementPlaySound(2, data.jumpCount - 1, Random.Range(0, jumpLandSound[data.jumpCount - 1].clips.Length));
}
data.jumpCount = 0;
data.isJumping = false;
}
if (pb.canControlPlayer)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
//Get Jump input
if (input.jump)
{
//Check if we can jump
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
if (pb.isServer)
{
//Play Animation and Jump Sound
pb.RpcMovementPlayAnimation(0, data.jumpCount);
pb.RpcMovementPlaySound(1, data.jumpCount, Random.Range(0, jumpSound[data.jumpCount].clips.Length));
}
data.jumpCount = 1;
//Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= jumpStaminaCost;
if (data.staminaLeft <= 0f)
{
//Stamina is now depleted. Set times
data.staminaRegenerationTime = Time.time + staminaPauseRateEmpty;
data.staminaDepletedSprintingBlock = Time.time + staminaDepletedSprintBlockTime;
//Play sound.
if (staminaExhaustedSound.Length > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(0, 0, Random.Range(0, staminaExhaustedSound.Length));
}
}
}
else
{
//Set time for regen
data.staminaRegenerationTime = Time.time + staminaPauseRateNotEmpty;
}
}
}
}
//If we try to jump and we try to jump, stand up
else if (data.state == 1)
{
data.state = 0;
}
}
}
}
#endregion
}
else
{
//Save initial falling point
if (!data.falling)
{
data.fallHighestPoint = pb.transform.position.y;
data.falling = true;
}
//Check if we moved higher for some reason
if (pb.transform.position.y > data.fallHighestPoint)
{
data.fallHighestPoint = pb.transform.position.y;
}
if (data.isJumping)
{
if (data.jumpCount < jumpMaxCount)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
//Get Jump input
if (input.jump)
{
//Check if we can jump
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
if (pb.isServer)
{
pb.RpcMovementPlayAnimation(0, data.jumpCount);
pb.RpcMovementPlaySound(1, data.jumpCount, Random.Range(0, jumpSound[data.jumpCount].clips.Length));
}
data.jumpCount++;
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= jumpStaminaCost;
if (data.staminaLeft <= 0f)
{
//Stamina is now depleted. Set times
data.staminaRegenerationTime = Time.time + staminaPauseRateEmpty;
data.staminaDepletedSprintingBlock = Time.time + staminaDepletedSprintBlockTime;
//Play sound.
if (staminaExhaustedSound.Length > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(0, 0, Random.Range(0, staminaExhaustedSound.Length));
}
}
}
else
{
//Set time for regen
data.staminaRegenerationTime = Time.time + staminaPauseRateNotEmpty;
}
}
}
}
}
}
}
}
}
#region Character Height
//Change character height based on the state
//Standing
if (data.state == 0)
{
pb.cc.height = standHeight; //Set height
pb.cc.center = new Vector3(0f, standHeight / 2, 0f); //Set center
}
//Crouch
else if (data.state == 1)
{
pb.cc.height = crouchHeight; //Set height
pb.cc.center = new Vector3(0f, crouchHeight / 2, 0f); //Set center
}
#endregion
// Apply JumpPad velocity if set
if (data.jumpPadVelocity != Vector3.zero)
{
data.moveDirection = data.jumpPadVelocity;
data.jumpPadVelocity = Vector3.zero; // Reset after use
Debug.Log("[BootsOnGround] JumpPad velocity applied.");
}
//Apply gravity
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
//Move
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
//Get local movement direction
data.localMoveDirection = pb.transform.InverseTransformDirection(pb.cc.velocity);
//Check grounded
data.isGrounded = pb.cc.isGrounded;
//Velocity
data.velocity = pb.cc.velocity;
//If we are grounded, reset swimming bool
if (data.isGrounded)
{
data.wasSwimming = false;
}
//Check if we hit a roof
if (collision.HasFlag(CollisionFlags.Above))
{
if (data.moveDirection.y > 0f)
{
data.moveDirection.y = -data.moveDirection.y;
}
}
}
//Move the camer to the correct position
#region CameraMove
//Standing
if (data.state == 0)
{
//Smoothly lerp to the correct state
pb.mouseLookObject.localPosition = Vector3.Lerp(pb.mouseLookObject.localPosition, camPosStand + pb.looking.GetCameraOffset(pb), delta * camPosSmoothSpeed);
}
//Crouching
else if (data.state == 1)
{
//Smoothly lerp to the correct state
pb.mouseLookObject.localPosition = Vector3.Lerp(pb.mouseLookObject.localPosition, camPosCrouch + pb.looking.GetCameraOffset(pb), delta * camPosSmoothSpeed);
}
#endregion
#region Character Height
//Change character height based on the state
//Standing
if (data.state == 0)
{
pb.cc.height = standHeight; //Set height
pb.cc.center = new Vector3(0f, standHeight / 2, 0f); //Set center
}
//Crouch
else if (data.state == 1)
{
pb.cc.height = crouchHeight; //Set height
pb.cc.center = new Vector3(0f, crouchHeight / 2, 0f); //Set center
}
#endregion
#region Stamina regen
if (staminaSystemEnabled && pb.isServer)
{
//Check if we can regen
if (Time.time > data.staminaRegenerationTime)
{
//Check if we need to regen
if (data.staminaLeft < 100f)
{
//Now, regen
data.staminaLeft += delta * staminaIncreaseRate;
}
}
}
#endregion
if (pb.isServer)
{
data.serverPosition = pb.transform.position;
data.serverRotation = pb.transform.rotation;
}
}
public override void PredictionInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (!pb.isServer)
{
if (data.historicalPositions.Count > 0)
{
//Calculate how much delay between server and client
data.snapShotCalculated = Mathf.RoundToInt(Mathf.InverseLerp(0, history, (float)NetworkTime.rtt) * data.amountOfSnapShots);
//Debug.Log("Calculated snapshot: " + snapShotToUse);
//Debug.Log("Closest snapshot: " + closestSnapshot);
//This is the position where serverPosition currently should be
Vector3 positionToCompareServerPosTo = data.historicalPositions[Mathf.Clamp(data.snapShotCalculated, 0, data.historicalPositions.Count - 1)];
//Offset in the past
float d = Vector3.Distance(positionToCompareServerPosTo, data.serverPosition);
data.deltaToServer = data.serverPosition - positionToCompareServerPosTo;
float totalInput = (Mathf.Abs(input.ver) + Mathf.Abs(input.hor));
float inputMultiplier = Mathf.Lerp(3, 1, totalInput);
float totalDelta = Mathf.Clamp01(delta * deltaMultiplier * inputMultiplier);
Vector3 deltaAdd = (data.deltaToServer * totalDelta);
deltaAdd.y = 0;
if (d > 0.03f)
{
//Move faster the larger the distance is, and also faster if wew let go of the input
pb.transform.position = pb.transform.position + deltaAdd;
for (int i = 0; i < data.snapShotCalculated; i++)
{
data.historicalPositions[i] += deltaAdd;
}
}
//Teleport distance
if (d > teleportDistance)
{
pb.transform.position = data.serverPosition;
for (int i = 0; i < data.historicalPositions.Count; i++)
{
data.historicalPositions[i] = data.serverPosition;
}
}
}
}
//Just simulate this again
AuthorativeInput(pb, input, delta, 0);
}
public void OnServerPositionReceived(Kit_PlayerBehaviour pb, Vector3 serverPos)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
}
public override void CreateSnapshot(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (data.historicalPositions.Count < data.amountOfSnapShots)
{
data.historyLastPositionSetAt = Time.time + Time.fixedDeltaTime;
data.historicalPositions.Add(pb.transform.position);
}
else
{
//Extract position and re-add it at the front.
data.historicalPositions.RemoveAt(data.historicalPositions.Count - 1);
data.historicalPositions.Insert(0, pb.transform.position);
data.historyLastPositionSetAt = Time.time + Time.fixedDeltaTime;
}
}
public override void Visuals(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (pb.isFirstPersonActive)
{
//Move transform back
pb.playerCameraFallDownTransform.localRotation = Quaternion.Slerp(pb.playerCameraFallDownTransform.localRotation, Quaternion.identity, Time.deltaTime * fallDownReturnSpeed);
if ((data.isSwimming && swimmingEnableDrowning && data.airLeft < 100f) || data.airLeft < 100f && !data.isSprinting && data.staminaLeft >= 99)
{
Kit_IngameMain.instance.hud.DisplayStamina(data.airLeft);
}
else
{
//Display stamina
Kit_IngameMain.instance.hud.DisplayStamina(data.staminaLeft);
}
if (data.state == 0)
{
Kit_IngameMain.instance.hud.DisplayMovementState(0);
}
else if (data.state == 1)
{
Kit_IngameMain.instance.hud.DisplayMovementState(1);
}
}
}
public override int GetCurrentWeaponMoveAnimation(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Check if we're grounded
if (bogrd.isGrounded)
{
//Check if we're moving
if (pb.cc.velocity.sqrMagnitude > 0.5f)
{
//Check if we're sprinting, if return 2
if (bogrd.isSprinting) return 2;
//If not return 1
else
return 1;
}
}
return 0;
}
public override float GetCurrentWalkAnimationSpeed(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Check if we're grounded
if (bogrd.isGrounded)
{
//Check if we're moving
if (pb.cc.velocity.sqrMagnitude > 0.1f)
{
//Check if we're sprinting, if return speed divided by sprintSpeed
if (bogrd.isSprinting) return pb.cc.velocity.magnitude / sprintSpeed;
//If not return speed divided by normal walking speed
else
return pb.cc.velocity.magnitude / walkSpeed;
}
}
return 1f;
}
public override Vector3 GetMovementDirection(Kit_PlayerBehaviour pb)
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
return bogrd.localMoveDirection.normalized;
}
return Vector3.zero;
}
/*public override bool CanFire(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Just based on our spriting value, if we are sprinting we cannot fire
if (bogrd.isSprinting && bogrd.isGrounded) return false;
else return true;
}*/
public override bool CanFire(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
// If the player is sprinting, cancel sprinting before firing
if (bogrd.isSprinting)
{
bogrd.isSprinting = false; // This assumes you can directly modify this state
}
// Now allow firing
return true;
}
public override bool IsRunning(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Just based on our spriting value, if we are sprinting we cannot fire
if (bogrd.isSprinting) return true;
else return false;
}
public override void CalculateFootstepsUpdate(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Check if we're grounded
if (bogrd.isGrounded)
{
//Get velMag
if (bogrd.velocity.magnitude > 0.5f)
{
//We're moving
//Check if enough time has passed since the last footstep
if (Time.time >= bogrd.nextFootstep)
{
if (allFootsteps.ContainsKey(bogrd.currentMaterial))
{
//Set next footstep sound
pb.footstepSource.clip = allFootsteps[bogrd.currentMaterial].clips[Random.Range(0, allFootsteps[bogrd.currentMaterial].clips.Length)];
//Set footstep source rolloff and distance
pb.footstepSource.maxDistance = allFootsteps[bogrd.currentMaterial].maxDistance;
pb.footstepSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, allFootsteps[bogrd.currentMaterial].rollOff);
//Set volume and time
if (bogrd.state == 0)
{
if (bogrd.isSprinting) //Sprinting
{
pb.footstepSource.volume = footstepsRunVolume;
bogrd.nextFootstep = Time.time + footstepsRunTime;
}
else //Normal walking
{
pb.footstepSource.volume = footstepsWalkVolume;
bogrd.nextFootstep = Time.time + footstepsWalkTime;
}
}
else if (bogrd.state == 1) //Crouching
{
pb.footstepSource.volume = footstepsCrouchVolume;
bogrd.nextFootstep = Time.time + footstepsCrouchTime;
}
//Play
pb.footstepSource.Play();
}
}
}
}
}
public override void OnControllerColliderHitRelay(Kit_PlayerBehaviour pb, ControllerColliderHit hit)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
Terrain terrain = hit.collider.GetComponent<Terrain>();
Kit_TerrainFootstepConverter convertedFootsteps = hit.collider.GetComponent<Kit_TerrainFootstepConverter>();
if (terrain && convertedFootsteps)
{
//Get texture from helper
int texture = GetMainTexture(pb.transform.position, terrain);
if (texture < convertedFootsteps.textureToString.Length)
{
//Convert texture id to 'tag' equivalent
if (allFootsteps.ContainsKey(convertedFootsteps.textureToString[texture]))
{
bogrd.currentMaterial = convertedFootsteps.textureToString[texture];
}
else
{
bogrd.currentMaterial = "Concrete";
}
}
else
{
Debug.LogError("Terrain texture outside of texture to foosteps conversion array! Playing concrete footstep.");
bogrd.currentMaterial = "Concrete";
}
}
else
{
//Use tag if it exists
if (allFootsteps.ContainsKey(hit.collider.tag))
{
bogrd.currentMaterial = hit.collider.tag;
}
//Use default 'concrete'
else
{
bogrd.currentMaterial = "Concrete";
}
}
}
public override Vector3 GetVelocity(Kit_PlayerBehaviour pb)
{
if (pb.isLocalPlayer || pb.isServer)
{
//If we are the controller, just get velocity from the character controller
return pb.cc.velocity;
}
else
{
return Vector3.zero;
}
}
public override void PlaySound(Kit_PlayerBehaviour pb, int soundID, int id2, int arrayID)
{
//Check if sound isnt playing right now
//Check for id
if (soundID == 0) //Exhausted
{
if (!pb.movementSoundSource.isPlaying)
{
//Set clip
pb.movementSoundSource.clip = staminaExhaustedSound[arrayID];
//Play
pb.movementSoundSource.Play();
}
}
else if (soundID == 1)
{
//Set clip
pb.movementSoundSource.clip = jumpSound[id2].clips[arrayID];
//Play
pb.movementSoundSource.Play();
}
else if (soundID == 2)
{
//Set clip
pb.movementSoundSource.clip = jumpLandSound[id2].clips[arrayID];
//Play
pb.movementSoundSource.Play();
}
}
public override void PlayAnimation(Kit_PlayerBehaviour pb, int id, int id2)
{
if (id == 0)
{
pb.thirdPersonPlayerModel.anim.SetTrigger(jumpAnimations[Mathf.Clamp(id2, 0, jumpAnimations.Length - 1)]);
}
}
public override void OnTriggerEnterRelay(Kit_PlayerBehaviour pb, Collider col)
{
//Check for swimming trigger
if (col.GetComponent<Kit_SwimmingTrigger>())
{
//Get
Kit_SwimmingTrigger trigger = col.GetComponent<Kit_SwimmingTrigger>();
//Check if its ours
if (pb.isServer)
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
Debug.Log("[Player] Entered swimming trigger. Entering swim state.");
//Only play this sound upon entering!
if (bogrd.state != 3)
{
//Check if a sound should be played
if (trigger.playerEnterSound)
{
if (Time.time - 0.5f > bogrd.lastSwimmingSoundPlayed)
{
AudioSource.PlayClipAtPoint(trigger.playerEnterSound, pb.playerCameraTransform.position);
bogrd.lastSwimmingSoundPlayed = Time.time;
}
}
}
//Set state
bogrd.state = 3;
//Copy input
bogrd.swimmingWorldMoveDirection = bogrd.moveDirection;
bogrd.swimmingCurrent = trigger;
if (swimmingWeapon)
{
//Copy current weapon slot
int wep = pb.weaponManager.GetCurrentlySelectedWeapon(pb);
if (wep != bogrd.swimmingWeaponSlot)
{
bogrd.swimmingPreviousWeaponSlot = wep;
}
//Select swimming weapon
pb.weaponManager.PluginSelectWeapon(pb, bogrd.swimmingWeaponSlot, true);
}
}
}
else
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
//Only play this sound upon entering!
if (!bogrd.isSwimming)
{
//Check if a sound should be played
if (trigger.playerEnterSound)
{
if (Time.time - 0.5f > bogrd.lastSwimmingSoundPlayed)
{
AudioSource.PlayClipAtPoint(trigger.playerEnterSound, pb.playerCameraTransform.position);
bogrd.lastSwimmingSoundPlayed = Time.time;
}
}
bogrd.state = 3;
}
}
}
}
}
public override void OnTriggerExitRelay(Kit_PlayerBehaviour pb, Collider col)
{
Kit_SwimmingTrigger swim = col.GetComponent<Kit_SwimmingTrigger>();
//Check for swimming trigger
if (swim)
{
//Check if its ours
if (pb.isServer)
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
if (bogrd.state == 3 && bogrd.swimmingCurrent == swim)
{
Debug.Log("[Player] Exited swimming trigger. Exiting swim state.");
//Set bool
bogrd.wasSwimming = true;
//Set state
bogrd.state = 0;
bogrd.swimmingCurrent = null;
bogrd.moveDirection = bogrd.swimmingWorldMoveDirection;
bogrd.moveDirection += swim.exitAdjustment;
//Select previous weapon
if (swimmingWeapon)
{
pb.weaponManager.PluginSelectWeapon(pb, bogrd.swimmingPreviousWeaponSlot, false);
}
}
}
}
else
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
//Just reset bool
bogrd.state = 0;
}
}
}
}
public override void OnCameraTriggerEnterRelay(Kit_PlayerBehaviour pb, Collider col)
{
Kit_SwimmingTrigger swim = col.GetComponent<Kit_SwimmingTrigger>();
//Check for swimming trigger
if (swim)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (bogrd.swimmingCurrent == swim)
{
//Camera is underwater - player is underwater too
bogrd.isUnderwater = true;
//Check if that's really "us" and not a bot
if (pb.isFirstPersonActive)
{
//Show
Kit_IngameMain.instance.hud.DisplayUnderwater(true);
}
}
}
}
public override void OnCameraTriggerExitRelay(Kit_PlayerBehaviour pb, Collider col)
{
Kit_SwimmingTrigger swim = col.GetComponent<Kit_SwimmingTrigger>();
//Check for swimming trigger
if (swim)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (bogrd.swimmingCurrent == swim)
{
//Camera is not underwater - player is not underwater anymore
bogrd.isUnderwater = false;
//Check if that's really "us" and not a bot
if (pb.isFirstPersonActive)
{
//Hide
Kit_IngameMain.instance.hud.DisplayUnderwater(false);
}
}
}
}
#region Weapon Injection
public override WeaponsFromPlugin WeaponsToInjectIntoWeaponManager(Kit_PlayerBehaviour player)
{
if (swimmingWeapon)
{
WeaponsFromPlugin toReturn = new WeaponsFromPlugin();
toReturn.weaponsInSlot = new WeaponAttachmentBundle[1];
toReturn.weaponsInSlot[0] = new WeaponAttachmentBundle();
toReturn.weaponsInSlot[0].weapon = swimmingWeapon;
toReturn.weaponsInSlot[0].attachments = new int[0];
return toReturn;
}
else
{
return base.WeaponsToInjectIntoWeaponManager(player);
}
}
public override void ReportSlotOfInjectedWeapons(Kit_PlayerBehaviour pb, int slotWhereTheyWereInjected)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
bogrd.swimmingWeaponSlot = slotWhereTheyWereInjected;
}
#endregion
#region Helpers for Terrain
public static float[] GetTextureMix(Vector3 worldPos, Terrain terrain)
{
// returns an array containing the relative mix of textures
// on the main terrain at this world position.
// The number of values in the array will equal the number
// of textures added to the terrain.
TerrainData terrainData = terrain.terrainData;
Vector3 terrainPos = terrain.transform.position;
// calculate which splat map cell the worldPos falls within (ignoring y)
int mapX = (int)(((worldPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
int mapZ = (int)(((worldPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);
// get the splat data for this cell as a 1x1xN 3d array (where N = number of textures)
float[,,] splatmapData = terrainData.GetAlphamaps(mapX, mapZ, 1, 1);
// extract the 3D array data to a 1D array:
float[] cellMix = new float[splatmapData.GetUpperBound(2) + 1];
for (int n = 0; n < cellMix.Length; ++n)
{
cellMix[n] = splatmapData[0, 0, n];
}
return cellMix;
}
public static int GetMainTexture(Vector3 worldPos, Terrain terrain)
{
// returns the zero-based index of the most dominant texture
// on the main terrain at this world position.
float[] mix = GetTextureMix(worldPos, terrain);
float maxMix = 0;
int maxIndex = 0;
// loop through each mix value and find the maximum
for (int n = 0; n < mix.Length; ++n)
{
if (mix[n] > maxMix)
{
maxIndex = n;
maxMix = mix[n];
}
}
return maxIndex;
}
#endregion
}
}
Assistant
To integrate bunny hopping to get speed specifically when jumping and moving left ("jumping left") into this existing Boots On Ground movement script, you need to:
Detect when the player is bunny hopping (jumping repeatedly, especially with movement input to the left).
Apply additional velocity or speed boost to their movement direction on jump launch to simulate bunny hopping momentum.
Let that extra velocity "ride" over time while in the air, gradually decaying it to avoid infinite speed.
Ensure this integrates with your existing moveDirection and jump logic cleanly.
How Bunny Hopping Concept Maps to Your Script
In your existing code, the important sections related to jumping and air movement are here inside AuthorativeInput inside this block:
csharp
if (pb.cc.isGrounded || airControlEnabled && !data.wasSwimming)
{
// grounded movement, normal walking and sprinting logic here...
}
else
{
// in-air logic including jumps, multiple jumps
}
Your jump is done by setting data.moveDirection.y = jumpSpeed; on jump key press and then applying gravity per frame.
To implement bunny hopping (bhopping) for jumping left, you want to:
Detect jump button press + a strong left input (input.hor < -0.3 or so).
When jump happens on the ground, add a speed boost/velocity in the left direction.
Preserve (or reset) that velocity boost while in air (rides momentum).
Apply some gradual deceleration so the speed boost fades when air control inputs change.
Step-by-step integration
Step 1: Add needed fields in the NetworkData class
You need some variables on the player data (i.e., Kit_Movement_BootsOnGroundNetworkData) for bunny hopping velocity.
Add, for example:
csharp
[NonSerialized] public Vector3 bhopVelocity = Vector3.zero;
[NonSerialized] public float bhopDecaySpeed = 4f; // how fast bunny hop velocity decays
Since this class is not shown here, just add those fields in your Kit_Movement_BootsOnGroundNetworkData class.
User
I meant when jumping left and right
Assistant
Got it! You want bunny hopping to add speed boost both when jumping left and right (not just left). The approach is almost identical to the left-only version, but now you'll apply the boost whenever horizontal input on jump is beyond a threshold on either side.
How to integrate bunny hopping on jumping left and right:
You can detect horizontal input when jumping:
If input.hor > 0.3, then jumping right → add velocity boost right.
If input.hor < -0.3, then jumping left → add velocity boost left.
If horizontal input is near zero, no bunny hop boost.
Changes compared to previous answer:
Instead of only checking for input.hor < -0.3f, you'll check:
Full integration snippet inside AuthorativeInput jump block (grounded jump):
Replace your current jump velocity left addition with:
csharp
if (input.jump)
{
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
// Bunny hop left or right speed boost
if (Mathf.Abs(input.hor) > 0.3f)
{
Vector3 sideDir = input.hor > 0 ? pb.transform.right : -pb.transform.right;
float bhopBoostAmount = 4f; // tune to desired speed boost
data.bhopVelocity = sideDir * bhopBoostAmount;
}
else
{
data.bhopVelocity = Vector3.zero;
}
// Play jump animation, sound etc.
data.jumpCount = 1;
// Spawn protection and stamina logic...
}
}
else if (data.state == 1)
{
// Stand up if crouching
data.state = 0;
}
}
User
show me code before and after your input, so that I exactly know where to put it
Assistant
Certainly! Below I’ll show exactly where to put the bunny hopping integration. I’ll provide the before and after code snippets from your existing AuthorativeInput method, so you can clearly see what to add or replace.
1. In the grounded jump input handling
This is your existing jump input code inside AuthorativeInput in the grounded block (simplified):
BEFORE:
csharp
if (pb.canControlPlayer)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
// Get Jump input
if (input.jump)
{
// Check if we can jump
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
if (pb.isServer)
{
// Play Animation and Jump Sound
pb.RpcMovementPlayAnimation(0, data.jumpCount);
pb.RpcMovementPlaySound(1, data.jumpCount, Random.Range(0, jumpSound[data.jumpCount].clips.Length));
}
data.jumpCount = 1;
// Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= jumpStaminaCost;
if (data.staminaLeft <= 0f)
{
// stamina depleted logic...
}
else
{
// stamina regeneration timing...
}
}
}
}
else if (data.state == 1)
{
// if crouching, stand up
data.state = 0;
}
}
}
}
User
[NonSerialized] public Vector3 bhopVelocity = Vector3.zero;
Show me exactly where to put it here
using Mirror;
using System.Collections.Generic;
using UnityEngine;
namespace MarsFPSKit
{
public class Kit_Movement_BootsOnGroundNetworkData : Kit_MovementNetworkBase
{
code
Assistant
You want to add this field:
csharp
[System.NonSerialized] public Vector3 bhopVelocity = Vector3.zero;
Exactly where to put it
A good place is with other similar Vector3 movement-related fields like:
jumpPadVelocity
moveDirection
desiredMoveDirection
swimmingWorldMoveDirection
Example snippet with your added field:
csharp
public class Kit_Movement_BootsOnGroundNetworkData : Kit_MovementNetworkBase
{
// ... other fields above ...
public Vector3 refVelocity;
public Vector3 desiredMoveDirection = Vector3.zero;
public Vector3 swimmingWorldMoveDirection = Vector3.zero;
public Vector3 moveDirection = Vector3.zero;
/// <summary>
/// Bunny hop velocity for horizontal speed boost during jumps
/// </summary>
[System.NonSerialized]
public Vector3 bhopVelocity = Vector3.zero; // <------ ADD THIS HERE
/// <summary>
/// The local movement direction
/// </summary>
public Vector3 localMoveDirection = Vector3.zero;
// Other existing fields below...
/// <summary>
/// Velocity boost added by external sources such as jump pads. Applied once then reset.
/// </summary>
[System.NonSerialized]
public Vector3 jumpPadVelocity = Vector3.zero;
// Remaining code...
}
Summary:
Place bhopVelocity near other velocity-related fields (moveDirection, jumpPadVelocity, etc.).
Mark it [System.NonSerialized] like jumpPadVelocity since this data probably does not need syncing over network.
Then you can safely read and modify bhopVelocity in your movement code for bunny hopping as discussed.
If you want me to prepare a ready patch file or further explanation just ask!
User
can you add an inspector field for me to enter values for the bunny hopping
Assistant
Certainly! To add inspector-editable fields for bunny hopping parameters in your Kit_Movement_BootsOnGround class (the movement logic ScriptableObject), you should:
Add public fields (e.g., speed boost amount and decay rate).
Use them in your movement logic instead of hardcoded values.
Step 1: Add fields to Kit_Movement_BootsOnGround
In your main movement class (you showed it already), add at the top under [Header("Bunny Hopping Settings")] or create a new header:
csharp
[Header("Bunny Hopping Settings")]
[Tooltip("Speed boost amount horizontally added on bunny hop jump left or right.")]
public float bunnyHopBoostAmount = 4f;
[Tooltip("How fast does the bunny hop boost decay when in air.")]
public float bunnyHopDecaySpeed = 4f;
Step 2: Use the inspector values instead of constants
In your AuthorativeInput method, replace the hardcoded 4f with these fields from the movement instance, for example:
Great! The log shows bhopVelocity is being set and has large values, e.g.:
code
Bunny hop velocity set to: (-7.40, 0.00, -59.54)
This means your boost vector is applied with a very high Z component (-59.54), which might be unexpected and possibly why the gameplay difference feels weird or not visible as expected.
Why is your bhopVelocity so big and skewed on Z axis?
Your code assigns bunny hop velocity like this (pseudo):
If sideDir is pb.transform.right or -pb.transform.right, it should represent a horizontal sideways vector relative to player orientation, no Z component if player faces Z+, but your log shows a large negative Z value.
What does this imply?
pb.transform.right has a large Z component, meaning your player orientation might be rotated such that "right" is not purely along X-axis.
The player’s forward direction (transform.forward) might be rotated such that right vector points into world negative Z mostly (e.g., looking South, right is West).
The large Z value is expected if player's facing direction is rotated, BUT the velocity Z component being so high relative to horizontal movement might make the effect harder to notice in typical first-person view or confuses perception of motion.
What you should check / do to test and visualize properly:
1. Verify that you apply the bhop velocity only on the horizontal plane (X and Z), and don't apply Y component (vertical).
You're doing that correctly, but your jump velocity is data.moveDirection.y = jumpSpeed, and bhopVelocity affects only x and z.
2. Log the player input and facing direction for clarity:
Add debug before bhop assignment:
csharp
Debug.Log($"Input Horizontal: {input.hor}, Player forward: {pb.transform.forward}, Player right: {pb.transform.right}");
This will confirm how the right vector is oriented.
3. You may also cap or tame the boost to avoid too large velocity:
User
show the whole code
Assistant
Certainly! Below is an example of the complete, integrated AuthorativeInput method including:
Bunny hop velocity applied on jump left/right
Reading boost and decay amounts from inspector fields
Debug logs to trace bunny hop velocity and player horizontal speed
Make sure you have the following in your Kit_Movement_BootsOnGround class:
csharp
[Header("Bunny Hopping Settings")]
[Tooltip("Speed boost amount horizontally added on bunny hop jump left or right.")]
public float bunnyHopBoostAmount = 4f;
[Tooltip("How fast does the bunny hop boost decay when in air.")]
public float bunnyHopDecaySpeed = 4f;
Full AuthorativeInput method snippet integrating bunny hopping with debug logs:
Great! The new bunny hop velocity (6.47, 0.00, -4.70) shows a more reasonable magnitude and horizontal direction after projecting transform.right onto the horizontal plane and normalizing.
Final summary & recommendation for your bunny hopping velocity integration:
Use this exact snippet inside your jump input logic (replace your current bhop velocity calculation):
csharp
if (Mathf.Abs(input.hor) > 0.3f)
{
// Get horizontal right vector (flattened Y)
Vector3 rightHoriz = pb.transform.right;
rightHoriz.y = 0;
rightHoriz.Normalize();
Vector3 sideDir = input.hor > 0 ? rightHoriz : -rightHoriz;
data.bhopVelocity = sideDir * bunnyHopBoostAmount;
Debug.Log($"Bunny hop velocity set to: {data.bhopVelocity}");
Debug.DrawRay(pb.transform.position, data.bhopVelocity.normalized * 3f, Color.cyan, 1f);
}
else
{
data.bhopVelocity = Vector3.zero;
}
This ensures the sideways boost is strictly horizontal aligned with your player's facing direction but no up/down skew.
bunnyHopBoostAmount can be adjusted in inspector (try values like 6-10 for clear but controllable boost).
The debug ray helps you visualize the exact direction and magnitude of the bunny hop in the Scene view during play.
What to expect next:
When jumping left or right while moving, your player will get a noticeable horizontal velocity boost in that direction.
The boost fades smoothly in air based on your bunnyHopDecaySpeed.
Your player will "slide" faster sideways on bunny hops.
If you want, I can help you with further improvements like adding a UI speed display or refining air control, just ask!
Bunny hop velocity set to: (-7.97, 0.00, 0.73)
Bunny hop velocity set to: (-2.55, 0.00, -7.58)
show the bunny hop velocity updating with different directions and magnitudes each jump, which is expected and means your code responds correctly to player input and facing.
What this indicates:
When pressing jump with left/right input, you get a smooth, mostly horizontal vector that reasonably represents the sideways boost in world space.
Variations in values reflect different facing angles or input intensities during the jump.
The Y component remains zero, keeping velocity horizontal — good.
If the bunny hop feels right but you want to improve or tune:
Tweak bunnyHopBoostAmount — values between 5 and 15 often give good speed boosts without overpowering control.
Check your physics and friction settings in your CharacterController and environment — heavy drag or collision settings can reduce visible effect.
Verify air control settings in your movement script — strong air control can help maintain or enhance bhop momentum.
Next step: Visual confirmation & feel
To really know if it's working as intended:
Hold strafe-left or strafe-right and jump repeatedly.
Your horizontal velocity should spike each time you jump while moving sideways, making your movement feel speedier and more fluid in-air.
Use the cyan debug ray (from the previous snippet) in the Scene view to watch the direction of bunny hop velocity visually.
Final recommended bhop assignment snippet (for clarity):
Your bhop velocity values look appropriate and dynamic.
The effect should be seen as added lateral speed on jump with left/right movement.
Visual debugging in Scene view and tuning bunnyHopBoostAmount will help reach your desired feel.
Feel free to ask if you want help with refining the feel, adding UI displays, or otherwise enhancing the bunny hopping!
User
does quake 3 get faster speed when moving left or right without jumping?
Assistant
In Quake 3 Arena, simply moving left or right (strafing) without jumping does not increase your player speed beyond the base movement speed. The increased speed—commonly referred to as "strafe-jumping" or bunny hopping"—is achieved by combining strafing with jumping and specific mouse movement techniques.
Details:
Walking/Running Left or Right Alone:
You move at your standard walk or run speed with no built-in speed increase for strafing on the ground. Strafing left/right on the ground just changes your direction of movement at normal speed.
Speed Gain Comes from Strafe-Jumping:
Strafe-jumping requires:
Jumping while moving forward.
Strafing left or right simultaneously.
Moving your mouse smoothly in the strafe direction during the jump.
This combined input adds velocity vectors due to the way the game handles acceleration, allowing you to gain speed beyond the normal running speed.
Bunny Hopping:
Bunny hopping in Quake 3 is essentially repeatedly performing strafe jumps without losing speed upon landing by timing the jumps perfectly and maintaining momentum, leading to faster movement across the map.
Summary:
No speed boost just from strafing while grounded without jumping.
Speed boost only achieved through strafe-jumping / bunny hopping which involves jumping + strafing + mouse movement combined.
If you want to mimic Quake 3 style bunny hopping movement, your system should increase horizontal velocity when jumping sideways (with or without mouse turn input), not just when strafing on the ground. This matches what you are trying to implement with the bunny hop velocity boost on jump left/right.
If you want some tips or code examples on implementing Quake 3 style strafe-jumping + mouse movement style bunny hopping feel, I can help with that too!
User
analyze the script:
using Mirror;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Random = UnityEngine.Random;
namespace MarsFPSKit
{
///
/// Helper class for Footsteps
///
[Serializable]
public class Footstep
{
///
/// Sounds for this footstep material
///
public AudioClip[] clips;
///
/// Max audio distance for this footstep material
///
public float maxDistance = 20f;
///
/// Audio rolloff for this footstep material
///
public AnimationCurve rollOff = AnimationCurve.EaseInOut(0f, 1f, 20f, 0f);
}
code
Assistant
You're working with a fairly complete and realistic "BootsOnGround" movement system, with walking, sprinting, crouching, jumping, stamina, swimming, fall damage, etc.
To make movement even faster and more responsive for a fast-paced FPS game (similar to Quake, Unreal, or Apex), consider the following changes in this system:
1. Increase base speeds
Adjust these values upward to push overall speed higher:
csharp
public float sprintSpeed = 9f; // from 6f+
public float walkSpeed = 7f; // from 6f+
public float crouchSpeed = 5f; // adjust accordingly if desired
public float jumpSpeed = 10f; // stronger jump impulse
Make sure jumpSpeed is enough to feel floaty and give better air time for mobility.
2. Enhance Air Control
Currently, air control seems limited or disabled (airControlEnabled = false by default). For fast-paced movement:
Set:
csharp
public bool airControlEnabled = true;
public bool airControlSprintControl = true; // to allow sprinting mid-air
Smooth and amplify air control by increasing the responsiveness like:
csharp
// When not grounded, allow input to significantly influence velocity in the air
// Consider increasing swimmingInputLerpSpeed equivalent for movement acceleration/response
You might want to multiply air control effect by a factor (e.g., 1.5x or 2x) to make it more responsive.
3. Implement and increase Bunny Hopping / Strafe Jumping
You already have a bunny hopping velocity boost in AuthorativeInput:
csharp
User
analyze the script again.
I have this:
// Apply JumpPad velocity if set
if (data.jumpPadVelocity != Vector3.zero)
{
data.moveDirection = data.jumpPadVelocity;
data.jumpPadVelocity = Vector3.zero; // Reset after use
Debug.Log("[BootsOnGround] JumpPad velocity applied.");
}
How to create a jumppad like in quake 3 arena and to be 100% compatible with this
Assistant
You currently have a snippet that handles a JumpPad velocity boost:
csharp
// Apply JumpPad velocity if set
if (data.jumpPadVelocity != Vector3.zero)
{
data.moveDirection = data.jumpPadVelocity;
data.jumpPadVelocity = Vector3.zero; // Reset after use
Debug.Log("[BootsOnGround] JumpPad velocity applied.");
}
This means your movement system supports an external velocity override applied once per server tick or frame.
How to implement a Quake 3 Arena-style jump pad compatible with this system
1. What is a Quake 3 jump pad?
A jump pad in Q3 applies a one-time, instantaneous velocity boost to a player — launching them along a specific direction (usually upward with some forward push).
The boost overrides or adds to the current player velocity on contact.
The player’s velocity is then handled normally by physics and input afterward.
2. How to create a jump pad compatible with your system:
Because your system uses data.jumpPadVelocity as a single-frame velocity override applied next movement update, you need a component or script for your jump pad trigger that:
Detects player collision
On collision, sets jumpPadVelocity on that player’s movement network data
Sets it to the launch velocity vector (direction + speed)
3. Sample approach
Step A: Create a JumpPad trigger collider
Add a trigger collider (e.g., box or sphere) in your map where you want the jump pad.
Step B: Create JumpPad script attached to that collider
Example in C#:
csharp
User
show the whole script for the advanced jumppad
Assistant
Certainly! Below is a complete advanced JumpPad Unity C# script designed to work seamlessly with your existing Kit_Movement_BootsOnGround movement system. It applies a launch velocity to players entering the trigger, in the configured direction and speed, compatible with your jumpPadVelocity logic.
AdvancedJumpPad.cs
csharp
using UnityEngine;
using MarsFPSKit;
[RequireComponent(typeof(Collider))]
public class AdvancedJumpPad : MonoBehaviour
{
[Header("JumpPad Settings")]
[Tooltip("Local direction of launch (relative to JumpPad transform). Should be normalized or will be normalized automatically.")]
public Vector3 launchDirection = new Vector3(0f, 1f, 1f); // Default angled upwards forward
[Tooltip("Launch speed multiplier")]
public float launchSpeed = 20f;
[Tooltip("Minimum time between jump pad activations per player (seconds)")]
public float cooldownTime = 1f;
// Keep track of last applied time per player to avoid spam
private System.Collections.Generic.Dictionary<uint, float> lastAppliedTime = new System.Collections.Generic.Dictionary<uint, float>();
private void Reset()
{
// Ensure collider is trigger
Collider col = GetComponent<Collider>();
if (col)
col.isTrigger = true;
}
private void OnTriggerEnter(Collider other)
{
Kit_PlayerBehaviour pb = other.GetComponent<Kit_PlayerBehaviour>();
if (pb == null) return;
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (data == null) return;
uint playerNetId = pb.netId;
// Check cooldown to prevent repeated velocity application
if (lastAppliedTime.TryGetValue(playerNetId, out float lastTime))
{
if (Time.time < lastTime + cooldownTime)
return; // Not yet cooled down, ignore
}
// Calculate launch velocity in world space
Vector3 launchVel = transform.rotation * launchDirection.normalized * launchSpeed;
// Apply launch velocity to player movement data
data.jumpPadVelocity = launchVel;
Debug.Log($"[JumpPad] Applied velocity {launchVel} to player {playerNetId}");
// Record time of application
lastAppliedTime[playerNetId] = Time.time;
}
}
Not yet included in a published release.
Step 2: Modify jump logic to add bunny hop speed boost
Around where jump happens in the grounded case:
Find this in AuthorativeInput inside grounded jump code (simplified):
Add detect if player is moving left on jump (input.hor < -0.3f), and boost velocity accordingly:
csharp
if (input.jump)
{
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
// Bunny hop on jump left
if (input.hor < -0.3f)
{
// Calculate a leftward boost relative to player transform
Vector3 leftDir = -pb.transform.right;
float bhopBoostAmount = 4f; // tune this to desired bunny hop speed boost
// Add to bhopVelocity instead of directly modifying moveDirection
data.bhopVelocity = leftDir * bhopBoostAmount;
}
else
{
// Reset bhop velocity if not jumping left
data.bhopVelocity = Vector3.zero;
}
// other jump-related code ...
}
}
}
Step 3: Add bunny hop velocity application in-air
Inside the air control block (the else after grounded check) where you assign and apply moveDirection and gravity, do this:
Right after the moveDirection is calculated, add the bhopVelocity (which is a Vector3 horizontal addition), and decay the bhopVelocity to zero every frame:
csharp
else
{
// existing air logic or jumping multiple jump logic...
// Apply bunny hop velocity addition here
// Only apply horizontal bunny hop velocity, don't override y velocity
Vector3 horizontalMove = new Vector3(data.moveDirection.x, 0f, data.moveDirection.z);
horizontalMove += data.bhopVelocity;
// Clamp horizontal speed so it doesn't grow infinitely
float maxBhopSpeed = walkSpeed * 1.5f; // max bunny hop speed, tune as desired
horizontalMove = Vector3.ClampMagnitude(horizontalMove, maxBhopSpeed);
data.moveDirection.x = horizontalMove.x;
data.moveDirection.z = horizontalMove.z;
// Decay bhop velocity over time (air resistance)
data.bhopVelocity = Vector3.Lerp(data.bhopVelocity, Vector3.zero, bhopDecaySpeed * delta);
// existing gravity and movement code...
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
// etc...
}
Step 4: Optional - enhance air control for bunny hopping
If you want stronger air control while bunny hopping, you can also adjust the bunny hop velocity based on player input while airborne (e.g., nudging left while in air increases bhopVelocity).
This is optional and more complex, but for now this basic boost + decay will emulate bunny hopping momentum.
Summary of changes to AuthorativeInput:
Add a bhopVelocity Vector3 to player movement data (Kit_Movement_BootsOnGroundNetworkData).
On jump when moving left (input.hor < -0.3), set bhopVelocity to left * boost amount.
While airborne, add bhopVelocity to horizontal velocity and gradually decay it.
Clamp speed to avoid runaway velocity.
Example patched snippet inside AuthorativeInput (very simplified):
csharp
public override void AuthorativeInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta, double revertTime)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
// Other code...
if (pb.cc.isGrounded || airControlEnabled && !data.wasSwimming)
{
float yMovement = data.moveDirection.y;
// Input processing, grounded movement...
#region Jump
if (data.jumpCount > 0)
{
// landed reset jumpCount
data.jumpCount = 0;
data.isJumping = false;
}
if (pb.canControlPlayer)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
if (input.jump)
{
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
// Bunny hop left jump speed boost
if (input.hor < -0.3f)
{
Vector3 leftDir = -pb.transform.right;
float bhopBoostAmount = 4f; // tune this number
data.bhopVelocity = leftDir * bhopBoostAmount;
}
else
{
data.bhopVelocity = Vector3.zero;
}
// existing jump sound/animation/stamina code...
data.jumpCount = 1;
// spawn protection code...
// stamina cost code...
}
}
else if (data.state == 1)
{
// crouching jump makes player stand up
data.state = 0;
}
}
}
}
#endregion
// other grounded movement and height logic...
// Apply gravity
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
// Move character controller
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
// store velocity and grounded flag like original code
data.velocity = pb.cc.velocity;
data.isGrounded = pb.cc.isGrounded;
}
else
{
// Airborne control and multiple jump logic here...
// Assume data.moveDirection.x and z is set from input or previous frame
// Add bunny hop velocity to moveDirection horizontal movement
Vector3 horizontalMove = new Vector3(data.moveDirection.x, 0f, data.moveDirection.z);
horizontalMove += data.bhopVelocity;
float maxBhopSpeed = walkSpeed * 1.5f; // max speed tuning
horizontalMove = Vector3.ClampMagnitude(horizontalMove, maxBhopSpeed);
data.moveDirection.x = horizontalMove.x;
data.moveDirection.z = horizontalMove.z;
// Decay bunny hop velocity
data.bhopVelocity = Vector3.Lerp(data.bhopVelocity, Vector3.zero, 4f * delta);
// Apply gravity again
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
data.velocity = pb.cc.velocity;
data.isGrounded = pb.cc.isGrounded;
}
// Rest of AuthorativeInput code...
}
Final tuning notes
Adjust bhopBoostAmount and maxBhopSpeed to get desired bunny hopping feel.
You can further modify to apply bunny hopping boost in other directions if you want (e.g., backward or right).
Optionally add some visual/sound feedback on bunny hop boosts for more player gratification.
If you want, I can help integrate this directly line-by-line in your full script or adjust for multiple directions or air control. Let me know!
In-air velocity addition and decay (unchanged from before):
In airborne logic:
csharp
// Add bunny hop velocity to horizontal move direction
Vector3 horizontalMove = new Vector3(data.moveDirection.x, 0f, data.moveDirection.z);
horizontalMove += data.bhopVelocity;
// Clamp speed
float maxBhopSpeed = walkSpeed * 1.5f; // tune this
horizontalMove = Vector3.ClampMagnitude(horizontalMove, maxBhopSpeed);
data.moveDirection.x = horizontalMove.x;
data.moveDirection.z = horizontalMove.z;
// Decay bhop velocity
data.bhopVelocity = Vector3.Lerp(data.bhopVelocity, Vector3.zero, 4f * delta);
// Gravity and movement code...
Summary:
Any time player jumps with horizontal input stronger than 0.3 (left or right),
Set bhopVelocity in that direction for horizontal speed boost,
While airborne, add and gradually decay bhopVelocity to your current horizontal move velocity.
Let me know if you want the complete patch applied into your full script or any refinements!
AFTER: modify jump logic to add bunny hop velocity on jumping left or right
csharp
if (pb.canControlPlayer)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
// Get Jump input
if (input.jump)
{
// Check if we can jump
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
// === BUNNY HOPPING ADDITION START ===
if (Mathf.Abs(input.hor) > 0.3f)
{
Vector3 sideDir = input.hor > 0 ? pb.transform.right : -pb.transform.right;
float bhopBoostAmount = 4f; // tune speed boost value
data.bhopVelocity = sideDir * bhopBoostAmount;
}
else
{
data.bhopVelocity = Vector3.zero;
}
// === BUNNY HOPPING ADDITION END ===
if (pb.isServer)
{
// Play Animation and Jump Sound
pb.RpcMovementPlayAnimation(0, data.jumpCount);
pb.RpcMovementPlaySound(1, data.jumpCount, Random.Range(0, jumpSound[data.jumpCount].clips.Length));
}
data.jumpCount = 1;
// Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= jumpStaminaCost;
if (data.staminaLeft <= 0f)
{
// stamina depleted logic...
}
else
{
// stamina regeneration timing...
}
}
}
}
else if (data.state == 1)
{
// if crouching, stand up
data.state = 0;
}
}
}
}
2. In the 'in air' movement code, apply bhopVelocity and decay
Before: (your existing in-air movement inside else block after checking grounded)
csharp
else
{
// Save initial falling point if needed
// Additional jump logic for multiple jumps or normal air move logic already in place...
// Existing moveDirection processing, gravity application...
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
// set localMoveDirection, velocity, grounded flags etc.
}
After: (add bhopVelocity application before gravity and move)
csharp
else
{
// Save initial falling point if needed
// Additional jump logic for multiple jumps or normal air move logic already in place...
// Add bunny hop velocity to horizontal movement
Vector3 horizontalMove = new Vector3(data.moveDirection.x, 0f, data.moveDirection.z);
horizontalMove += data.bhopVelocity;
// Clamp horizontal speed so it doesn't exceed max
float maxBhopSpeed = walkSpeed * 1.5f; // tune this value
horizontalMove = Vector3.ClampMagnitude(horizontalMove, maxBhopSpeed);
// Update moveDirection horizontal components
data.moveDirection.x = horizontalMove.x;
data.moveDirection.z = horizontalMove.z;
// Decay bhop velocity smoothly
float bhopDecaySpeed = 4f; // decay speed can be class variable or local value
data.bhopVelocity = Vector3.Lerp(data.bhopVelocity, Vector3.zero, bhopDecaySpeed * delta);
// Then apply gravity and move
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
// Update localMoveDirection, velocity, grounded, etc... as before
}
3. Additional note
Make sure you have added bhopVelocity to your Kit_Movement_BootsOnGroundNetworkData class, like:
csharp
[NonSerialized] public Vector3 bhopVelocity = Vector3.zero;
Summary where to add stuff
Location
What to add
Grounded jump input (inside if (input.jump))
Add conditional setting of data.bhopVelocity based on horizontal input (step #1)
Airborne movement handling (else block after grounded check)
Add data.bhopVelocity to horizontal move direction and decay it (step #2)
If you want me to generate a full patched method with these integrated, just say so! Otherwise you can copy/paste the added parts exactly where I showed above.
[SyncVar(hook = "OnServerPositionChanged")]
public Vector3 serverPosition;
[SyncVar]
public Quaternion serverRotation;
[SyncVar]
/// <summary>
/// Are we grounded?
/// </summary>
public bool isGrounded;
[SyncVar]
/// <summary>
/// Velocity
/// </summary>
public Vector3 velocity;
[SyncVar]
/// <summary>
/// The character state.
/// <para>0 = Standing</para>
/// <para>1 = Crouching</para>
/// <para>2 = Prone (not implemented right now.)</para>
/// <para>3 = Swimming</para>
/// </summary>
public int state;
/// <summary>
/// Helper bool to see if we're currently swimming
/// </summary>
public bool isSwimming
{
get
{
return state == 3;
}
}
[SyncVar]
/// <summary>
/// Are we underwater?
/// </summary>
public bool isUnderwater;
[SyncVar]
/// <summary>
/// How much air do we have left?
/// </summary>
public float airLeft = 100f;
/// <summary>
/// When do we take the next damage?
/// </summary>
public float nextAirDamageAppliedAt;
/// <summary>
/// Current
/// </summary>
public Kit_SwimmingTrigger swimmingCurrent;
/// <summary>
/// When was the last swimming sound played?
/// </summary>
public float lastSwimmingSoundPlayed;
/// <summary>
/// Did we jump and have not been grounded since?
/// </summary>
public bool isJumping;
/// <summary>
/// How many times have we jumped since last ground?
/// </summary>
public int jumpCount;
[SyncVar]
/// <summary>
/// Are we currently sprinting?
/// </summary>
public bool isSprinting;
/// <summary>
/// Were we swimming (true until grounded)
/// </summary>
public bool wasSwimming;
/// <summary>
/// Slot of swimming weapon :)
/// </summary>
public int swimmingWeaponSlot;
/// <summary>
/// This is where we return afterwards!
/// </summary>
public int swimmingPreviousWeaponSlot;
[SyncVar]
/// <summary>
/// Material type for footsteps
/// </summary>
public string currentMaterial;
/// <summary>
/// When can we make our next footstep?
/// </summary>
public float nextFootstep;
/// <summary>
/// Should we play slow (aiming) walk animation?
/// </summary>
public bool playSlowWalkAnimation;
#region Fall Damage
/// <summary>
/// Are we falling?
/// </summary>
public bool falling;
/// <summary>
/// How far have we fallen?
/// </summary>
public float fallDistance;
/// <summary>
/// From where did we fall?
/// </summary>
public float fallHighestPoint;
#endregion
#region Stamina
[SyncVar]
/// <summary>
/// Our currently left stamina
/// </summary>
public float staminaLeft = 100f;
/// <summary>
/// After which time can we regenerate stamina?
/// </summary>
public float staminaRegenerationTime = 0f;
/// <summary>
/// If <see cref="Time.time"/> is smaller than this, sprinting is blocked because stamina is depleted
/// </summary>
public float staminaDepletedSprintingBlock;
#endregion
public Vector3 refVelocity;
public Vector3 desiredMoveDirection = Vector3.zero;
public Vector3 swimmingWorldMoveDirection = Vector3.zero;
public Vector3 moveDirection = Vector3.zero;
/// <summary>
/// The local movement direction
/// </summary>
public Vector3 localMoveDirection = Vector3.zero;
/// <summary>
/// Last state of the crouch input
/// </summary>
public bool lastCrouch = false;
/// <summary>
/// Last state of the jump input
/// </summary>
public bool lastJump = false;
/// <summary>
/// Our historical posititons
/// </summary>
public List<Vector3> historicalPositions;
/// <summary>
/// When was the last position set
/// </summary>
public float historyLastPositionSetAt;
public int amountOfSnapShots = 10;
public Kit_PlayerBehaviour myPlayer;
public Kit_Movement_BootsOnGround bogrd;
public int snapShotCalculated;
public Vector3 deltaToServer;
public float compareToTime = 0.6f;
/// <summary>
/// Velocity boost added by external sources such as jump pads. Applied once then reset.
/// </summary>
///
[System.NonSerialized]
public Vector3 jumpPadVelocity = Vector3.zero;
public void OnServerPositionChanged(Vector3 was, Vector3 isNow)
{
if (!myPlayer)
{
if (isServer)
{
if (NetworkServer.spawned.ContainsKey(ownerPlayerNetworkId))
myPlayer = NetworkServer.spawned[ownerPlayerNetworkId].GetComponent<Kit_PlayerBehaviour>();
}
else
{
if (NetworkClient.spawned.ContainsKey(ownerPlayerNetworkId))
myPlayer = NetworkClient.spawned[ownerPlayerNetworkId].GetComponent<Kit_PlayerBehaviour>();
}
}
else
{
if (!bogrd)
{
bogrd = myPlayer.movement as Kit_Movement_BootsOnGround;
}
bogrd.OnServerPositionReceived(myPlayer, isNow);
}
}
}
}
Where exactly to add the new inspector bunny hopping fields?
Inside your Kit_Movement_BootsOnGround class near the top among other public fields, for example:
csharp
[Header("Bunny Hopping Settings")]
[Tooltip("Speed boost amount horizontally added on bunny hop jump left or right.")]
public float bunnyHopBoostAmount = 4f;
[Tooltip("How fast does the bunny hop boost decay when in air.")]
public float bunnyHopDecaySpeed = 4f;
Summary:
Add two new public float fields to expose bunny hop boost speed and decay speed in inspector.
Replace the hardcoded values in AuthorativeInput with these.
You get easy tuning in Unity inspector at runtime or per movement profile.
If you want, I can prepare a fully integrated diff with these changes inside your complete Kit_Movement_BootsOnGround script!
If you see logs but no visual movement change:
The data.bhopVelocity might be getting overwritten somewhere else.
The character controller might cap horizontal velocity preventing visible effect.
What exactly you press:
Action
Key(s)
Move Left
Hold A
Move Right
Hold D
Jump
Press Spacebar
Simultaneously Move + Jump
Hold A or D + press Space
Expected behavior after pressing:
When you jump while moving left or right, your character gets a noticeable sideways speed addition in the jump direction.
You should feel like the player "bounces" off sideways faster than a normal jump without the boost.
The boost gradually fades out in the air (over approx 1 second depending on bunnyHopDecaySpeed).
If still no effect:
Double-check the movement update code that applies and decays bhopVelocity, it must run every frame while airborne.
Ensure your input system correctly maps horizontal axis to input.hor—some setups may use different input names.
Test with a simpler setup by temporarily printing out player velocity magnitude after adding bhopVelocity.
You might add a temporary visual indicator or speed display on UI to verify velocity changes.
Summary for simple test:
Hold Left or Right movement key.
Press Jump while holding that key.
Look for added horizontal speed and "slide" in that direction in midair.
If you want, I can help you with adding debug UI or code to display current horizontal speed values so you can verify the bunny hop boost is working.
Also verify that bhopVelocity is actually added tomoveDirection each frame during airborne movement and moveDirection is then applied via cc.Move(...).
If you want, I can help you create a small debug UI overlay or modify your code to display horizontal speed in the game view to better feel bunny hopping effect. Would that help?
public override void AuthorativeInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta, double revertTime)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
// Swimming branch omitted for clarity, only Boots on Ground portion shown below
if (pb.cc.isGrounded || airControlEnabled && !data.wasSwimming)
{
float yMovement = data.moveDirection.y;
#region Main Input
if (pb.canControlPlayer)
{
// Calculate move direction based on input
data.moveDirection.x = input.hor;
data.moveDirection.y = 0f;
data.moveDirection.z = input.ver;
data.moveDirection = Vector3.ClampMagnitude(data.moveDirection, 1f);
if (pb.cc.isGrounded)
data.moveDirection.y = defaultYmove;
else
data.moveDirection.y = 0f;
// Sprinting logic omitted for brevity...
// Other grounded input processing...
}
else
{
data.moveDirection = new Vector3(0f, defaultYmove, 0f);
data.isSprinting = false;
}
#endregion
// Convert moveDirection from local to world space
data.moveDirection = pb.transform.TransformDirection(data.moveDirection);
// Apply speed based on state
if (data.state == 0)
{
if (data.isSprinting)
{
data.moveDirection *= sprintSpeed;
}
else
{
data.moveDirection *= walkSpeed;
}
}
else if (data.state == 1)
{
data.moveDirection *= crouchSpeed;
}
if (!pb.cc.isGrounded)
{
data.moveDirection.y = yMovement;
}
else
{
data.moveDirection *= pb.looking.GetSpeedMultiplier(pb);
data.moveDirection *= pb.weaponManager.CurrentMovementMultiplier(pb);
data.playSlowWalkAnimation = pb.weaponManager.IsAiming(pb);
}
#region Jump Input
if (data.jumpCount > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(2, data.jumpCount - 1, Random.Range(0, jumpLandSound[data.jumpCount - 1].clips.Length));
}
data.jumpCount = 0;
data.isJumping = false;
}
if (pb.canControlPlayer)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
if (input.jump)
{
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
// ** BUNNY HOP VELOCITY SETTING **
if (Mathf.Abs(input.hor) > 0.3f)
{
Vector3 sideDir = input.hor > 0 ? pb.transform.right : -pb.transform.right;
float bhopBoostAmount = bunnyHopBoostAmount;
data.bhopVelocity = sideDir * bhopBoostAmount;
Debug.Log($"Bunny hop velocity set to: {data.bhopVelocity}");
Debug.Log($"Input Horizontal: {input.hor}, Player Right: {pb.transform.right}");
}
else
{
data.bhopVelocity = Vector3.zero;
}
if (pb.isServer)
{
pb.RpcMovementPlayAnimation(0, data.jumpCount);
pb.RpcMovementPlaySound(1, data.jumpCount, Random.Range(0, jumpSound[data.jumpCount].clips.Length));
}
data.jumpCount = 1;
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= jumpStaminaCost;
if (data.staminaLeft <= 0f)
{
data.staminaRegenerationTime = Time.time + staminaPauseRateEmpty;
data.staminaDepletedSprintingBlock = Time.time + staminaDepletedSprintBlockTime;
if (staminaExhaustedSound.Length > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(0, 0, Random.Range(0, staminaExhaustedSound.Length));
}
}
}
else
{
data.staminaRegenerationTime = Time.time + staminaPauseRateNotEmpty;
}
}
}
}
else if (data.state == 1)
{
data.state = 0;
}
}
}
}
#endregion
// Character height and other grounded logic omitted for brevity...
// Gravity application before Move
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
// Apply jump pad velocity (existing code)
if (data.jumpPadVelocity != Vector3.zero)
{
data.moveDirection = data.jumpPadVelocity;
data.jumpPadVelocity = Vector3.zero;
}
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
data.localMoveDirection = pb.transform.InverseTransformDirection(pb.cc.velocity);
data.isGrounded = pb.cc.isGrounded;
data.velocity = pb.cc.velocity;
if (collision.HasFlag(CollisionFlags.Above))
{
if (data.moveDirection.y > 0f)
{
data.moveDirection.y = -data.moveDirection.y;
}
}
}
else
{
// === AIRBORNE MOVEMENT ===
// Save falling point logic omitted for brevity...
// Air control / multi-jump logic omitted...
// Add bhop velocity to horizontal movement:
Vector3 horizontalMove = new Vector3(data.moveDirection.x, 0f, data.moveDirection.z);
horizontalMove += data.bhopVelocity;
float maxBhopSpeed = walkSpeed * 1.5f;
horizontalMove = Vector3.ClampMagnitude(horizontalMove, maxBhopSpeed);
data.moveDirection.x = horizontalMove.x;
data.moveDirection.z = horizontalMove.z;
// Decay bhop velocity using inspector decay value
data.bhopVelocity = Vector3.Lerp(data.bhopVelocity, Vector3.zero, bunnyHopDecaySpeed * delta);
// Debug current horizontal velocity magnitude for clarity
Vector3 horizontalVelocity = new Vector3(pb.cc.velocity.x, 0, pb.cc.velocity.z);
Debug.Log($"Player horizontal velocity magnitude: {horizontalVelocity.magnitude}");
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
data.localMoveDirection = pb.transform.InverseTransformDirection(pb.cc.velocity);
data.isGrounded = pb.cc.isGrounded;
data.velocity = pb.cc.velocity;
}
// Camera positioning and stamina regen omitted for brevity...
if (pb.isServer)
{
data.serverPosition = pb.transform.position;
data.serverRotation = pb.transform.rotation;
}
}
Notes:
Replace your current AuthorativeInput method with this or merge the bunny hop parts into your existing code.
Adjust bunnyHopBoostAmount & bunnyHopDecaySpeed in inspector to tune the bunny hop feel.
The Debug.Log lines will output useful info in the Unity console to confirm bunny hop velocity is applied and how it affects actual velocity.
Remember to hold left or right movement key and press jump simultaneously to see the velocity boost effect.
If you want me to also help with the whole class or explain any part, just ask!
This will draw a cyan line from player position showing the direction of your bunny hop velocity in the editor scene view for 1 second on every jump.
Option 2: Project bhopVelocity onto pure X or Z axis
If you want purely left/right boost on world axes ignoring player rotation, you can change your code from using transform.right to pure world axis:
Replace your bhop velocity calculation with above to guarantee purely horizontal side boost.
Press move left/right + jump, watch in Scene view for cyan arrow on every jump to confirm direction.
Tune bunnyHopBoostAmount for desired speed.
Let me know if you want me to generate the whole fixed method part!
[Serializable]
public class StringFootstepDictionary : SerializableDictionary<string, Footstep> { }
[Serializable]
public class NestedSound
{
public AudioClip[] clips;
}
[CreateAssetMenu(menuName = "MarsFPSKit/Movement/Boots on ground")]
public class Kit_Movement_BootsOnGround : Kit_MovementBase
{
[Header("Bunny Hopping Settings")]
[Tooltip("Speed boost amount horizontally added on bunny hop jump left or right.")]
public float bunnyHopBoostAmount = 4f;
[Tooltip("How fast does the bunny hop boost decay when in air.")]
public float bunnyHopDecaySpeed = 4f;
[Header("Stats")]
[Tooltip("Sprinting speed")]
public float sprintSpeed = 6f;
[Tooltip("Normal walk speed")]
public float walkSpeed = 6f;
[Tooltip("Crouch walk speed")]
public float crouchSpeed = 6f;
/// <summary>
/// If this is set to true, we can move while we are not grounded
/// </summary>
public bool airControlEnabled = false;
/// <summary>
/// Air control can control sprint?
/// </summary>
public bool airControlSprintControl = true;
[Tooltip("Multiplier that is applied to Physics.gravity for the character controller")]
/// <summary>
/// Multiplier for Physics.gravity
/// </summary>
public float gravityMultiplier = 1f;
[Tooltip("The speed that is applied when you try to jump")]
public float jumpSpeed = 8f;
/// <summary>
/// How many times can we jump
/// </summary>
[Tooltip("How many times can we jump?")]
public int jumpMaxCount = 1;
[Tooltip("How much stamina does the jump cost?")]
/// <summary>
/// How much stamina does the jump cost?
/// </summary>
public float jumpStaminaCost = 10f;
/// <summary>
/// Which jump animation to play for a certain jump count?
/// </summary>
public string[] jumpAnimations;
/// <summary>
/// Which jump sound to play for a certain jump?
/// </summary>
public NestedSound[] jumpSound;
/// <summary>
/// Which land sound to play for a certain jump?
/// </summary>
public NestedSound[] jumpLandSound;
[Header("Character Heights")]
public float standHeight = 1.8f; //State 0 height
public float crouchHeight = 1.2f; //State 1 height
[Header("Camera Positions")]
public float camPosSmoothSpeed = 6f; //The lerp speed of changing the camera position
public Vector3 camPosStand = new Vector3(0, 1.65f, 0f);
public Vector3 camPosCrouch = new Vector3(0, 1.05f, 0f);
[Header("Fall Damage")]
/// <summary>
/// After how many units of falling will we take damage?
/// </summary>
public float fallDamageThreshold = 10;
/// <summary>
/// With which value will the fall damage be multiplied with?
/// </summary>
public float fallDamageMultiplier = 5f;
[Header("Others")]
[Tooltip("How many units should we be moved down by default? To be able to walk down stairs properly")]
public float defaultYmove = -2f; //How many units should we be moved down by default? To be able to walk down stairs properly
[Header("Footsteps")]
public float footstepsRunTime = 0.25f; //Time between footsteps when we're running
public float footstepsWalkTime = 0.4f; //Time between footsteps when we're standing
public float footstepsCrouchTime = 0.7f; //Time between footsteps when we're crouching
public float footstepsRunVolume = 0.8f; //Volume for footsteps when we're running
public float footstepsWalkVolume = 0.4f; //Volume for footsteps when we're walking
public float footstepsCrouchVolume = 0.1f; //Volume for footsteps when we're crouching
public StringFootstepDictionary allFootsteps; //All footstep materials
[Header("Fall Down effect")]
public float fallDownAmount = 10.0f;
public float fallDownMinOffset = -6.0f;
public float fallDownMaxoffset = 6.0f;
public float fallDownTime = 0.3f;
public float fallDownReturnSpeed = 1f;
/// <summary>
/// Is stamina enabled?
/// </summary>
[Header("Stamina")]
public bool staminaSystemEnabled = true;
/// <summary>
/// How fast will stamina decrease when we are running?
/// </summary>
public float staminaDecreaseRate = 5f;
/// <summary>
/// How fast will stamina increase when we are not running?=
/// </summary>
public float staminaIncreaseRate = 3f;
/// <summary>
/// How long until regen starts when stamina was not depleted?
/// </summary>
public float staminaPauseRateNotEmpty = 2f;
/// <summary>
/// How long until regen starts when stamina was depleted?
/// </summary>
public float staminaPauseRateEmpty = 5f;
/// <summary>
/// How long will sprinting be blocked if stamina was depleted
/// </summary>
public float staminaDepletedSprintBlockTime = 7f;
/// <summary>
/// Sounds that will play when stamina was depleted
/// </summary>
public AudioClip[] staminaExhaustedSound;
/// <summary>
/// How fast do we swim?
/// </summary>
[Header("Swimming")]
public float swimmingSpeed = 4f;
/// <summary>
/// How fast does it react to our input?
/// </summary>
public float swimmingInputLerpSpeed = 1f;
/// <summary>
/// Swimming height
/// </summary>
public float swimmingHeight = 0.6f;
/// <summary>
/// Weapon to select when swimming!
/// </summary>
public Weapons.Kit_WeaponBase swimmingWeapon;
/// <summary>
/// Should we be able to drown?
/// </summary>
public bool swimmingEnableDrowning;
/// <summary>
/// How long does it take to drown?
/// </summary>
public float swimmingDrowningTime = 5f;
/// <summary>
/// How quickly do we recover air?
/// </summary>
public float swimmingDrowningRecoveryTime = 5f;
/// <summary>
/// How much time between drowning
/// </summary>
public Vector2 swimmingDrowningDamageTimes = new Vector2(1, 3);
/// <summary>
/// Damage we take when drowning
/// </summary>
public Vector2 swimmingDrowningDamage = new Vector2(10, 20f);
[Header("Authorative Correction")]
public float history = 1f;
public float deltaMultiplier = 1;
public float teleportDistance = 2f;
public override void InitializeServer(Kit_PlayerBehaviour pb)
{
GameObject data = Instantiate(networkData, Vector3.zero, Quaternion.identity);
Kit_Movement_BootsOnGroundNetworkData nData = data.GetComponent<Kit_Movement_BootsOnGroundNetworkData>();
pb.movementNetworkData = nData;
nData.ownerPlayerNetworkId = pb.netId;
if (pb.isBot)
NetworkServer.Spawn(data);
else
NetworkServer.Spawn(data, pb.gameObject);
}
public override void InitializeClient(Kit_PlayerBehaviour pb)
{
if (!pb.movementNetworkData)
{
//Find ours
pb.movementNetworkData = FindObjectsOfType<Kit_Movement_BootsOnGroundNetworkData>().Where(x => x.ownerPlayerNetworkId == pb.netId).FirstOrDefault();
}
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
bogrd.amountOfSnapShots = Mathf.CeilToInt(history / Time.fixedDeltaTime);
bogrd.historicalPositions = new List<Vector3>(bogrd.amountOfSnapShots);
for (int i = 0; i < bogrd.amountOfSnapShots; i++)
{
bogrd.historicalPositions.Add(pb.transform.position);
}
bogrd.serverPosition = pb.transform.position;
bogrd.serverRotation = pb.transform.rotation;
}
public override void NotControllerUpdate(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Manually sync
pb.transform.position = Vector3.Lerp(pb.transform.position, bogrd.serverPosition, Time.deltaTime * 20f);
pb.transform.rotation = Quaternion.Slerp(pb.transform.rotation, bogrd.serverRotation, Time.deltaTime * 20f);
}
public override void AuthorativeInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta, double revertTime)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Swim logic
if (data.isSwimming)
{
//Reset "ground" bools
data.isGrounded = false;
data.isJumping = false;
data.isSprinting = false;
data.falling = false;
//Adjust CC
pb.cc.height = swimmingHeight; //Set height
pb.cc.center = new Vector3(0f, swimmingHeight / 1.3f, 0f); //Set center
#region Main Input
//Only get input if the cursor is locked
if (pb.canControlPlayer)
{
//Check if we want to move
if (data.isGrounded && data.desiredMoveDirection.sqrMagnitude > 0.005f)
{
//Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
}
if (Mathf.Abs(input.ver) > 0.05f)
{
data.desiredMoveDirection.x = 0f;
data.desiredMoveDirection.y = 0f;
data.desiredMoveDirection.z = input.ver;
//Transform
data.desiredMoveDirection = pb.playerCameraTransform.TransformDirection(data.desiredMoveDirection * swimmingSpeed);
//Add that
data.swimmingWorldMoveDirection += data.desiredMoveDirection * delta * swimmingInputLerpSpeed;
data.swimmingWorldMoveDirection = Vector3.ClampMagnitude(data.swimmingWorldMoveDirection, swimmingSpeed);
}
if (Mathf.Abs(input.hor) > 0.05f)
{
data.desiredMoveDirection.x = input.hor;
data.desiredMoveDirection.y = 0f;
data.desiredMoveDirection.z = 0f;
//Transform
data.desiredMoveDirection = pb.playerCameraTransform.TransformDirection(data.desiredMoveDirection * swimmingSpeed);
//Add that
data.swimmingWorldMoveDirection += data.desiredMoveDirection * delta * swimmingInputLerpSpeed;
data.swimmingWorldMoveDirection = Vector3.ClampMagnitude(data.swimmingWorldMoveDirection, swimmingSpeed);
}
if (Mathf.Abs(input.ver) < 0.05f && Mathf.Abs(input.hor) < 0.05f)
{
data.swimmingWorldMoveDirection = Vector3.Lerp(data.swimmingWorldMoveDirection, Vector3.zero, delta * swimmingInputLerpSpeed);
}
}
//If not, don't move
else
{
data.swimmingWorldMoveDirection = Vector3.Lerp(data.swimmingWorldMoveDirection, Vector3.zero, delta * swimmingInputLerpSpeed);
}
//Move
pb.cc.Move(data.swimmingWorldMoveDirection * delta);
data.moveDirection = pb.cc.velocity;
//Get local movement direction
data.localMoveDirection = pb.playerCameraTransform.InverseTransformDirection(data.moveDirection);
//Velocity
data.velocity = pb.cc.velocity;
#endregion
if (data.isUnderwater)
{
//Check if drowning is enabled
if (swimmingEnableDrowning)
{
if (data.airLeft > 0)
{
data.airLeft -= (100 / swimmingDrowningTime) * delta;
}
else
{
if (Time.time > data.nextAirDamageAppliedAt)
{
if (pb.isServer)
{
//Apply damage
pb.ServerDamage(Random.Range(swimmingDrowningDamage.x, swimmingDrowningDamage.y), "Water", pb.transform.position, Vector3.zero, 0f, pb.transform.position, 0, pb.isBot, pb.id);
}
//Set time
data.nextAirDamageAppliedAt = Time.time + Random.Range(swimmingDrowningDamageTimes.x, swimmingDrowningDamageTimes.y);
}
}
}
}
else
{
if (swimmingEnableDrowning)
{
if (data.airLeft < 100f)
{
data.airLeft += (100 / swimmingDrowningRecoveryTime) * delta;
}
}
}
}
else
{
if (pb.cc.isGrounded || airControlEnabled && !data.wasSwimming)
{
float yMovement = data.moveDirection.y;
#region Main Input
//Only get input if the cursor is locked
if (pb.canControlPlayer)
{
//Calculate move direction based on input
data.moveDirection.x = input.hor;
//if (pb.cc.isGrounded)
data.moveDirection.y = 0f;
data.moveDirection.z = input.ver;
//Check if we want to move
if (data.isGrounded && data.moveDirection.sqrMagnitude > 0.005f)
{
//Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
}
//Correct strafe
data.moveDirection = Vector3.ClampMagnitude(data.moveDirection, 1f);
if (pb.cc.isGrounded)
{
data.moveDirection.y = defaultYmove;
}
else
{
data.moveDirection.y = 0f;
}
if (airControlSprintControl || data.isGrounded)
{
//Get sprinting input
if (input.sprint && data.moveDirection.z > 0.3f && pb.weaponManager.CanRun(pb))
{
//Check if we can sprint
if (data.state == 0 && (!staminaSystemEnabled || staminaSystemEnabled && data.staminaLeft >= 0f && Time.time > data.staminaDepletedSprintingBlock))
{
data.isSprinting = true;
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= delta * staminaDecreaseRate;
if (data.staminaLeft <= 0f)
{
//Stamina is now depleted. Set times
data.staminaRegenerationTime = Time.time + staminaPauseRateEmpty;
data.staminaDepletedSprintingBlock = Time.time + staminaDepletedSprintBlockTime;
//Play sound.
if (staminaExhaustedSound.Length > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(0, 0, Random.Range(0, staminaExhaustedSound.Length));
}
}
}
else
{
//Set time for regen
data.staminaRegenerationTime = Time.time + staminaPauseRateNotEmpty;
}
}
}
//We cannot sprint
else
{
data.isSprinting = false;
}
}
else
{
//We are not sprinting
data.isSprinting = false;
}
}
}
//If not, don't move
else
{
//Reset move direction
data.moveDirection = new Vector3(0f, defaultYmove, 0f);
//Reset sprinting
data.isSprinting = false;
}
#endregion
//Take rotation in consideration (local to world)
data.moveDirection = pb.transform.TransformDirection(data.moveDirection);
//Apply speed based on state
//Standing
if (data.state == 0)
{
//Sprinting
if (data.isSprinting)
{
data.moveDirection *= sprintSpeed;
}
//Not sprinting
else
{
data.moveDirection *= walkSpeed;
}
}
//Crouching
else if (data.state == 1)
{
data.moveDirection *= crouchSpeed;
}
if (!pb.cc.isGrounded)
{
data.moveDirection.y = yMovement;
}
else
{
//Mouse Look multiplier
data.moveDirection *= pb.looking.GetSpeedMultiplier(pb);
//Weapon multiplier
data.moveDirection *= pb.weaponManager.CurrentMovementMultiplier(pb); //Retrive from weapon manager
//Should play slow animation?
data.playSlowWalkAnimation = pb.weaponManager.IsAiming(pb); //Retrive from weapon manager
}
}
//Air recovery
if (swimmingEnableDrowning)
{
if (data.airLeft < 100f)
{
data.airLeft += (100 / swimmingDrowningRecoveryTime) * delta;
}
}
if (pb.cc.isGrounded)
{
#region Fall Damage
if (data.falling)
{
//Calculate distance we have fallen
data.fallDistance = data.fallHighestPoint - pb.transform.position.y;
data.falling = false;
if (data.fallDistance > fallDamageThreshold)
{
//Apply Fall distance multiplied with the multiplier (=Fall Damage)
pb.ApplyFallDamage(data.fallDistance * fallDamageMultiplier);
if (pb.isFirstPersonActive)
{
Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.Kick(pb.playerCameraFallDownTransform, new Vector3(fallDownAmount, Random.Range(fallDownMinOffset, fallDownMaxoffset), 0), fallDownTime));
//Tell weapon manager
pb.weaponManager.FallDownEffect(pb, true);
}
}
else if (data.fallDistance > 0.1f)
{
if (pb.isFirstPersonActive)
{
Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.Kick(pb.playerCameraFallDownTransform, new Vector3(fallDownAmount / 3, Random.Range(fallDownMinOffset, fallDownMaxoffset) / 2, 0), fallDownTime));
//Tell weapon manager
pb.weaponManager.FallDownEffect(pb, false);
}
}
}
#endregion
#region Crouch Input
if (pb.canControlPlayer)
{
if (Kit_GameSettings.isCrouchToggle)
{
if (data.lastCrouch != input.crouch)
{
data.lastCrouch = input.crouch;
//Get crouch input
if (input.crouch)
{
//Change state
if (data.state == 0)
{
//We are standing, crouch
data.state = 1;
}
else if (data.state == 1)
{
//We are crouching, stand up
data.state = 0;
}
}
}
}
else
{
if (input.crouch)
{
data.state = 1;
}
else
{
data.state = 0;
}
data.lastCrouch = input.crouch;
}
}
#endregion
#region Jump
//Reset jump counter
if (data.jumpCount > 0)
{
if (pb.isServer)
{
//We Landed
pb.RpcMovementPlaySound(2, data.jumpCount - 1, Random.Range(0, jumpLandSound[data.jumpCount - 1].clips.Length));
}
data.jumpCount = 0;
data.isJumping = false;
}
if (pb.canControlPlayer)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
//Get Jump input
if (input.jump)
{
//Check if we can jump
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
// === BUNNY HOPPING ADDITION START ===
if(Mathf.Abs(input.hor) > 0.3f)
{
// Get horizontal right vector (flattened Y)
Vector3 rightHoriz = pb.transform.right;
rightHoriz.y = 0;
rightHoriz.Normalize();
code
Vector3 sideDir = input.hor > 0 ? rightHoriz : -rightHoriz;
data.bhopVelocity = sideDir * bunnyHopBoostAmount;
Debug.Log($"Bunny hop velocity set to: {data.bhopVelocity}");
Debug.DrawRay(pb.transform.position, data.bhopVelocity.normalized * 3f, Color.cyan, 1f);
}
// === BUNNY HOPPING ADDITION END ===
if (pb.isServer)
{
//Play Animation and Jump Sound
pb.RpcMovementPlayAnimation(0, data.jumpCount);
pb.RpcMovementPlaySound(1, data.jumpCount, Random.Range(0, jumpSound[data.jumpCount].clips.Length));
}
data.jumpCount = 1;
//Call for spawn protection
if (pb.spawnProtection)
{
pb.spawnProtection.PlayerMoved(pb);
}
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= jumpStaminaCost;
if (data.staminaLeft <= 0f)
{
//Stamina is now depleted. Set times
data.staminaRegenerationTime = Time.time + staminaPauseRateEmpty;
data.staminaDepletedSprintingBlock = Time.time + staminaDepletedSprintBlockTime;
//Play sound.
if (staminaExhaustedSound.Length > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(0, 0, Random.Range(0, staminaExhaustedSound.Length));
}
}
}
else
{
//Set time for regen
data.staminaRegenerationTime = Time.time + staminaPauseRateNotEmpty;
}
}
}
}
//If we try to jump and we try to jump, stand up
else if (data.state == 1)
{
data.state = 0;
}
}
}
}
#endregion
}
else
{
//Save initial falling point
if (!data.falling)
{
data.fallHighestPoint = pb.transform.position.y;
data.falling = true;
}
//Check if we moved higher for some reason
if (pb.transform.position.y > data.fallHighestPoint)
{
data.fallHighestPoint = pb.transform.position.y;
}
if (data.isJumping)
{
if (data.jumpCount < jumpMaxCount)
{
if (data.lastJump != input.jump)
{
data.lastJump = input.jump;
//Get Jump input
if (input.jump)
{
//Check if we can jump
if (data.state == 0)
{
if (!staminaSystemEnabled || data.staminaLeft >= jumpStaminaCost)
{
data.moveDirection.y = jumpSpeed;
data.isJumping = true;
if (pb.isServer)
{
pb.RpcMovementPlayAnimation(0, data.jumpCount);
pb.RpcMovementPlaySound(1, data.jumpCount, Random.Range(0, jumpSound[data.jumpCount].clips.Length));
}
data.jumpCount++;
if (staminaSystemEnabled && pb.isServer)
{
data.staminaLeft -= jumpStaminaCost;
if (data.staminaLeft <= 0f)
{
//Stamina is now depleted. Set times
data.staminaRegenerationTime = Time.time + staminaPauseRateEmpty;
data.staminaDepletedSprintingBlock = Time.time + staminaDepletedSprintBlockTime;
//Play sound.
if (staminaExhaustedSound.Length > 0)
{
if (pb.isServer)
{
pb.RpcMovementPlaySound(0, 0, Random.Range(0, staminaExhaustedSound.Length));
}
}
}
else
{
//Set time for regen
data.staminaRegenerationTime = Time.time + staminaPauseRateNotEmpty;
}
}
}
}
}
}
}
}
}
#region Character Height
//Change character height based on the state
//Standing
if (data.state == 0)
{
pb.cc.height = standHeight; //Set height
pb.cc.center = new Vector3(0f, standHeight / 2, 0f); //Set center
}
//Crouch
else if (data.state == 1)
{
pb.cc.height = crouchHeight; //Set height
pb.cc.center = new Vector3(0f, crouchHeight / 2, 0f); //Set center
}
#endregion
// Apply JumpPad velocity if set
if (data.jumpPadVelocity != Vector3.zero)
{
data.moveDirection = data.jumpPadVelocity;
data.jumpPadVelocity = Vector3.zero; // Reset after use
Debug.Log("[BootsOnGround] JumpPad velocity applied.");
}
//Apply gravity
data.moveDirection += Physics.gravity * delta * gravityMultiplier;
//Move
CollisionFlags collision = pb.cc.Move(data.moveDirection * delta);
//Get local movement direction
data.localMoveDirection = pb.transform.InverseTransformDirection(pb.cc.velocity);
//Check grounded
data.isGrounded = pb.cc.isGrounded;
//Velocity
data.velocity = pb.cc.velocity;
//If we are grounded, reset swimming bool
if (data.isGrounded)
{
data.wasSwimming = false;
}
//Check if we hit a roof
if (collision.HasFlag(CollisionFlags.Above))
{
if (data.moveDirection.y > 0f)
{
data.moveDirection.y = -data.moveDirection.y;
}
}
}
//Move the camer to the correct position
#region CameraMove
//Standing
if (data.state == 0)
{
//Smoothly lerp to the correct state
pb.mouseLookObject.localPosition = Vector3.Lerp(pb.mouseLookObject.localPosition, camPosStand + pb.looking.GetCameraOffset(pb), delta * camPosSmoothSpeed);
}
//Crouching
else if (data.state == 1)
{
//Smoothly lerp to the correct state
pb.mouseLookObject.localPosition = Vector3.Lerp(pb.mouseLookObject.localPosition, camPosCrouch + pb.looking.GetCameraOffset(pb), delta * camPosSmoothSpeed);
}
#endregion
#region Character Height
//Change character height based on the state
//Standing
if (data.state == 0)
{
pb.cc.height = standHeight; //Set height
pb.cc.center = new Vector3(0f, standHeight / 2, 0f); //Set center
}
//Crouch
else if (data.state == 1)
{
pb.cc.height = crouchHeight; //Set height
pb.cc.center = new Vector3(0f, crouchHeight / 2, 0f); //Set center
}
#endregion
#region Stamina regen
if (staminaSystemEnabled && pb.isServer)
{
//Check if we can regen
if (Time.time > data.staminaRegenerationTime)
{
//Check if we need to regen
if (data.staminaLeft < 100f)
{
//Now, regen
data.staminaLeft += delta * staminaIncreaseRate;
}
}
}
#endregion
if (pb.isServer)
{
data.serverPosition = pb.transform.position;
data.serverRotation = pb.transform.rotation;
}
}
public override void PredictionInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (!pb.isServer)
{
if (data.historicalPositions.Count > 0)
{
//Calculate how much delay between server and client
data.snapShotCalculated = Mathf.RoundToInt(Mathf.InverseLerp(0, history, (float)NetworkTime.rtt) * data.amountOfSnapShots);
//Debug.Log("Calculated snapshot: " + snapShotToUse);
//Debug.Log("Closest snapshot: " + closestSnapshot);
//This is the position where serverPosition currently should be
Vector3 positionToCompareServerPosTo = data.historicalPositions[Mathf.Clamp(data.snapShotCalculated, 0, data.historicalPositions.Count - 1)];
//Offset in the past
float d = Vector3.Distance(positionToCompareServerPosTo, data.serverPosition);
data.deltaToServer = data.serverPosition - positionToCompareServerPosTo;
float totalInput = (Mathf.Abs(input.ver) + Mathf.Abs(input.hor));
float inputMultiplier = Mathf.Lerp(3, 1, totalInput);
float totalDelta = Mathf.Clamp01(delta * deltaMultiplier * inputMultiplier);
Vector3 deltaAdd = (data.deltaToServer * totalDelta);
deltaAdd.y = 0;
if (d > 0.03f)
{
//Move faster the larger the distance is, and also faster if wew let go of the input
pb.transform.position = pb.transform.position + deltaAdd;
for (int i = 0; i < data.snapShotCalculated; i++)
{
data.historicalPositions[i] += deltaAdd;
}
}
//Teleport distance
if (d > teleportDistance)
{
pb.transform.position = data.serverPosition;
for (int i = 0; i < data.historicalPositions.Count; i++)
{
data.historicalPositions[i] = data.serverPosition;
}
}
}
}
//Just simulate this again
AuthorativeInput(pb, input, delta, 0);
}
public void OnServerPositionReceived(Kit_PlayerBehaviour pb, Vector3 serverPos)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
}
public override void CreateSnapshot(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (data.historicalPositions.Count < data.amountOfSnapShots)
{
data.historyLastPositionSetAt = Time.time + Time.fixedDeltaTime;
data.historicalPositions.Add(pb.transform.position);
}
else
{
//Extract position and re-add it at the front.
data.historicalPositions.RemoveAt(data.historicalPositions.Count - 1);
data.historicalPositions.Insert(0, pb.transform.position);
data.historyLastPositionSetAt = Time.time + Time.fixedDeltaTime;
}
}
public override void Visuals(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (pb.isFirstPersonActive)
{
//Move transform back
pb.playerCameraFallDownTransform.localRotation = Quaternion.Slerp(pb.playerCameraFallDownTransform.localRotation, Quaternion.identity, Time.deltaTime * fallDownReturnSpeed);
if ((data.isSwimming && swimmingEnableDrowning && data.airLeft < 100f) || data.airLeft < 100f && !data.isSprinting && data.staminaLeft >= 99)
{
Kit_IngameMain.instance.hud.DisplayStamina(data.airLeft);
}
else
{
//Display stamina
Kit_IngameMain.instance.hud.DisplayStamina(data.staminaLeft);
}
if (data.state == 0)
{
Kit_IngameMain.instance.hud.DisplayMovementState(0);
}
else if (data.state == 1)
{
Kit_IngameMain.instance.hud.DisplayMovementState(1);
}
}
}
public override int GetCurrentWeaponMoveAnimation(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Check if we're grounded
if (bogrd.isGrounded)
{
//Check if we're moving
if (pb.cc.velocity.sqrMagnitude > 0.5f)
{
//Check if we're sprinting, if return 2
if (bogrd.isSprinting) return 2;
//If not return 1
else
return 1;
}
}
return 0;
}
public override float GetCurrentWalkAnimationSpeed(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Check if we're grounded
if (bogrd.isGrounded)
{
//Check if we're moving
if (pb.cc.velocity.sqrMagnitude > 0.1f)
{
//Check if we're sprinting, if return speed divided by sprintSpeed
if (bogrd.isSprinting) return pb.cc.velocity.magnitude / sprintSpeed;
//If not return speed divided by normal walking speed
else
return pb.cc.velocity.magnitude / walkSpeed;
}
}
return 1f;
}
public override Vector3 GetMovementDirection(Kit_PlayerBehaviour pb)
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
return bogrd.localMoveDirection.normalized;
}
return Vector3.zero;
}
/*public override bool CanFire(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Just based on our spriting value, if we are sprinting we cannot fire
if (bogrd.isSprinting && bogrd.isGrounded) return false;
else return true;
}*/
public override bool CanFire(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
// If the player is sprinting, cancel sprinting before firing
if (bogrd.isSprinting)
{
bogrd.isSprinting = false; // This assumes you can directly modify this state
}
// Now allow firing
return true;
}
public override bool IsRunning(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Just based on our spriting value, if we are sprinting we cannot fire
if (bogrd.isSprinting) return true;
else return false;
}
public override void CalculateFootstepsUpdate(Kit_PlayerBehaviour pb)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
//Check if we're grounded
if (bogrd.isGrounded)
{
//Get velMag
if (bogrd.velocity.magnitude > 0.5f)
{
//We're moving
//Check if enough time has passed since the last footstep
if (Time.time >= bogrd.nextFootstep)
{
if (allFootsteps.ContainsKey(bogrd.currentMaterial))
{
//Set next footstep sound
pb.footstepSource.clip = allFootsteps[bogrd.currentMaterial].clips[Random.Range(0, allFootsteps[bogrd.currentMaterial].clips.Length)];
//Set footstep source rolloff and distance
pb.footstepSource.maxDistance = allFootsteps[bogrd.currentMaterial].maxDistance;
pb.footstepSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, allFootsteps[bogrd.currentMaterial].rollOff);
//Set volume and time
if (bogrd.state == 0)
{
if (bogrd.isSprinting) //Sprinting
{
pb.footstepSource.volume = footstepsRunVolume;
bogrd.nextFootstep = Time.time + footstepsRunTime;
}
else //Normal walking
{
pb.footstepSource.volume = footstepsWalkVolume;
bogrd.nextFootstep = Time.time + footstepsWalkTime;
}
}
else if (bogrd.state == 1) //Crouching
{
pb.footstepSource.volume = footstepsCrouchVolume;
bogrd.nextFootstep = Time.time + footstepsCrouchTime;
}
//Play
pb.footstepSource.Play();
}
}
}
}
}
public override void OnControllerColliderHitRelay(Kit_PlayerBehaviour pb, ControllerColliderHit hit)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
Terrain terrain = hit.collider.GetComponent<Terrain>();
Kit_TerrainFootstepConverter convertedFootsteps = hit.collider.GetComponent<Kit_TerrainFootstepConverter>();
if (terrain && convertedFootsteps)
{
//Get texture from helper
int texture = GetMainTexture(pb.transform.position, terrain);
if (texture < convertedFootsteps.textureToString.Length)
{
//Convert texture id to 'tag' equivalent
if (allFootsteps.ContainsKey(convertedFootsteps.textureToString[texture]))
{
bogrd.currentMaterial = convertedFootsteps.textureToString[texture];
}
else
{
bogrd.currentMaterial = "Concrete";
}
}
else
{
Debug.LogError("Terrain texture outside of texture to foosteps conversion array! Playing concrete footstep.");
bogrd.currentMaterial = "Concrete";
}
}
else
{
//Use tag if it exists
if (allFootsteps.ContainsKey(hit.collider.tag))
{
bogrd.currentMaterial = hit.collider.tag;
}
//Use default 'concrete'
else
{
bogrd.currentMaterial = "Concrete";
}
}
}
public override Vector3 GetVelocity(Kit_PlayerBehaviour pb)
{
if (pb.isLocalPlayer || pb.isServer)
{
//If we are the controller, just get velocity from the character controller
return pb.cc.velocity;
}
else
{
return Vector3.zero;
}
}
public override void PlaySound(Kit_PlayerBehaviour pb, int soundID, int id2, int arrayID)
{
//Check if sound isnt playing right now
//Check for id
if (soundID == 0) //Exhausted
{
if (!pb.movementSoundSource.isPlaying)
{
//Set clip
pb.movementSoundSource.clip = staminaExhaustedSound[arrayID];
//Play
pb.movementSoundSource.Play();
}
}
else if (soundID == 1)
{
//Set clip
pb.movementSoundSource.clip = jumpSound[id2].clips[arrayID];
//Play
pb.movementSoundSource.Play();
}
else if (soundID == 2)
{
//Set clip
pb.movementSoundSource.clip = jumpLandSound[id2].clips[arrayID];
//Play
pb.movementSoundSource.Play();
}
}
public override void PlayAnimation(Kit_PlayerBehaviour pb, int id, int id2)
{
if (id == 0)
{
pb.thirdPersonPlayerModel.anim.SetTrigger(jumpAnimations[Mathf.Clamp(id2, 0, jumpAnimations.Length - 1)]);
}
}
public override void OnTriggerEnterRelay(Kit_PlayerBehaviour pb, Collider col)
{
//Check for swimming trigger
if (col.GetComponent<Kit_SwimmingTrigger>())
{
//Get
Kit_SwimmingTrigger trigger = col.GetComponent<Kit_SwimmingTrigger>();
//Check if its ours
if (pb.isServer)
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
Debug.Log("[Player] Entered swimming trigger. Entering swim state.");
//Only play this sound upon entering!
if (bogrd.state != 3)
{
//Check if a sound should be played
if (trigger.playerEnterSound)
{
if (Time.time - 0.5f > bogrd.lastSwimmingSoundPlayed)
{
AudioSource.PlayClipAtPoint(trigger.playerEnterSound, pb.playerCameraTransform.position);
bogrd.lastSwimmingSoundPlayed = Time.time;
}
}
}
//Set state
bogrd.state = 3;
//Copy input
bogrd.swimmingWorldMoveDirection = bogrd.moveDirection;
bogrd.swimmingCurrent = trigger;
if (swimmingWeapon)
{
//Copy current weapon slot
int wep = pb.weaponManager.GetCurrentlySelectedWeapon(pb);
if (wep != bogrd.swimmingWeaponSlot)
{
bogrd.swimmingPreviousWeaponSlot = wep;
}
//Select swimming weapon
pb.weaponManager.PluginSelectWeapon(pb, bogrd.swimmingWeaponSlot, true);
}
}
}
else
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
//Only play this sound upon entering!
if (!bogrd.isSwimming)
{
//Check if a sound should be played
if (trigger.playerEnterSound)
{
if (Time.time - 0.5f > bogrd.lastSwimmingSoundPlayed)
{
AudioSource.PlayClipAtPoint(trigger.playerEnterSound, pb.playerCameraTransform.position);
bogrd.lastSwimmingSoundPlayed = Time.time;
}
}
bogrd.state = 3;
}
}
}
}
}
public override void OnTriggerExitRelay(Kit_PlayerBehaviour pb, Collider col)
{
Kit_SwimmingTrigger swim = col.GetComponent<Kit_SwimmingTrigger>();
//Check for swimming trigger
if (swim)
{
//Check if its ours
if (pb.isServer)
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
if (bogrd.state == 3 && bogrd.swimmingCurrent == swim)
{
Debug.Log("[Player] Exited swimming trigger. Exiting swim state.");
//Set bool
bogrd.wasSwimming = true;
//Set state
bogrd.state = 0;
bogrd.swimmingCurrent = null;
bogrd.moveDirection = bogrd.swimmingWorldMoveDirection;
bogrd.moveDirection += swim.exitAdjustment;
//Select previous weapon
if (swimmingWeapon)
{
pb.weaponManager.PluginSelectWeapon(pb, bogrd.swimmingPreviousWeaponSlot, false);
}
}
}
}
else
{
if (pb.movementNetworkData != null && pb.movementNetworkData.GetType() == typeof(Kit_Movement_BootsOnGroundNetworkData))
{
Kit_Movement_BootsOnGroundNetworkData bogrd = (Kit_Movement_BootsOnGroundNetworkData)pb.movementNetworkData;
//Just reset bool
bogrd.state = 0;
}
}
}
}
public override void OnCameraTriggerEnterRelay(Kit_PlayerBehaviour pb, Collider col)
{
Kit_SwimmingTrigger swim = col.GetComponent<Kit_SwimmingTrigger>();
//Check for swimming trigger
if (swim)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (bogrd.swimmingCurrent == swim)
{
//Camera is underwater - player is underwater too
bogrd.isUnderwater = true;
//Check if that's really "us" and not a bot
if (pb.isFirstPersonActive)
{
//Show
Kit_IngameMain.instance.hud.DisplayUnderwater(true);
}
}
}
}
public override void OnCameraTriggerExitRelay(Kit_PlayerBehaviour pb, Collider col)
{
Kit_SwimmingTrigger swim = col.GetComponent<Kit_SwimmingTrigger>();
//Check for swimming trigger
if (swim)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (bogrd.swimmingCurrent == swim)
{
//Camera is not underwater - player is not underwater anymore
bogrd.isUnderwater = false;
//Check if that's really "us" and not a bot
if (pb.isFirstPersonActive)
{
//Hide
Kit_IngameMain.instance.hud.DisplayUnderwater(false);
}
}
}
}
#region Weapon Injection
public override WeaponsFromPlugin WeaponsToInjectIntoWeaponManager(Kit_PlayerBehaviour player)
{
if (swimmingWeapon)
{
WeaponsFromPlugin toReturn = new WeaponsFromPlugin();
toReturn.weaponsInSlot = new WeaponAttachmentBundle[1];
toReturn.weaponsInSlot[0] = new WeaponAttachmentBundle();
toReturn.weaponsInSlot[0].weapon = swimmingWeapon;
toReturn.weaponsInSlot[0].attachments = new int[0];
return toReturn;
}
else
{
return base.WeaponsToInjectIntoWeaponManager(player);
}
}
public override void ReportSlotOfInjectedWeapons(Kit_PlayerBehaviour pb, int slotWhereTheyWereInjected)
{
Kit_Movement_BootsOnGroundNetworkData bogrd = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
bogrd.swimmingWeaponSlot = slotWhereTheyWereInjected;
}
#endregion
#region Helpers for Terrain
public static float[] GetTextureMix(Vector3 worldPos, Terrain terrain)
{
// returns an array containing the relative mix of textures
// on the main terrain at this world position.
// The number of values in the array will equal the number
// of textures added to the terrain.
TerrainData terrainData = terrain.terrainData;
Vector3 terrainPos = terrain.transform.position;
// calculate which splat map cell the worldPos falls within (ignoring y)
int mapX = (int)(((worldPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth);
int mapZ = (int)(((worldPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight);
// get the splat data for this cell as a 1x1xN 3d array (where N = number of textures)
float[,,] splatmapData = terrainData.GetAlphamaps(mapX, mapZ, 1, 1);
// extract the 3D array data to a 1D array:
float[] cellMix = new float[splatmapData.GetUpperBound(2) + 1];
for (int n = 0; n < cellMix.Length; ++n)
{
cellMix[n] = splatmapData[0, 0, n];
}
return cellMix;
}
public static int GetMainTexture(Vector3 worldPos, Terrain terrain)
{
// returns the zero-based index of the most dominant texture
// on the main terrain at this world position.
float[] mix = GetTextureMix(worldPos, terrain);
float maxMix = 0;
int maxIndex = 0;
// loop through each mix value and find the maximum
for (int n = 0; n < mix.Length; ++n)
{
if (mix[n] > maxMix)
{
maxIndex = n;
maxMix = mix[n];
}
}
return maxIndex;
}
#endregion
}
}
How to make the movement even faster for a fastpaced fps game
?
Increase bunnyHopBoostAmount significantly, e.g. 8~12 or more
Decrease bunnyHopDecaySpeed to let this velocity last longer (e.g., 1.5~3)
Possibly add continuous acceleration if holding strafe keys in air (not just on jump)
This will add sustained momentum during air control, increasing overall speed.
4. Reduce drag / friction
This movement uses CharacterController, which has built-in collision handling and some friction. You can try:
Minimize slowdown on landing / friction by tweaking velocity clamping if any is applied elsewhere (check weapon multipliers and mouse look speed multipliers)
Avoid or reduce values that scale velocity down too much (like crouching multipliers or aiming slowdowns), or make aiming have less movement penalty.
If you want almost no drag, move towards physics-based movement with explicit velocity integration, but that requires structural overhaul.
5. Increase acceleration / responsiveness
If there's smoothing over movement inputs or velocity (e.g., input lerp), reduce lerp times or increase acceleration factors. For example:
Use immediate input response rather than lerping slowly
Increase multiplier speed for movement changes
6. Allow Sprinting Forward + Strafing
Currently sprint possible only for forward movement (moveDirection.z > 0.3f). For "fast strafe running," consider removing or loosening this requirement, allowing sprint with strafing or even backward movement for advanced players.
7. Jump height / multi-jump increase
Increase jumpMaxCount to allow double jumps or more (jumpMaxCount = 2 or 3)
Increase jumpSpeed to maintain air time with extra jumps
8. Misc tuning
Reduce crouch speed penalty: Raise crouchSpeed closer to walk or sprint speed.
Increase stamina capacity or regen: So players can sprint longer, keeping movement fast.
Optimize camera smoothing speeds: To reduce lag between player movement and camera.
Example tuning snippet in Kit_Movement_BootsOnGround inspector defaults:
csharp
[Header("Stats")]
public float sprintSpeed = 9f;
public float walkSpeed = 7f;
public float crouchSpeed = 5.5f;
public float jumpSpeed = 11f;
[Header("Bunny Hopping Settings")]
public float bunnyHopBoostAmount = 10f;
public float bunnyHopDecaySpeed = 2f;
public bool airControlEnabled = true;
public bool airControlSprintControl = true;
Additional advanced ideas:
Implement velocity clipping and air acceleration like Quake 3 or Source engine:
You accumulate velocity based on strafing and mouse movement
No excessive clamping
Handle sliding and circle strafing with manual velocity vectors
Reduce or remove fall damage or implement softer fall damage to keep speed flow
Add dash / slide mechanics
Summary
Your current system is solid for boots-on-ground movement — to make it faster and more like a fast-paced FPS:
This will result in fluid, responsive, and quick movement typical of fast twitch FPS games.
If you'd like, I can help prepare a full patch integrating these changes into your code!
using UnityEngine;
using MarsFPSKit;
public class Kit_JumpPad : MonoBehaviour
{
[Tooltip("Velocity applied to player when using this jump pad")]
public Vector3 jumpPadLaunchVelocity = new Vector3(0, 15f, 10f);
private void OnTriggerEnter(Collider other)
{
var pb = other.GetComponent<Kit_PlayerBehaviour>();
if (pb != null)
{
var data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (data != null)
{
// Set the jumpPadVelocity to launch vector transformed into world space
data.jumpPadVelocity = jumpPadLaunchVelocity;
Debug.Log($"JumpPad: Applied velocity {jumpPadLaunchVelocity} to player {pb.netId}");
}
}
}
}
This assigns jumpPadVelocity on the player's movement data.
The existing movement code will then pick this up during the next AuthorativeInput call (as you already have it).
4. Important considerations
Velocity is applied as an override, so it replaces whatever was in data.moveDirection for that tick.
Your current jump pad logic resets jumpPadVelocity to zero immediately after applying (as it should).
Your jump pad velocity must be in world coordinates, so if you want directional pads, you can rotate your launch velocity accordingly or expose direction and speed fields in the Kit_JumpPad inspector.
You can make the jump pad velocity configurable so level designers can change power and direction per jump pad instance.
5. Enhanced jump pad with direction
If you want your jump pad to launch players in the direction the jump pad is facing:
csharp
public Vector3 launchDirection = Vector3.forward;
public float launchSpeed = 20f;
private void OnTriggerEnter(Collider other)
{
var pb = other.GetComponent<Kit_PlayerBehaviour>();
if (pb != null)
{
var data = pb.movementNetworkData as Kit_Movement_BootsOnGroundNetworkData;
if (data != null)
{
Vector3 velocity = transform.rotation * launchDirection.normalized * launchSpeed;
data.jumpPadVelocity = velocity;
Debug.Log($"JumpPad: Applied velocity {velocity} to player {pb.netId}");
}
}
}
launchDirection is local to the jump pad, typically (0,1,0) for straight up or (0,1,1) for angled launch.
transform.rotation * launchDirection converts it to world space.
6. Compatibility checklist
Your system expects that data.jumpPadVelocity is set externally and consumed once during AuthorativeInput (this is true in your code).
Your jump pad script only needs to set this velocity; the movement system handles gravity, air control, fall damage, etc. as usual.
There is no conflict with bunny hop or normal jump logic—they coexist since jumpPadVelocity overrides moveDirection once.
7. Optional: Adding a cooldown or trigger delay
You may want to:
Prevent repeated re-triggering of jump pad velocity while player remains inside trigger.
Use timestamps and check against last application time in player data.
Or use OnTriggerExit and OnTriggerEnter to apply velocity only on fresh entry.
Summary
To create a Quake 3 style jump pad fully compatible with your movement system:
Create a trigger volume with a script.
On player entering trigger, set the player's jumpPadVelocity field to the intended launch velocity.
Your existing movement system applies that velocity once in the next update, then clears it.
This matches the pattern of your current jump pad velocity application code perfectly.
If you want, I can help provide a full Unity C# component script for the jump pad, ready to plug in! Just ask.
How to use this script:
Add this script to a GameObject that has a Collider component (Box, Sphere, Mesh, etc.), set Is Trigger to true (the script forces this in Reset()).
Configure launchDirection in the inspector:
Default (0,1,1) shoots players angled up and forward relative to pad.
For straight up, set (0,1,0).
For forward only (flat), (0,0,1), etc.
Set launchSpeed to control the velocity magnitude.
Tune cooldownTime to avoid multiple triggering when player stays inside collider.
Why this is compatible:
It uses your movement data's jumpPadVelocity field exactly as your movement script expects.
The velocity is applied once per frame inside your AuthorativeInput and then cleared.
launchVel is in world coordinates, converted from local pad direction.
Cooldown per player avoids excessively resetting velocity if player remains inside trigger.
Optional improvements
Add visual or audio effects on trigger for feedback.
Add spawn protection or team checks as needed.
Add directional arrows or gizmos in OnDrawGizmos to visualize launch direction.
If you want, I can provide example code for visualizing the pad direction or for audio feedback as well!