Changing the camera view

Hi guys,

I’m fairly new to LUA and still learning but I was wondering if any of you could help me out.
I’d like to have my character’s camera view to change when I press a key.
I want my character to maintain the position he was facing while this happens as well.

Basically I want to look at myself when I press and hold a key.

If you don’t mind sharing the process of the code then I’d appreciate that too, it’d help me learn.


You can use a

GM/CalcView hook, and override the camera position.

If you want some example code:

hook.Add( 'Think', 'LookAtSelfKeyPress', function() -- Every time 'think' is called (which is every frame for clients) this will be run.

	if ( input.IsKeyDown( KEY_B ) ) then --If the key 'b' is down then continue
		LocalPlayer().LookAtSelf = true --Set the variable 'LookAtSelf' to be true if the key is down (the dot means that it's making it part of the LocalPlayer's table)
		else --If the key 'b' isn't down then
		LocalPlayer().LookAtSelf = false --Set the variable as false
end )

hook.Add( 'CalcView', 'LookAtSelf', function( ply, pos, angles, fov ) --This actually changes the view

	if ply.LookAtSelf ~= nil and ply.LookAtSelf then --If the value we created in the previous hook isn't nothing (nil) (which is unlikely but just in case), and it's also positive (meaning the player's B key is down) then continue with changing the view
		local view = {}

		view.origin = pos-( angles:Forward()*-60 )
		view.angles = angles - Angle(0,180,0)
		view.fov = fov
		view.drawviewer = true

		return view --This is slightly modified code from the wiki's example of a CalcView hook so it actually faces the player instead of being behind the player, you might want to check the wiki and fiddle around a bit if you don't want this.

end )

If you don’t want B as your key, then check the key enums and replace KEY_B with whatever key you want.