Camera Bob

From Valve Developer Community
Jump to navigation Jump to search
English (en)Deutsch (de)Русский (ru)Translate (Translate)

This tutorial will go through the basics of creating a camera bobbing for when a player walks. The result is a pretty realistic simulation of a head bob that nearly matches HL2's default walking speed and walking sounds. This tutorial has only been tested with the HL2MP OB and the beta OB SDK template, but should work for most every other version of Valve's source code with a few adjustments. A special thanks goes out to sharkkk (archived) and Winston (archived) from the Steam Forums for figuring all of this stuff out.

Sources:
sharkkk's code (archived)
Winston's code (archived)

The Code

In gamemovement.cpp, before the list of defines around lines 65 or so, add the following:

// Camera Bob
ConVar cl_viewbob_enabled	( "cl_viewbob_enabled", "1", 0, "Oscillation Toggle" ); // Enable or disable camera bobbing
ConVar cl_viewbob_timer		( "cl_viewbob_timer", "10", 0, "Speed of Oscillation" ); // How often do "turns up and down" happen
ConVar cl_viewbob_scale		( "cl_viewbob_scale", "0.05", 0, "Magnitude of Oscillation" ); // How far does the camera go up or down when walking

All we're doing here is declaring our ConVars, bools and floats for our camera bobbing code below.

In the same file, find the function void CGameMovement::WalkMove( void ) and add the following to the very top of the function after smove = mv->m_flSideMove:

	if ( cl_viewbob_enabled.GetBool() && !engine->IsPaused() ) // Disable bobbing when menuing (NOT in multiplayer)
	{
		float xoffset = sin( gpGlobals->curtime * cl_viewbob_timer.GetFloat() ) * player->GetAbsVelocity().Length() * cl_viewbob_scale.GetFloat() / 100;
		float yoffset = sin( 2 * gpGlobals->curtime * cl_viewbob_timer.GetFloat() ) * player->GetAbsVelocity().Length() * cl_viewbob_scale.GetFloat() / 400;
		player->ViewPunch( QAngle( xoffset, yoffset, 0 ) );
	}

What this does is it uses the player's velocity and the ConVars to oscillate the players view in a figure of 8 using a ViewPunch.