Camera Bob

From Valve Developer Community
Jump to: navigation, search
Deutsch Русский

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 and Winston from the Steam Forums for figuring all of this stuff out.

Sources: Sharkkk's Code Winston's Code

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", true, 0, true, 1 );
ConVar cl_viewbob_timer		( "cl_viewbob_timer", "10", 0, "Speed of Oscillation");
ConVar cl_viewbob_scale		( "cl_viewbob_scale", "0.05", 0, "Magnitude of Oscillation");

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:

 if ( cl_viewbob_enabled.GetInt() == 1 && !engine->IsPaused() )
	{
		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.