UFPS : Ultimate FPS Documentation

    © Opsive, All rights reserved.

OpsiveLogoBlack.png

Table of Contents

Introduction

Playing the demo

Demo controls

Getting started

Trying out the demo scenes

Sky City

CleanScene

DemoScene1

DemoScene2

DemoScene3

Using the example player prefabs in your own scene

Important Concepts

FP components

States

Events

Working in the editor

Adjusting values

Toggling between Game and Editor

Navigating for text assets

Keep an eye on the Console

Scripting

Beginner

Intermediate

Code comments

About the "vp_" filename prefix

Creating an FPS Player from scratch

Basic setup

Adding a weapon

Adjusting weapon position

Adding a weapon camera

Adding a projectile

Adjusting the recoil

Animation concepts

Springs

Bob

Noise

Animations

Timers

The Controller

Motor

Acceleration

Damping

Air Speed

Slope Speed Up

Slope Speed Down

Free Fly

Jump

Force

Force Damping

Force (Hold)

Force Damping (Hold)

Physics

Force Damping

Push Force

Gravity Modifier

Slope Slide Limit

Slope Slidiness

Wall Bounce

Wall Friction

Has collision trigger

The Camera

Mouse

Sensitivity

Smooth Steps

Smooth Weight

Acceleration

Acceleration Threshold

Rendering

Field of View

Zoom Damping

Disable VR mode on startup

Position Spring

Offset

Ground Limit

Spring Stiffness

Spring Damping

Spring2 Stiffness

Spring2 Damping

Kneeling

Kneeling Softness

Earthquake Factor

Rotation

Pitch Limit

Yaw Limit

Kneeling

Kneeling Softness

Strafe Roll

Earthquake Factor

Shake

Speed

Amplitude

Bob

Rate

Amplitude

Step Threshold

Input Velocity Scale

Max Input Velocity

Require ground contact

Weapons

Positioning a model in your 3d art package

Avoiding camera clipping

Choosing a world intersection solution

1. Weapon Camera

2. Retraction

Rendering

Weapon Prefab

Field of View

Zoom Damping

Clipping Planes

Z Scale

Position Springs

Offset

Exit Offset

Pivot

Pivot Stiffness

Pivot Damping

Show Pivot

Spring Stiffness

Spring Damping

Spring2 Stiffness

Spring2 Damping

Kneeling

Kneeling Softness

Fall Retract

Walk Sliding

Input Velocity Scale

Max Input Velocity

Rotation Springs

Offset

Exit Offset

Pivot

Pivot Stiffness

Pivot Damping

Show Pivot

Spring Stiffness

Spring Damping

Spring2 Stiffness

Spring2 Damping

Kneeling

Kneeling Softness

Look Sway

Strafe Sway

Fall Sway

Slope Sway

Input Rotation Scale

Max Input Rotation

Retraction

Retraction tutorial

Distance

Offset

Relax Speed

Shake

Speed

Amplitude

Bob

Rate

Amplitude

Input Velocity Scale

Max Input Velocity

Require ground contact

Step

Min Velocity

Step Softness

Position Force

Rotation Force

Force Scale

Position Balance

Rotation Balance

Sound

Wield

Unwield

Animation

Wield

Unwield

Ambient

Ambient Interval

Shooters

Projectile

Firing Rate

Tap Firing Rate

Prefab

Scale

Count

Spread

Spawn Delay

Motion

Position Recoil

Rotation Recoil

Rotation Recoil Dead Zone

Position Reset

Rotation Reset

Position Pause

Rotation Pause

Dry Fire Recoil

Recoil Delay

Muzzle Flash

Prefab

Position

Scale

Fade Speed

Muzzle Flash Delay

Show Muzzle Flash

Shell

Prefab

Scale

Eject Position

Eject Direction

Eject Velocity

Eject Spin

Eject Delay

Sound

Fire

Dry Fire

Fire Pitch

Fire Sound Delay

Animation

Fire

Melee Attacks

Tutorial (Basic)

The quickest way to set up a new melee weapon

Making adjustments

System Walkthrough

Weapon poses

Attack states

The melee attack sequence

Types of states

Pull

Swing

Attack

Default

Tutorial (Advanced)

Overview

1. Decide how the weapon should move

2. Create the Pull state

3. Create the Swing state

4. Assign the states to the weapon component

5. Create the attack script

6. Create an Attack state

7. Test the attack in-game

8. Tweak the swing motion

9. Tweak the recoil force

10. Tweak the physics force

Debug objects

Player Body

Features Overview

Body animator with headlook

Full body awareness

3rd person camera view

Hand-aiming & recoil

Ragdoll handling

Player Body Setup

Introduction

The "Body" child object

"Weapons" vs. "weapon props"

Good to know for Artists

Good to know for Scripters

Tutorials

Setting up a basic, ragdolled player body

Enabling animation, headlook and ragdoll handler

Removing head clipping and extra arms

Adding weapon props for 3rd person

Adjusting the position and rotation of weapon props

Defining spawnpoints for muzzleflashes and shell casings

Muzzle flash

Shell ejection

Re-using weapon groups

Calibrating 3rd person weapon aim

Preparation checklist

Calibration steps

Adjusting 3rd person Recoil

Head & Arm materials setup

Anatomy of a player body

1) The main Body object, childed to the root player gameobject

Components

2) The Skinned Mesh Renderer

3) The "Lowest Spine Bone", assigned to slot in the bodyanimator (1)

4) The "Head Bone" assigned to slot in the bodyanimator (1)

5) Right hand gameobject (parent of 3rd person weapons)

6) The Weapon Group

7) 3rd Person Weapon Models

Mecanim Reference

Upper and lower body split

Full body animations

State machines

Lower Body

Upper Body (main)

Upper Body -> Firearm

Upper Body -> Unarmed

Upper Body -> Melee Weapon

Parameters of the UFPSExampleAnimator

Floating point values

Booleans

Triggers

Integers (enum indices)

Supported animation content

Body scripting

Terminology

Local player

Remote player

Look Point

On a local player

On a remote player

Look Direction

In Local 1st person

In Local 3rd person / Remote players

IsFirstPerson

Recommended components and scripts to study

Where to find the 3rd person code?

Why is the bullet always fired from middle of camera in 1st person?

What exactly does the ragdoll handler do?

In case of funky headlook

Using the "Generate Remote Player" wizard for AI and multiplayer

Body Troubleshooting

Body related issues

The player model doesn't stick to the center of the charactercontroller, but rotates around it in a huge arc /

The player model walks away from the charactercontroller

My ragdoll keeps falling over backwards, but I want it to fall over forwards

My remote player or 3rd person player starts swiveling around its hip like crazy

My character is invisible and won't move. Upon closer inspection its body floats far away in the air and wobbles about strangely

The camera shakes violently when I move

The local player starts stopping, stuttering or jumping erratically high up in the air for no apparent reason, especially when moving

Headlook is weird somehow: head tilts to / rests on shoulder or looks in wrong direction

Weapon related issues

I have assigned a 3rd person weapon to the hand bone of my character and positioned it correctly but it won't appear in-game

When I aim or shoot in 3rd person, the hand of my character points in a wrong / unnatural direction

When I calibrate weapon aim, the next time I start the game it's broken

I am building a new player based on an old player prefab. The old weapons are hovering in front of me even though i have removed them from the FPcamera

Firearm shells fly off at an extremely high forward or sideways velocity when I'm moving and shooting

Presets

Load & Save

Save Tweaks

States

Creating a new state

Activating and deactivating states

State order

The Default state

State blocking

Deleting a state

Removing a preset

Persist play mode changes

Projectiles

Anatomy of a bullet prefab

Anatomy of a bullet hole decal prefab

Creating a new bullet type

Disabling quad raycasts per-projectile

Making bullets ignore triggers

Spawning certain impact effects such as blood on enemies

Preventing decals from attaching to enemies

Muzzle Flashes

Creating a MuzzleFlash prefab from scratch

Shells

Creating a Shell prefab from scratch

Parameters

Life Time

Persistence

Bounce Sounds

Player Damage Handler

Parameters

Health

DeathEffect

MinDeathDelay & MaxDeathDelay

Respawns

MinRespawnTime & MaxRespawnTime

RespawnCheckRadius

RespawnSound

Inventory

Basics

Item Scripts

vp_PIayerInventory

vp_ItemIdentifier

vp_ItemPickup

Item Types

Item

UnitBank

Unit

Adding the Inventory

Enabling a weapon for inventory use

Step 1/2: Declare an ItemType for your weapon

Step 2/2: Add an Item Identifier to the FPS weapon

Creating an Item Pickup

Setting the Start Weapon

Limiting inventory capacity

Limit specific items by Amount

Limit items by Volume or Weight

Unlimited items and ammo

Setting zero item restrictions

Setting unlimited ammo & items

Item ID

Item Identifier ID logic

Explosions

Spawning an Explosion from script

Parameters

Radius

Force

UpForce

Damage

CameraShake

DamageMethodName

SoundMinPitch & SoundMaxPitch

FXPrefabs

Moving Platforms

General requirements

Assigning the MovingPlatform layer

Moving platform tutorial

Path

Type

PingPong

Loop

Target

Waypoints

Auto Start Target

Return Delay

Cooldown

Direction

Movement

Interpolation Mode

EaseInOut

EaseIn

EaseOut

EaseOut2

Slerp

Lerp

Speed

Rotation

Interpolation mode

SyncToMovement

EaseOut

CustomEaseOut

CustomRotate

Physics

Push Force

Snap player to top

Sound

Start

Move

Waypoint

Stop

Interaction

Adding the Interact Manager

Parameters

Interact Distance

Max Interact Distance

Interactables

Parameters

Interact Type

Normal

Trigger

CollisionTrigger

Recipient Tags

Interact Distance

Interact Crosshair

Interact Text

Delay Showing Text

Climb Interactable

Parameters

Minimum Climb Speed

Climb Speed

Mount Speed

Distance To Climbable

Min Velocity To Climb

Climb Again Timeout

Mount Auto Rotate Pitch

Simple Climb

Dismount Force

Sounds

Audio Source

Mount Sounds

Dismount Sounds

Climbing Sound Speed

Climbing Pitch

Climbing Sounds

Grab Interactable

Parameters

On Grab Text

Grab State Crosshair

Footstep Force

Kneeling

Stiffness

Shake Speed

Shake Amplitude

Throw Strength

Allow Throw Rotation

Burden

Max Collision Count

Carrying Offset

Camera Pitch Down Limit

Sounds Pitch

Grab Sounds

Drop Sounds

Throw Sounds

Platform Switch Interactable

Parameters

Switch Timeout

Platform

Audio Source

Switch Pitch Range

Switch Sounds

Switch Interactable

Parameters

Target

Target Message

Audio Source

Switch Pitch Range

Switch Sounds

Surface System

Features overview

Basic surface system logic

How does it all fit together?

Quick script overview

The SceneManager group

vp_SurfaceManager

vp_DecalManager

vp_PoolManager

ScriptableObjects

vp_SurfaceType

vp_SurfaceEffect

vp_ImpactEvent

Scripts that sit on scene objects

vp_SurfaceIdentifier

vp_PlayerFootFXHandler

vp_RigidbodyFX

Scripts that sit on effect prefabs

vp_FadingDecal

vp_ParticleFXPooler

Surface Manager

Texture Fallbacks

UV overlap

Default Fallbacks

Impact Event

Surface Type

Allow Decals

Dealing with stretched decals

Impact Events

Creating a new ImpactEvent

Fallback ImpactEvent

Surface Types

Recommended usage

Creating a new SurfaceType

ImpactFX

ImpactEvents and SurfaceEffects

Defining a fallback effect for when the ImpactType is unknown

Allow Footprints

Surface Effects

Creating a new SurfaceEffect

Sounds

Min & Max Pitch

Max One Per Frame

Objects

Prefab

Probability

Decal

Min & Max Scale

Allow Edge Overlap

Setting up a SurfaceEffect from scratch

Surface Identifiers

SurfaceType

Allow Decals

Surface ID

Enabling blood effects on the player

Decal Manager

Decal Limits

Total

Weathered

Placement Tests

Cleanup over time

Vertex Raycast Interval (sec) and Decals Per Batch

Instant quad corner test

Quad Raycast Range

Max Quad Raycasts

Allow Stretched Decals

Removal on Fail

Delay

Fadeout Speed

Insta-remove if offscreen

Fading Decals

Fadeout Delay

Fadeout Speed

Shrink Delay

Shrink Speed

Rotate Delay

Rotate Speed

Rotate Accelerate

Player Foot FX Handler

Footsteps

Mode

Detect Body Step

Fixed Time Interval

Interval mode with player body feet

Interval mode with "dummy" feet

Detect Camera Bob

Impact Event

Left Foot and Right Foot

Trigger Height

Sensitivity

Force Always Animate

Require Move Input

Verify Ground Contact

Jumping

Impact Event

Fall Impact

Impact Event

Threshold

Debug

Pause on every step

Mute local footsteps

State and Preset

Using a state to temporarily silence footsteps

Footstep Tutorials

Setting up a Foot FX Handler on your player

Tweaking AudioSources for footsteps

Recommended AudioSource settings for footstep sounds

Adding new footstep sounds to your game

Setting up footstep sounds for multiplayer

Using 'Muting local footsteps' for multiplayer testing

Setting footstep range

Making footsteps audible behind your back

Rigidbody FX

Impact Event

Impact Threshold

Min Camera Distance

Collision sounds

Making a Rigidbody emit SurfaceEffects on collision

Item pickup ground drop effects

Adding ragdoll drop effects

Advanced Surface System Topics

Surface Manager

Fallback logic

Limitations due to system architecture

Limitations due to Unity architecture

Footsteps

Sounds

Verify ground contact

Choosing a footstep detection mode

Detect Body Step

Pros

Cons

Detect Camera Bob

Pros

Cons

Fixed Time Interval

Pros

Cons

Bullets

Choosing a bullet script

vp_FXBullet

vp_Bullet

vp_HitscanBullet

Pooling

Why use vp_PoolManager?

Preventing bugs when pooling objects

Particle FX

Surface System Troubleshooting

Surface related

I have a level geometry whose material / shader does not have a texture. How to associate it with a surface?

My surface fallback does not work

I have put a vp_SurfaceIdentifier on an object but it does not seem to work

SurfaceEffects don't work on a static, multi-material / atlas map object

Bullet and decal related

Bullets make the wrong (or no) sound when hitting the player

Trouble getting decals to show on a uniformly scaled object

Trouble getting decals to show on a non-uniformly scaled object

In a standalone build, decals show up as stretched on a non-uniform, static object

Decals have not been removed when an objects respawns

Footstep related

Footsteps won't trigger in 'Detect Camera Bob' mode when I'm walking slowly, backwards or crouching

No footsteps / effects on terrain

VR

Introduction

What is the VR integration?

What is it not?

Input model

Requirements

Setup

Project Settings (IMPORTANT)

Install OVR Plugin

Script execution order

Demo scenes setup

UFPS_VR_Comfortable

Make these settings before play

'Comfortable' demo details

UFPS_VR_Moderate

Make these settings before play:

'Moderate' demo details

UFPS_VR_Intense

Make these settings before play

'Intense' demo details

Custom player and scene setup

Overview

Workflow

Scene root objects (not childed to each other)

Player Camera VR setting

Body

Adjustments

Footstep sounds

Camera adjustments

Procedural Motion

Death state

Reload state

Other unnecessary camera states

Weapons adjustments

Weapon states

Retraction

Muzzle & shell eject points

Scene objects

VRMode gameobject

OVRCameraRig

Rigidbody interpolation

VR Scripts

vp_VRCameraManager

VR mode forced runtime changes

Procedural motion section

Snap Rotate section

SnapRotate

StepDegrees

MinDelay

vp_VRCrosshair

CrosshairPrefab

InteractIconPrefab

MaxDistance

RelaxSpeed

CrosshairMinDistance

InteractIconMinDistance

SurfaceOffset

HideOnZoom

vp_VRWeaponManager

RenderPitchLimit

HeadLookSway

InputSway

ForcedRetraction

vp_VRTeleporter

DirectionPointer

CursorPrefab

CursorFacesCamera

MaxTeleportDistance

MinTeleportInterval

FallImpactDistance

AllowJumping

vp_VRPainFlash

PlanePrefab

PainTexture

DeathTexture

Distance

Limitations and unsupported features in VR

General

UFPS features

VR Troubleshooting

General

The unity editor just crashes when I press play in VR

"There are X audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene."

VR mode doesn't work / behaves oddly

"Hierarchy error. This component must be added to a gameobject with vp_Weapon components in child gameobjects."

Headset

Oculus Headset is not tracking

"Error (vp_VRCameraManager) 'CenterEyeAnchor' is not assigned."

My VR character suddenly seems taller or shorter than normal / I can't reach down to the pickups.

Input

I suddenly can't fire / interact / rotate

I can't fire in a standalone VR build

Snap rotating with the gamepad is unresponsive / slow

Snap rotating with the mouse is crazy sensitive

Rotating with the right gamepad stick is very sensitive / unsensitive

I can't move with the left gamepad stick but rotating with the right stick works

I can't rotate with the right gamepad stick but moving with the left stick works

I can't toss a grabbed rigidbody with the fire button using a gamepad

Interaction detection seems to be offset by a few decimeters in VR

The player slides a little when picking up items by pressing the Interact button in VR

FX

My player does not trigger footstep effects in VR

Performance

Rigidbody objects move with a stutter

Framerate micro stutter

Image Effects

Important notes

Rendering Path considerations

Forward Rendering

Deferred Lighting

Use Player Settings

Image FX compatibility notes

Crease

DepthOfField

EdgeDetectEffectNormals

GlobalFog

SSAOEffect

SunShafts

Input Manager

Example scripting usage

Rebinding controls at runtime

Gamepads

Basic setup

Setting up basic gamepad buttons and axes for a new project

Setting up Left- and Right Trigger axes as buttons for a new project

Updating the Input Manager for an existing project (pre UFPS 1.6)

If you don't have a lot of custom bindings

If you have lots of custom bindings

Additional info

Basic scripting

Accessing vp_LocalPlayer

Initialization

bool Exists

Refresh()

Position, Velocity, Angles and Directions

Vector3 Position

Vector2 Rotation

Vector3 BodyHeadLookDirection

Vector3 AimDirection

Physics and Velocity

Vector3 Velocity

float Velocity

AddForce(Vector3 force)

Move

Stop()

Teleportation

Teleport(Vector3 position, Vector2 rotation)

Teleport(float x, float y, float z, float pitch, float yaw)

Teleport(Vector3 position)

Teleport(float x, float y, float z)

Teleport(vp_SpawnPoint spawnPoint)

External Objects

Transform LookTransform

Transform GetLookTransform(float maxRange, int layerMask)

Transform Ground

Transform Platform

DismountPlatform

bool IsGrounded

Health and Death

Damage(float damage)

Damage(float damage, Transform source, vp_DamageInfo.DamageType type)

Damage(vp_DamageInfo damageInfo)

Die(float painHUDIntensity = 0.0f)

float Health

float MaxHealth

Weapons and Ammo

SetNextWeapon()

SetPrevWeapon()

SetWeaponByName(string gameObjectName)

SetWeaponByIndex(int index)

UnwieldCurrentWeapon

string CurrentWeaponName

int CurrentWeaponIndex

int CurrentAmmo

int CurrentMaxAmmo

int SpareAmmoForCurrentWeapon

Texture2D CurrentAmmoIcon

First- and Third Person

GoFirstPerson()

GoThirdPerson()

ToggleThirdPerson()

bool IsFirstPerson

Body Hierarchy

Collider Collider

Transform Head

Transform LeftFoot

Transform RightFoot

Effects

AudioClip DeathSound

vp_ImpactEvent FootstepFXImpactEvent

vp_ImpactEvent FallFXImpactEvent

vp_ImpactEvent JumpFXImpactEvent

Camera Shakes

CameraShake(float force = 0.5f, AudioClip audioClip = null, AudioSource audioSource = null)

GroundStomp(float force = 0.5f, AudioClip audioClip = null, AudioSource audioSource = null)

Input

EnableGameplayInput()

DisableGameplayInput()

ToggleGameplayInput()

EnableFreeLook()

DisableFreeLook()

Crosshair

ShowCrosshair

HideCrosshair

ToggleCrosshair

CrosshairTexture

Mouse Cursor

ShowMouseCursor()

ShowMouseCursorAndAllowMouseLook()

HideMouseCursor()

ToggleMouseCursor()

Multiplayer

bool IsMaster

Accessing components

EventHandler

Camera

Controller

InputManager

DamageHandler

WeaponHandler

Inventory

Respawner

BodyAnimator

RagdollHandler

FootFXHandler

Event system

Introduction to the event system

Modularity

Performance

Understanding event driven code

Brief overview

Finding the lines that SEND an event

Finding the methods that LISTEN to an event

Event handler tutorial

Preparation

1. Declaring an event

2. Making the PlayerEventHandler available to the scripts

3. Registering a target script with the event handler

4. Adding an event listener

5. Sending an event

Event types

vp_Message

vp_Attempt

vp_Value

vp_Activity

Activity additional properties

MinPause

MinDuration

AutoDuration

Argument

Active

Start

Stop

Disallow

Binding states to Activities

Activity example flows

Crouch

Jump

Attack

What's the difference between an Activity and a State?

Timers

Scheduling actions using vp_Timer.In

Iterations (repetition)

Intervals

Arguments

Multiple arguments

Delegates

Delegates with arguments

Delegates with multiple arguments

Canceling timers

Running a timer forever using vp_Timer.Start

vp_Timer.Handle

Creating timer handles

Canceling and blocking timers

Methods

Cancel

Execute

Properties

Debug Mode

Debug info

Created

Inactive

Active

Show Id

Show Callstack

Cheat Detection

Setup

ObscuredTypes Scripting Guide

When to implement ObscuredTypes?

Changing a variable in ANY SCRIPT into an ObscuredType

Changing a variable in a UFPS SCRIPT with a STATE MANAGER into an ObscuredType

Where to use ObscuredTypes?

Preventing obscured value reset in prefabs when updating UFPS

Additional scripting notes

'Unsupported type' editor error message

ObscuredTypes do not work with the ternary operator

There is no Vector4 ObscuredType

Sending an ObscuredType variable across the network in Photon PUN

Support and additional information

Introduction

Congratulations on your purchase of UFPS! A whole new world of amazing FPS immersion is now at your fingertips. Many thousands of hours of work has gone into the design and programming of these systems and we hope you'll have tons of fun with them!

At the core of UFPS is an advanced procedural camera system, allowing you to manipulate the camera and weapon model for a vast range of complex, realtime-generated behaviors. Combining this with traditional animation can result in super-lifelike motion rivaling the best AAA games out there!

Imagine having an artillery shell detonate nearby, shaking your arms and the camera violently while you desperately attempt to reload a shotgun. Shell shocked, your vision, hands and movement pattern are disturbed for a while before returning to normal ...

In summary, the main emphasis of UFPS is immersive first person motion. That said, it is currently being expanded into a full FPS framework that will eventually cover every aspect of a first person game. It can already be used as a cornerstone for a new FPS. Great effort has also gone into keeping it modular, so you should be able to pick it apart and use bits and pieces of it in your existing systems.

Hope you'll have as fun working and playing with this system as we are having building it! Feel free to show off your game or participate in the official forum discussion at:

www.opsive.com/assets/UFPS/forum/

Also, stay up-to-date on current developments by following us on twitter:

https://twitter.com/Opsive

Good luck with your game!

Playing the demo

The walkthrough demo is fairly self-explanatory. Use the big arrows at the top of the screen to navigate back and forth between screens. Press the buttons to try out various settings.

Demo controls

WASD

Move

C

Crouch

Space

Jump

Shift

Sprint

R

Reload

Middle & Right Mouse Button

Aim Down Sights / Zoom

F

Use

G

Toggle GUI

ESC

Quit app (if offline standalone player)

Enter

Toggle menu

Getting started

Trying out the demo scenes

Sky City

This scene, made with ProBuilder, is an example of how UFPS can feel and behave in a real game environment. It's a sci-fi museum populated by dangerous security turrets programmed to annihilate any intruder (you). Collect the small arsenal of HD weapons near the initial spawnpoint and see if you can make it around the museum!

CleanScene

This scene  (located in the "Demo/Levels" folder) is a simple terrain with a basic first person camera and controller, intended for prototyping and experimentation.

DemoScene1

This scene (located in the "Demo/Levels" folder) is designed as a test range using a Half Life "orange map" style. Its content and FPS player is tightly integrated into a walkthrough of the most important features.

DemoScene2

This scene is as test range for physics testing. It has an extra "slidy" player and several ramps tilted at various degrees for different test cases. It also has examples of various types of moving platforms. To shut off the demo walkthrough, disable or delete the "Demo" gameobject in the scene Hierarchy. Upon pressing Play you can now run around freely.

DemoScene3

This scene is an outdoor environment with a base and a bunch of explosive cubes, breakable crates and pickups of various kinds. It is a demonstration of how to put some of the example gameplay scripts to use. To shut off the demo walkthrough, disable or delete the "Demo" gameobject in the scene Hierarchy. Upon pressing Play you will be able to explore freely with an advanced FPS player.

Using the example player prefabs in your own scene

  1. Make sure your scene has some kind of floor in it, for example a huge box with collision. An easy way of achieving this is going to the Unity main menu, choosing GameObject > Create Other > Cube and setting the position of the cube transform to (0, 0, 0) and its scale to (1000, 1, 1000).
  2. In the Project view, browse to the Content/Prefabs/Players folder (or type player in the search box) and drag one of the example player prefabs into your scene hierarchy. Make sure it is positioned slightly above the floor.

IMPORTANT: If you have a fresh scene with an auto-created Main Camera object in it, delete this object (or atleast its Audio Listener) or you will get Unity warnings in the console.


Important Concepts

If you are like us and skip through manuals, here's what you really need to know: UFPS is all about FP components, States and Events.

FP components

An FP script is a Unity component designed to be part of a local, First Person player. These all have names beginning with "vp_FP" and include the Player, the Controller, the Camera, its Weapons and their Shooters.

States

A State is a list of settings for a specific component during a specific activity. For example: the camera "Crouch" state has values in it defining a lower Y-position for the camera. The controller's "Crouch" state makes it slow down. States are saved in small scripts called Presets.

Events

Events are how FP components communicate. For example: when the character controller detects a ground impact from falling, it sends the force of impact to the Player Event Handler, which in turn broadcasts it to the camera and weapon components (making them shake).

TIP: If you are planning to do even just a little scripting with this system, it is a good idea to first have a glance at the Event System chapter, and you will have more AHA! moments and fewer headaches.

Working in the editor

Adjusting values

Sliders are used to modify most variables. Text edit fields are used for variables with no limited range. Note that you can click and drag the text in front of a text edit field (for example the X) to adjust the value with the mouse.

Pressing and holding Alt while doing this gives you finer control. This is very useful when adjusting particular values, for example weapon position offset

Toggling between Game and Editor

Any time you want to toggle back and forth between the Inspector and the Game view without firing shots:

Navigating for text assets

The Unity Editor has a neat highlight feature which simplifies navigating for assets. To locate a text asset you see in a component State list, simply click on it and the text asset will be highlighted in the Project view. This gives you quick access to close by text presets compatible with the current component. You can also click directly on a text file in the Project view to inspect its values.

Another great way to quickly locate text assets is to write part of their names in the Project view search box).

Keep an eye on the Console

UFPS will communicate any detected errors and warnings via the Unity console. It's always a good idea to be aware of any red (Error) or yellow (Warning) messages it might display.

Most Unity crashes will result in an error message being shown in the console bar at the bottom left of the screen.

Click on the icon to open the full list of errors.

IMPORTANT: The displayed error may not be the one that caused your application to become unstable. To find the real source of a crash, you must often look further up the error list. The first and topmost (red) error message is often the culprit. Finding the name of the script and the line number of the crash in this way will often lead to AHA! moments.

Scripting

Beginner

To get started scripting with UFPS, check out the Basic Scripting chapter. It will give you a very good overview of what the system can do in terms of manipulating the player object.

Intermediate

When you feel comfortable with the basics, it's a good idea to read up on the Event System and Timers (both are central concepts to UFPS).

Code comments

Browsing through the scripts is also a great way of learning how the systems work. UFPS has very rich code commenting, and scripts will often contain additional useful info not found in the manual.

All methods in the included scripts use XML  <summary>  tags. Depending on your IDE (e.g. MonoDevelop / Visual Studio), this means you should be able to mouse-over on a method name in the code (or on a member name in a pop-up list) to display a brief description.

About the "vp_" filename prefix

The "vp_" prefix is a legacy from the original UFPS development team, VisionPunk. It will be removed in UFPS version 2.0, which is being developed by Opsive.

Creating an FPS Player from scratch

The demo scenes and prefabs will be sufficient for getting to know the system and playing around with its various parts. Once you're ready to dig a little deeper, these player creation tutorials will be good next steps for learning how things are set up.

Basic setup

  1. Create an empty gameobject and name it Player.
  2. Create a plane (or any kind of floor with collision) and place the player gameobject above it.
  3. Create another empty gameobject, name it Camera and drag it onto the first one so it becomes a child of the Player object.
  4. Set the position of the the new child gameobject to (0, 0, 0).
  5. In the project view search box, type vp_fp.
  6. Drag the vp_FPPlayerEventHandler script onto the Player gameobject.
  7. Drag the vp_FPController script onto the Player gameobject.
  8. Drag the vp_FPInput script also onto the Player gameobject.
  9. Drag the vp_FPCamera script onto the Camera gameobject.

TIP: Remember to clear the Project view search box when done.

  1. With the Camera gameobject selected, go to the top of the Inspector and set its Tag to MainCamera (if there was a default gameobject named "MainCamera" in the scene, delete it now).
  2. Press Play and you should now have a simple, working FPS controller and camera.

Adding a weapon

  1. If you haven't already, drag the vp_FPWeaponHandler script onto the Player gameobject.
  2. Create a new empty gameobject and give it the name of your weapon.
  3. Add a vp_FPWeapon component to your weapon gameobject.
  4. Open the weapon component's Rendering foldout, and drag a weapon prefab into the Weapon Prefab slot.

  1. Drag the weapon gameobject onto the Camera object so that it becomes a child of the camera.
  2. Set the weapon transform's position to (0, 0, 0).
  3. Press Play, then the 1 or E button, try moving and jumping, and there should now be a swaying weapon model in the view. If you don't see the weapon right away, proceed with the next section, Adjusting weapon position.
  4. To add more weapons, simply repeat steps 1-6 above.

TIP: If you have more than one weapon, it's a good idea to prefix the name of your weapon object with a number. This will not only define weapon order in the hierarchy. It will also control the order of the weapons when toggled.

A weapon prefab means a prefab containing a mesh filter, a mesh renderer and materials. For more info about prefabs and how to set them up, see these articles:

   
http://docs.unity3d.com/Documentation/Manual/Prefabs.html
   
http://docs.unity3d.com/Documentation/Components/comp-MeshGroup.html
   
http://docs.unity3d.com/Documentation/Manual/Materials.html

Adjusting weapon position

  1. Start the game.
  2. Open the weapon's Position Springs foldout and gently increase Offset:Z until you see the weapon. Also adjust X and Y to your liking.
  3. For weapon angle, do the same under the Rotation Springs foldout.

  1. When happy with your weapon's default position and orientation, go to the Preset foldout at the bottom of the weapon component and click the Save button (make sure to do this in the Preset section of the weapon component and not another component).
  2. Stop the game and Load your weapon preset script onto the component.


Adding a weapon camera

Using a weapon camera will prevent the weapon from intersecting other objects in the scene, and will give you greater control over weapon appearance. Though this is optional, in most cases you will want one.

  1. Create a new empty gameobject, name it WeaponCamera and drag it onto the FPSCamera gameobject (setting it up as a child of the camera gameobject).

  1. Set the position of the WeaponCamera gameobject to (0, 0, 0).
  2. Select the WeaponCamera gameobject, go to the Unity main menu and choose Component > Rendering > Camera. Your weapon camera gameobject should now have a basic Camera component on it in the Inspector.

IMPORTANT: You should only create one weapon camera (not one per weapon).

Adding a projectile

  1. Drag the vp_FPWeaponShooter script onto your weapon gameobject.
  2. In the Inspector, expand the Sound foldout on the FPWeaponShooter component. In the Project view search box, type pistolfire and drag the pistol sound to the Fire slot in the Inspector.
  3. Expand the shooter's Projectile foldout. In the Project view search box, type pistolbullet and drag the PistolBullet prefab to the Projectile > Prefab slot in the Inspector.
  4. If you start the game now and press the left mouse button, the weapon should shoot bullets, play a fire sound and shake with a spring motion. The recoil doesn't yet look very realistic though! See the next section for info on how to make it look better.

Adjusting the recoil

  1. Start the game.
  2. Go to the vp_FPWeapon component in the Hierarchy and open its Position Springs foldout.
  3. Find the Spring2 Stiffness/Damping sliders and type the following into the respective field:

        Spring2 Stiffness: 0.2
           Spring2 Damping:
    0.55 

  1. Similarly, open the Rotation Springs foldout, find the Spring2 Stiffness/Damping sliders there and set them to:

            Spring2 Stiffness: 0.85
           Spring2 Damping:
    0.6
  2. Now fire the weapon in the game view to see the result. Of course, these values are only examples. Keep adjusting until you think it looks good.
  1. When happy with your modifications, with the game still running, go to the Preset foldout at the bottom of the weapon component (Note: not the shooter component) and click the Save button.
  2. Stop the game and Load your new weapon preset onto the component.

That's about it! There are obviously many more powerful features and things to learn about the various components. Play around and browse this manual for information and ideas.

Animation concepts

One of the really unique and cool things about UFPS is how it makes heavy use of procedural motion for animating the camera and weapons. This means it is not dependent on "regular" animations. Instead, most motion is generated in realtime depending on player input, movement, and external physics forces, which makes everything a lot more organic and natural. You are one with the camera and weapons.

Another huge benefit of procedural motion is that you don't have to animate every weapon individually. You don't even have to know a single thing about animating models! As long as there is a static 3d model, UFPS will animate it for you in realtime. Once you have motions for one weapon type - for example a pistol - the motions work instantly on all pistols with minor tweaks.

Here's the thing: using procedural motion in conjunction with traditional animation can result in incredibly realistic and lifelike motion, strongly promoting suspension of disbelief and giving your game a special edge.

Springs

   

The main workhorse of UFPS is a spring system that operates on transform position, rotation or scale. The spring has a Rest State (also known as the "static equilibrium") where it "wants to be". If you move it away from the target value using external force, it will immediately and continuously strive back to its target position or angle. The spring Stiffness - or mechanical strength - determines how loosely or rigidly the spring behaves. Finally, the Damping makes spring velocity wear off as it approaches its rest state. Springs can be used to simulate everything from jello (a loose spring operating on object scale), an arrow hitting a wall (a very stiff spring rotating the arrow with the pivot at the head) or an underwater camera (a loose spring making the camera bounce softly as your feet hit the ocean floor).

Bob

Bob is the sinusoidal motion of an object or the camera. View bob has been around in first person shooters for ages as a means of moving the camera up and down when walking. Modern shooters don't always have a very pronounced view bob, but bob is still very useful for animating the weapon model (and camera if used in moderation). If applying bob along both the x and y vector you can get interesting results such as the feeling of being a dinosaur or a huge ogre.

Noise

     

Procedural noise has been used in computer graphics and special effects for years as a means of generating smoke, terrains and camera shakes (to name but a few areas). UFPS uses a standard perlin noise function for applying random turbulence to the weapon and camera. For example: a slight breathing camera motion as you zoom in with a sniper rifle, gentle idle movements for a hand holding a sub machine gun, or the heavily disturbed camera movements of a character that is drunk or poisoned.

Animations

Since UFPS' procedural motion systems only operate on a model's pivot and transform, they won't handle more complex animations. For example, if you want to do things "inside" the weapon model - such as bending an arm or fingers -  you have to use a model with animations (this is also true for pistol / rifle reload animations).

That said, UFPS provides plenty of hooks for playing such weapon animations, e.g. when wielding, unwielding, firing and reloading weapons. The weapon class even has a cool ambient animation scheduler which will play a random idle animation from a list provided by you at random intervals. For more info about this, see the Animation section of the Weapons chapter.

Timers

UFPS makes massive use of our own timer logic, vp_Timer. This is a very powerful and easy-to-use script extension for delaying (scheduling) methods (such as animations or physics force impacts) with a time delay. The system has many commands an options and is well worth checking out for all sorts of sequential animation and gameplay programming tasks.

The pistol reload animation in the demo was actually made using procedural animations only. It was an experiment to see how far we could push the motion systems using only springs and timers. For more info, study the comments in the vp_PistolReloader script.

The Controller

vp_FPController is an extended character controller designed to work perfectly with the vp_FPCamera class. It features acceleration, sliding, air control, wall bouncing, external forces and the ability to push around rigidbodies.

The controller doesn't rotate by itself. To rotate it via mouselook, add an FPCamera to its hierarchy as described in the Creating an FPS Player from scratch chapter.

Motor

The Motor foldout contains all basic movement parameters of the FPController.

Acceleration

The amount of world velocity added to the controller every frame when moving.

Damping

How quickly velocity should deteriorate when movement stops. Low values will get you a "slippery floor" or icy feeling. High values will slow down the controller.

TIP: If you're not a big fan of "slidy" controls, set both Acceleration and Damping to 1 and reduce damping until you're happy with the walking speed. This will get you a controller that stops abruptly.

TIP: If you want to tweak the controller for a specific real world max speed, you may output the player's speed in meters per second using this line of code:

Debug.Log(Controller.Velocity.magnitude);

Air Speed

A factor determining how fast the controller can move when it has no contract with the ground (jumping, falling or flying). A value of 0 means the player can not move sideways at all when flying (like a real world human). A value of 1 means the player can move as quickly in the air as on the ground. This is often used in games to increase the feeling of control, especially if platform jumping is a gameplay element.

Slope Speed Up

This value increases or decreases controller velocity on upward slopes. At 1.0, velocity on upward slopes will be kept roughly the same as on flat ground. Values lower or higher than 1 will make the controller slow down / speed up on upward slopes, respectively.

TIP: The slope speed feature can be especially useful on outdoor terrain; try setting "Slope Speed Up" to 0.5 and "Slope Speed Down" to 1.5. This will slow down the controller moving uphill, and give it a speed boost running downhill.

Slope Speed Down

This value increases or decreases controller velocity on downward slopes. At 1.0, velocity on downward slopes will be kept roughly the same as on flat ground. Values lower or higher than 1 will make the controller slow down / speed up on downward slopes, respectively.

Free Fly

When active, this enables a throttle logic for moving a flying controller in an arbitrary direction based on player (camera) forward vector. This can be used for many things in an FPS, for example spectator cams, ingame editor modes, zero gravity, swimming underwater, jetpacks and superhero style flying. Free fly movement can be toggled at any time. This feature works best if the Physics > Gravity Modifier is zero or very low.

Jumping and crouching behaves differently in Free Fly mode. The Jump activity will make the camera go straight up. The Crouch activity will make it go straight down. The collider will only shrink upon crouching if the controller has ground contact.

Jump

The Jump foldout contains parameters allowing you to design a highly customized jumping behaviour for your player.

Force

The amount of up-force that is added to the character controller in a single frame when the player jumps. The height of the jump is slightly influenced by the gravity modifier.

Force Damping

This parameter determines how quickly the jump force wears off.

Force (Hold)

The amount of force to add per frame if the jump button is being held down continuously. This is a common feature for providing increased jump control in platform games. A large value here will have sort of a jetpack effect. To remove this feature, just set it to zero.

Force Damping (Hold)

Determines how quickly the hold jump force wears off.

Physics

The Physics foldout contains parameters governing how various laws of nature should affect the controller.


Force Damping

This value scales how receptive the controller is to scripted external forces such as explosion knockback. A value of 1 means it is not affected at all, like an extremely heavy object. A value of 0 means the controller will be affected enormously, as would a very light object.

Push Force

This value determines how "strong" the controller is when pushing around physical objects (rigidbodies). Rigidbodies with larger mass will be harder to move.

Gravity Modifier

The gravity modifier regulates how much the controller will be affected by gravity. Higher values give a heavier feel. The "Physics.Gravity" value of the Unity Physics Manager affects the object aswell.

Slope Slide Limit

The ground steepness in angles above which controller will start to slide.

Slope Slidiness

Slidiness of the surface that we're standing on. Will be additive if steeper than the (regular Unity) CharacterController's "slopeLimit" parameter.

TIP: You can alter PhysicsSlopeSlidiness and SlopeSlideLimit in realtime using the state manager depending on the current ground surface, for example by enabling a special sliding state on the vp_FPController via a trigger.

Wall Bounce

This feature makes the character controller bounce when moved by external forces such as explosions , giving a slightly more organic feel on wall collision (note that it does not apply to regular player movement).

Wall Friction

This feature determines how much the character controller should slide against surfaces when moved by external forces such as explosions (note that it does not apply to regular player movement).

Has collision trigger

The collision trigger is a scripting feature used for interacting with rigidbody objects such as moving platforms. When this is active (default) a child gameobject is generated on startup, with an encompassing capsule collider trigger. This is to allow physics responses to incoming rigidbodies.

IMPORTANT: Without a trigger, the controller will still be able to ride on moving platforms, but the platforms will not auto-start when stood upon and will not be able to push the player around or use its intersection solver.

The collision trigger may sometimes affect raycast or trigger logic. If you are experiencing issues with raycasts not hitting the player, make sure the raycast hits the actual charactercontroller, or send a message from the trigger to the controller using "SendMessageUpwards". See how this works in the vp_HitscanBullet script.

The Camera

The vp_FPCamera class governs all behaviour of the first person camera which is a child to the main player gameobject. It features mouse smoothing, view bob, camera shakes, smooth zooming, kneeling and reacting to external forces among many other things.

Mouse


Sensitivity

Sets mouse sensitivity in the X (yaw) and Y (pitch) axes.

Smooth Steps

Mouse smoothing interpolates mouse input over several frames to reduce jerky player input. "Smooth Steps" determines how many of the most recent frames of mouse input to average. A typical value is 10.

Smooth Weight

"Smooth Weight" determines the influence of recent mouse input as it ages. Reducing the weight modifier to 0 will provide the user with raw, unfiltered feedback. Increasing it to 1.0 will cause the result to be a simple average of all the recently sampled smooth steps (and will feel very laggy). A typical value is 0.5.

Acceleration

Mouse acceleration increases the mouse sensitivity above certain speeds. Along with low mouse sensitivity this allows high precision without loss of turn speed. It gives you optimal precision at slow mouse movements (for example when sniping), but will also allow you to turn 180 degrees quickly to aim at someone behind you.

Acceleration Threshold

Describes the speed above which mouse acceleration will be activated. If you move your hand above this set speed, mouse acceleration will kick in.

Rendering


Field of View

Sets the target FOV of the first person camera.

Zoom Damping

Determines how fast the camera will interpolate to the target value when FOV is changed from script. Higher values result in slower zoom.

Disable VR mode on startup

This setting will temporarily disable the setting 'Virtual Reality Supported' (found under Project Settings) when the vp_FPCamera wakes up, and re-enable it when needed. This may seem counter-intuitive for a VR game, but is an important workflow feature. For more info, see this section in the VR chapter.

Position Spring

The camera position is hooked to two springs, allowing for a host of interesting effects. The first, "regular" spring is used for reacting to player movements that need a soft spring setting. The second spring is intended for external forces that require stronger spring settings, such as the camera shaking violently from an artillery impact.


Offset

Camera position offset relative to the player. For example: to create a crouch animation, you can smoothly lower the camera with the Y-offset. To peek around corners without moving the character, you can move the camera sideways using x-offset.

This position is where the camera "wants to be". If you move it away from the target value using external force, it will immediately try to go back to the target position.

Ground Limit

A vertical limit intended to prevent the camera from intersecting the ground. The value is in negative world units relative to the camera position. It determines how far below the normal head position the camera is allowed to go when kneeling or reacting to external forces or camera bob.

Spring Stiffness

Camera spring stiffness - or mechanical strength - determines how loosely or rigidly the camera spring behaves. A low value will result in a soft, swaying motion, and higher values will result in stronger spring movements.

Spring Damping

Camera spring damping makes spring velocity wear off as it approaches its rest state. Low values will result in a very loose, swaying motion, while higher values can result in either motion that quickly grinds to a halt, or a stiff shaking motion (much depending on the spring stiffness setting).

Spring2 Stiffness

Stiffness for the secondary camera spring. This spring is intended for external forces. It does not automatically do anything. Instead, activate it using the "AddForce2" script function of vp_FPCamera. See the DemoScript for example usage.

Spring2 Damping

Damping for the secondary camera spring. This spring is intended for external forces. It does not automatically do anything. Instead, activate it using the "AddForce2" script function of vp_FPCamera. See the DemoScript for example usage.

Kneeling

Determines how much the camera will be pushed down when the player falls onto a surface.

Kneeling Softness

The number of frames over which to even out each fall impact for kneeling. A higher number will slow down the kneeling. A lower number will be more 'snappy'.

Earthquake Factor

Exaggerates or reduces the down force imposed on this camera by earthquakes.

Rotation

The camera is mainly rotated by mouse input and camera shakes. It also has a rotation spring, mostly used for rotating around the Z vector (rolling) by means of external forces.


Pitch Limit

Limits vertical mouse rotation of  the camera.

Yaw Limit

Limits horizontal mouse rotation of  the camera. Useful mainly for creating things like gun turrets. It could also be useful for players mounted on vehicles, let's say a player shooting out of a car side window.

Kneeling

Determines how much the camera will be rotated when the player falls onto a surface. There is a 50% chance the camera will rotate left versus right upon impact.

Kneeling Softness

The number of frames over which to even out each fall impact for kneeling. A higher number will slow down the kneeling. A lower number will be more 'snappy'.

Strafe Roll

This variable rotates the camera depending on sideways local velocity of the character controller, resulting in the camera leaning into or away from its sideways movement direction. It's useful when moving and crouching. Larger positive values (2.0 and above) will result in a motorcycle or airplane type behaviour.

Earthquake Factor

Exaggerates or reduces the rotation force imposed on this camera by earthquakes.


Shake

UFPS uses a standard perlin noise function for applying random turbulence to the weapon and camera. For example: a slight breathing camera motion as you zoom in with a sniper rifle, gentle idle movements for a hand holding a sub machine gun, or the heavily disturbed camera movements of a character that is drunk or poisoned.


Speed

Determines the shaking speed of the camera.

Amplitude

The strength of the angular camera shake around the X, Y and Z vectors. X and Y shakes are applied to the actual controls of the character model while Z is only applied to the camera. If you increase the shakes, you will essentially get a drunken / sick / drugged movement experience. This can also be used for i.e. sniper breathing since it will affect aiming.

Bob

View bob is the sinusoidal relative motion of the camera, hooked to character controller velocity. If applying bob along both the x and y vector you can get interesting results such as the feeling of being a dinosaur or a huge ogre.


Rate

Speed of the camera bob. X, Y and Z is positional motion. W is roll around the forward vector (tilting the head from left to right). A typical value for Y is 0.9.

Amplitude

The strength of the camera bob. Determines how far the camera swings in each respective direction. For camera bob, X, Y and Z is positional motion. W is roll around the forward vector (tilting the head from left to right). A typical value for Y is 0.1.

Step Threshold

A feature for syncing bob motion with a script callback. The bob step callback is triggered when the vertical camera bob reaches its bottom value (provided that the speed is higher than the bob step threshold). This can be used for footstep sounds and various other behaviours.

This feature is not automatically used by the camera (although external components such as the vp_PlayerFootFXHandler will hook into it). If you want to use it for additional purposes, you need to provide a callback through script. Here is an example of how to set up a bob step callback:

Camera.BobStepCallback += delegate()

{

        Camera.AddForce2(new Vector3(0.0f, -1.0f, 0.0f));

};

This snippet will apply a sharp stomping motion on the camera for every footstep. It will be called once whenever the camera reaches its lowest bob point and changes direction

Input Velocity Scale

This tweaking feature is useful if the bob motion goes out of hand after changing player velocity. Just use this slider to scale back the bob without having to adjust lots of values.

Max Input Velocity

A cap on the velocity value being fed into the bob function, preventing the camera from flipping out when the character travels at excessive speeds (such as when affected by a jump pad or a speed boost).

TIP: The current speed used by the camera bob can be displayed in script using:

Debug.Log(FPController.Velocity.sqrMagnitude);

Require ground contact

This determines whether bob should stay in effect when jumping, falling or flying. Disabling this is useful for doing flying dinosaurs, underwater movement et cetera.

Weapons

In UFPS, 1st person weapons are implemented by adding empty child gameobjects to the FPCamera transform and dragging vp_FPWeapon components onto each gameobject.

When the game starts, any such gameobjects are put in a list and may be toggled on or off from script. The weapons are arranged in alphabetical order, so you have great control over the order of your weapons, e.g. by putting numbers at the beginning of their names in the Hierarchy.

The runtime responsibility of the vp_FPWeapon component is to animate a weapon using its procedural motion properties. This means the component will manipulate the weapon transform's position and rotation using springs, bob and perlin noise. For more info about this, see the Animation Concepts chapter.

Note that the vp_FPWeapon class is not responsible for shooting logic, only for motion resulting from player movement or external forces. This is because an FPWeapon is not necessarily a firearm. It could just as easily be a knife, an axe, a crowbar or a couple of fists. All firearm specific features exist in a separate class called vp_FPWeaponShooter.

In UFPS, weapon availability is not controlled by adding or removing weapon gameobjects to the FPCamera hierarchy dynamically. Instead, the camera hierarchy is meant to parent all the weapons the player will ever be able to carry. The game code simply allows or prevent the player from activating these depending on the inventory state. By default, this is handled by the vp_WeaponHandler and the vp_PlayerInventory scripts.

Positioning a model in your 3d art package

The weapon should be rotated straight forward with no rotation around the X or Y axis (otherwise the iron sights won't match up by default when zooming). You can set the ingame position and rotation (aswell as the pivot) in the Inspector and in the preset scripts, so that doesn't really matter, but in general we recommend to keep the weapon 100% centered in the X axis, roughly centered in the Y axis and to keep the elbow of the arm at about the center of the Z axis. This way you'll make sure the weapon will be visible by default when added to the FPSPlayer, simplifying further editing. If you will be making many weapons, this rough placement is a good standard to conform to. Final tweaking of position and rotation should be done in the Position Springs and Rotation Springs foldouts of the vp_FPWeapon component.

Avoiding camera clipping

One important thing to remember when you create (or choose) a model is that any arm geometry should be positioned so an imaginary tube (about 3 inches in diameter) would be able to pass from the top of the wrist to the camera plane without touching any arm geometry. If it does, you will have trouble with the camera clipping arms ingame at some point (we call this the Pringles Tube Rule).

The "Pringles Tube Rule"

Choosing a world intersection solution

A common problem in FPS construction is preventing weapons from sticking through walls and other geometry. UFPS allows you to choose between two very different solutions to this issue.

1. Weapon Camera

This is the classic approach, where weapons are rendered by a second camera, after the scene has been rendered. This gives you greater control over weapon appearance, since you may change the Field of View (FOV) of the weapon camera independently of the vp_FPCamera. However, it comes with a couple of drawbacks:

For more info about the Weapon Camera and gameobject and component setup, see the Adding a weapon camera tutorial.

2. Retraction

This feature approaches the intersection problem in a more "realistic" manner. It allows you to run the system without a weapon camera. Instead, every frame a raycast is made from the weapon into the environment. Whenever the raycast hits something, the weapon is pulled back accordingly. Using this approach your weapon will feel more like a part of  the world geometrically. Shadows from world objects will be cast on the weapon model, which looks very nice. However, drawbacks include:

TIP: Although the Retraction feature is intended for running the system without a weapon camera, nothing prevents you from using the systems together. In fact, Retraction can be a small extra nice touch to "weapon camera weapons".

Rendering

The vp_FPWeapon's Rendering foldout manages what to render for the weapon and how to render it.

Weapon Prefab

This slot should contain the model to be rendered for this weapon. A weapon prefab means a prefab containing a mesh filter, a mesh renderer and materials. For more info about prefabs and how to set them up, see these articles:

   
http://docs.unity3d.com/Documentation/Manual/Prefabs.html
   
http://docs.unity3d.com/Documentation/Components/comp-MeshGroup.html
   
http://docs.unity3d.com/Documentation/Manual/Materials.html

Field of View

This slider sets the Field of View for the weapon camera (if using one). It gives you great control over the appearance of the weapon. Tweak this along with weapon position and rotation offset to get the exact placement and perspective that you want.

Zoom Damping

Determines how fast the weapon will interpolate to the target value when FOV is changed from script. Higher values result in slower zoom.

Clipping Planes

Determines the near and far clipping planes of the weapon camera. Very useful in situations where you want to use a specific FOV and positional / rotational offset for the weapon, but parts of the weapon mesh intersect the view too close to the camera. In these cases, simply increase the near clipping plane. This is best done at runtime by clicking and dragging on "Clipping plane: X" in the Inspector while holding the "Alt" key.

Z Scale

Z Scale is intended for tweaking the appearance of the weapon when running the system without a weapon camera. See the Retraction section for a use case.

Position Springs

The weapon is hooked to its own position and rotation springs. Just like the camera it supports bob, shakes and external forces. It applies player local velocity to its position when walking and falling. The weapon has special position and rotation springs for additional forces such as recoil. The pivot point of the weapon is also hooked to a spring, and manipulating this at runtime can be quite useful.



Offset

Weapon position offset relative to the weapon object position. This position is where the weapon "wants to be". If you move it away from the target value using external force, it will immediately try to go back to the target position.

Exit Offset

This position is used by the parent FPCamera for switching weapons. It will move the current weapon model to its Exit Offset, switch weapons and move the new weapon into view, starting at its Exit Offset.

Pivot

This setting manipulates the pivot point of the weapon model. A value of "0, 0, 0" will leave the object's pivot at the point defined in the 3d object file.

The relation between pivot and weapon model position is affected by rotations. This may lead to unexpected behaviour when moving the pivot in the editor. Before editing weapon pivot it is best to turn off weapon shake and set weapon rotation offset to (0, 0, 0).

Pivot Stiffness

Pivot spring stiffness - or mechanical strength - determines how loosely or rigidly the pivot spring behaves. A low value will result in a soft, swaying motion, and higher values will result in stronger spring movements.

In some scripting situations you may need to move the weapon offset and pivot offset at the same time. In these cases you may want to make sure that the two springs share the same Stiffness and Damping settings, and are moved approximately the same distance, or one spring will finish before the other. On the other hand, this results in a more complex animation and may sometimes be desireable. If you run into problems related to pivot switching in script, try calling the "SnapPivot" method of vp_FPWeapon.cs.

Pivot Damping

Pivot spring damping makes spring velocity wear off as it approaches its rest state. Low values will result in a very loose, swaying motion, while higher values can result in either motion that quickly grinds to a halt, or a stiff shaking motion (much depending on the pivot stiffness setting).

Show Pivot

Toggles pivot point visualization on or off for editing purposes. The pivot point looks like a blue transparent ball. It can only be visualized when the game is playing.

TIP: Set Pivot Z to about -0.5 to bring it into view.

Spring Stiffness

Weapon spring stiffness - or mechanical strength - determines how loosely or rigidly the weapon spring behaves. A low value will result in a soft, swaying motion, and higher values will result in stronger spring movements.

Spring Damping

Weapon spring damping makes spring velocity wear off as it approaches its rest state. Low values will result in a very loose, swaying motion, while higher values can result in either motion that quickly grinds to a halt, or a stiff shaking motion (much depending on the weapon stiffness setting).

Spring2 Stiffness

Positional stiffness for the second weapon spring. This spring is intended for additional forces such as recoil. It is not used internally by vp_FPWeapon, but the vp_FPWeaponShooter component uses it for recoil. It can also be activated using the "AddForce2" script function of vp_FPWeapon.

Spring2 Damping

Positional damping for the second weapon spring. This spring is intended for additional forces such as recoil. It is not used internally by vp_FPWeapon, but the vp_FPWeaponShooter component triggers it for recoil. It can also be activated using the "AddForce2" script function of vp_FPWeapon.

Kneeling

Determines how much the weapon will be pushed down when the player falls onto a surface.

Kneeling Softness

The number of frames over which to even out each fall impact.

Fall Retract

Makes the weapon pull backward while falling.

Walk Sliding

Walk sliding moves the weapon in different directions depending on character controller movement direction.

Input Velocity Scale

This tweak feature is useful if the spring motion goes out of hand after changing player velocity. Just use this slider to scale back the spring motion without having to adjust lots of values.

Max Input Velocity

A cap on the velocity value being fed into the weapon swaying method, preventing the weapon from flipping out when the character travels at excessive speeds (such as when affected by a jump pad or a speed boost). This also affects fall sway.

TIP: The current speed used by weapon swaying can be displayed in script using:

Debug.Log(Controller.Velocity.magnitude);

Rotation Springs

Weapon rotation is affected via springs by mouse movements and character controller motion. It can also be affected by external forces such as falling impact, and additional forces such as recoil.


Offset

Weapon rotation offset. This angle is where the weapon "wants to be". If you turn it away from the target value using external force, it will immediately try to swing back to the target angle.

Exit Offset

This angle is used by the parent FPCamera for switching weapons. It will move the current weapon model to its Exit Offset, switch weapons and move the new weapon into view, starting at its Exit Offset.

Pivot

This setting manipulates the angle of the weapon model's pivot point at runtime. A value of "0, 0, 0" will use the value defined in the 3d object file.

TIP: The relation between pivot and weapon model position is affected by rotations. This may lead to unexpected behaviour when moving the pivot in the editor. Before editing weapon pivot it is best to turn off weapon shake and set weapon rotation offset to (0, 0, 0).

Pivot Stiffness

Pivot spring stiffness - or mechanical strength - determines how loosely or rigidly the pivot spring behaves. A low value will result in a soft, swaying motion, and higher values will result in stronger spring movements.

In some scripting situations you may need to move the rotation spring and pivot spring at the same time. In these cases you may want to make sure that the two springs share the same Stiffness and Damping settings, and are moved approximately the same distance, or one spring will finish before the other. On the other hand, this results in a more complex animation and may sometimes be desireable. If you run into problems related to pivot switching in script, try calling the "SnapPivot" method of vp_FPWeapon.cs.

Pivot Damping

Pivot spring damping makes spring velocity wear off as it approaches its rest state. Low values will result in a very loose, swaying motion, while higher values can result in either motion that quickly grinds to a halt, or a stiff shaking motion (much depending on the pivot stiffness setting).


Show Pivot

Toggles pivot point visualization on or off for editing purposes. The pivot point looks like a blue transparent ball. It can only be visualized when the game is playing.

TIP: Set Pivot Z position to about -0.5 to bring it into view.

Spring Stiffness

Weapon rotation spring stiffness determines how loosely or rigidly the weapon rotation spring behaves. A low value will result in a soft, swaying motion, and higher values will result in stronger spring movements.

Spring Damping

Weapon rotation spring damping makes spring velocity wear off as it approaches its rest state. Low values will result in a very loose, swaying motion, while higher values can result in either motion that quickly grinds to a halt, or a stiff shaking motion (much depending on the weapon stiffness setting).

Spring2 Stiffness

Angular stiffness for the second weapon spring. This spring is intended for additional forces such as recoil. It is not used internally by vp_FPWeapon, but the vp_FPWeaponShooter component uses it for recoil. It can also be activated using the "AddForce2" script function of vp_FPWeapon.

Spring2 Damping

Angular damping for the second weapon spring. This spring is intended for additional forces such as recoil. It is not used internally by vp_FPWeapon, but the vp_FPWeaponShooter component uses it for recoil. It can also be activated using the "AddForce2" script function of vp_FPWeapon.

Kneeling

Kneeling determines the amount of downward pitch force the weapon will receive upon fall impact.

Kneeling Softness

The number of frames over which to even out angular force resulting from a fall impact.

Look Sway

This setting determines how much the weapon sways (rotates) in reaction to mouse movements. Horizontal and vertical mouse movements will sway the weapon spring around the Y and X vectors, respectively. Rotation around the Z vector is hooked to horizontal mouse movement, which is very useful for swaying long melee weapons such as swords or clubs.

Strafe Sway

Rotation strafe sway rotates the weapon in different directions depending on character controller movement direction.

Fall Sway

This setting rotates the weapon in response to vertical motion (e.g. falling or walking in stairs). Rotations will have opposing direction when falling versus rising. However, the weapon will only rotate around the Z axis while moving downwards / falling.

Slope Sway

This parameter reduces the effect of weapon Fall Sway when moving on the ground. At a value of 1.0, the weapon behaves as if the player was falling. A value of 0.0 will disable Fall Sway altogether when the controller is grounded.

Input Rotation Scale

A tweak feature that can be used to temporarily alter the impact of mouse input motion on the weapon rotation spring, for example in a special player state.

Max Input Rotation

A cap on the mouse input motion being fed into the weapon swaying method, preventing the weapon from flipping out when extreme mouse sensitivities are being used.

Retraction

The Retraction feature is intended for running the system without a weapon camera. Basically, this feature will pull back weapons when too close to walls. It makes for more realistic weapon rendering, but can also be a little trickier to use.

Retraction tutorial

The first thing you will notice when removing the weapon camera is that all the default presets are currently adapted to weapon camera use (for starters the weapon will probably sit way too far away), so you will want to retweak some weapon settings. Here is a quick rundown:

  1. In the "Position Springs" foldout, modify "Offset:Z" until the weapon sits in its proper place along the Z-axis.
  2. Optionally, go into the weapon's "Rendering" foldout and reduce "Z scale" slightly until the weapon doesn't have a strecthed out / distorted perspective.
  3. Start the game and walk up to a wall so the weapon sticks through it while you are looking down at a ~45 degree angle.
  4. Go into the weapon's "Retraction" foldout and gently increase "Distance" until the weapon no longer intersects the wall.

  1. You will likely need to tweak recoil and other settings so they look better without the weapon camera.

If you manage to tweak all these things nicely, it will sometimes look even better without the weapon camera! For more info on pros and cons of the two options, see the Choosing a world intersection solution chapter.

Distance

The length of the raycast used for performing retraction. The weapon will be pulled back a distance corresponding to the length of the overlap. A typical value is 0.5.

Offset

This parameter will offset the retraction raycast horizontally and / or vertically in relation to the weapon. While the Retraction foldout is open, a debug ray will be drawn in the Scene view. The ray will be yellow if it doesn't intersect anything, and red if it does. For the best result, tweak the Offset parameter until it runs inside the weapon's barrel (if any).

Relax Speed

This slider can be used to adjust how quickly the weapon will ease back into its regular Z position after an intersection has ended.

Shake

This is procedural weapon rotation shaking, intended as a purely aesthetic motion to breathe life into the weapon. Super-useful for idle motions, but can also be used to rattle the weapon from wind turbulence when skydiving!


Speed

Determines the shaking speed of the weapon.

Amplitude

The strength of the angular weapon shake around the X, Y and Z vectors.

Bob

Weapon bob is the sinusoidal motion of the weapon, hooked to character controller velocity.


Rate

Speed of the weapon bob. X & Z rate should be (Y/2) for a classic weapon bob. To invert the curve, make X and Y negative. For weapon bob, X, Y and Z is angular bob. W is the position along the forward vector (pushing back and forth). A typical value for Y is 0.9.

Amplitude

The strength of the weapon bob. Determines how far the weapon swings in each respective direction. For weapon bob, X, Y and Z is positional motion. W is roll around the forward vector (tilting the head from left to right). A typical value for Y is 0.1.

Input Velocity Scale

This tweak feature is useful if the bob motion goes out of hand after changing player velocity. Just use this slider to scale back the effect without having to adjust lots of values.

Max Input Velocity

A cap on the velocity value being fed into the bob function, preventing the weapon from flipping out when the character travels at excessive speeds (such as when affected by a jump pad or a speed boost).

TIP: The current player velocity can be displayed in script using:

Debug.Log(Controller.Velocity.magnitude);

Require ground contact

This determines whether bob should stay in effect when jumping, falling or flying. Disabling this is useful for doing flying dinosaurs, underwater movement et cetera.

Step

The Step feature applies force to the weapon springs in order to simulate a fine footstep impact in sync with the weapon bob. A footstep force is triggered every time the vertical weapon bob reaches its bottom value.

TIP: Try exagerrating weapon Y bob while also using steps.

This feature was developed to achieve procedural weapon motions rivaling the very best FPS games out there. If used in concert with regular weapon bob (and with decent understanding of position, rotation and pivot springs) it is indeed possible to achieve very realistic looking footstep motions.

Min Velocity

This parameter sets the minimum squared controller velocity at which footstep impacts will occur on the weapon. The system will be disabled if is zero (default).

TIP: To measure the controller's squared velocity you can do this in script:

Debug.Log(m_Controller.Velocity.sqrMagnitude);

Step Softness

The number of frames over which to even out each footstep impact. A higher number will make the footstep softer (more like regular bob). A lower number will be more 'snappy'.

Position Force

A vector relative to the weapon, determining the amount of force it will receive upon each footstep. Note that this parameter is very sensitive. A typical value is lower than 0.01.

Rotation Force

Determines the amount of angular force the weapon will receive upon each footstep. Note that this parameter is very sensitive. A typical value is lower than 0.01.

Force Scale

This value scales the impact force. It can be used for tweaking the overall force when you are satisfied with the axes' internal relations.

Position Balance

This parameter simulates shifting weight to the left or right foot, by alternating the positional footstep force every other step. Use this to reduce or enhance the effect of "limping".

Rotation Balance

This parameter simulates shifting weight to the left or right foot, by alternating the angular footstep force every other step. Use this to reduce or enhance the effect of "limping".

Sound

Wield

This sound will be played when the weapon is being readied.

Unwield

This sound will be played when the weapon is being put away.

Animation

This foldout provides hooks for playing regular animations on a weapon model. Unity basically provides two ways of triggering animations on a simple model:

  1. Playing the clips from inside a single model (by animation clip).
  2. Playing the clips from separate model files (by file).

UFPS supports method 1. That means; for any model that has properly built-in animation clips, you can unfold it in the project view and select a clip , then drag it to an animation slot in the Inspector.

CHECKLIST:

  1. Always first make sure that the weapon model has animation clips in it after import.
  2. Then make sure the weapon prefab assigned under the vp_FPWeapon's 'Rendering' foldout has an 'Animation' component on it, which references all the clips you wish to play on the weapon.
  3. Only after this is properly set up, you can start filling the Animation foldouts of the vp_FPWeapon and vp_FPWeaponShooter components.
  4. Remember that these components can only use the very same animation clips that are listed in the unity Animation component.

For a brief explanation on the different use cases of regular animation versus procedural motion, see the Animations section of the Animation Concepts chapter.

Wield

An animation to be played on the weapon when it is readied.

Unwield

An animation to be played on the weapon when it is being put away.

Ambient

A random animation from this list will be played on the weapon automatically with random intervals. This is especially useful for alternating very subtle hand and finger movements, or temporarily removing the left hand when holding a rifle (as if to wipe it off) and can be a real realism and immersion factor!

Ambient Interval

Average random interval in seconds between ambient animations.

Shooters

The vp_FPWeaponShooter class adds firearm properties to a weapon. The component should be added to a weapon GameObject that already has a vp_FPWeapon component added to it. The script will manipulate the weapon component for recoil and manages firing rate, accuracy, sounds, muzzle flashes and spawning of projectiles and shell casings. It also has basic ammo and reloading features.

The weapon shooter class inherits from vp_Shooter, a generic firing class that can easily be used for other shooters in your world - AI soldiers, traps, helicopters, robotic turrets - you name it! Add a vp_Shooter component to give all these things the ability to fire projectiles with muzzle flashes and shell ejection.

Projectile

The Projectile foldout handles the birth aspects of any projectile objects spawned by the weapon.


Firing Rate

The normal firing rate of the weapon. If the player continuously presses down the fire button, shots will be fired using this as the minimum time interval in seconds.

Tap Firing Rate

The fastest possible firing rate of the weapon. If the player "spam clicks" the fire button (that is; presses and lets go of it many times in rapid succession) this will be the shortest allowed interval between bullets fired.

Prefab

This should be a gameobject with a projectile logic script added to it, such as vp_HitscanBullet. But remember that a projectile does not have to use a vp_HitscanBullet script. You could put any gameobject here and a copy of it will be spawned when the weapon is fired. Feel free to write your own crazy projectile components! For more information about creating a bullet prefab, see the Projectiles chapter.

Gameobjects can not be saved using the preset system, so they need to be hooked manually each time you create a new vp_FPWeaponShooter component.

Scale

This parameter will scale each projectile object by the set amount. If using a vp_HitscanBullet projectile, this will be the scale of the resulting bullet hole object.


Count

The amount of projectiles to be fired simultaneously. Each projectile will get its own unique spread. However only one shell will be ejected and the muzzleflash will display as if one projectile was fired.


Spread

The conical deviation of the projectile. This parameter randomly alters the direction of the projectile by "Spread" degrees. A value of 1 means the projectile will deviate 1 degree within a cone from the player to the aim point. A value of 360 means the projectile will be emit from the player in a completely random direction (essentially within a sphere). This is good for scripting shotgun type weaponry or manipulating accuracy at runtime.

TIP: To emulate the famous Classic DOOM shotgun, set "Firing Rate" to 1, "Count" to 7, "Spread" to 6 and "Shell > Eject Delay" to 0.5. Oh yeah..

Spawn Delay

This is the delay between the fire button being pressed and a projectile is launched. Useful for weapons such as hand grenades, where you may want to play a short animation (i.e. pulling out the sprint) before the actual projectile is launched (or in this case thrown).

Motion

The Motion foldout contains parameters that manipulate the position and rotation of the weapon when discharged.

Position Recoil

A force added to the secondary position spring upon firing the weapon. Setting Z to a negative number will make the weapon increasingly "kick like a mule". Keep in mind that achieving a good positional recoil depends in large part on tweaking "Position > Spring2" of your vp_FPWeapon component. Check out the demo weapon presets for some example Spring2 Stiffness and Damping settings.

Rotation Recoil

A force added to the secondary rotation spring upon firing the weapon. Setting X to a negative number will make the weapon twist upward like a pistol. Rotation Recoil applied to the Z axis will make the weapon twist to the left or right for each shot fired (direction will be chosen randomly).

Keep in mind that achieving a good angular recoil depends in large part on tweaking the Rotation > Spring2 of your vp_FPWeapon component. Check out the demo weapon presets for some example Spring2 Stiffness and Damping settings.

Rotation Recoil Dead Zone

When using Rotation Recoil around the Z axis, this parameter can be used to tweak the aggressiveness of the recoil. The function works by limiting the minimum possible Z rotation applied. A high Dead Zone gives sharper / crazier Z twist.

Position Reset

Upon firing, the primary position spring will snap back to its rest state by this factor.

Rotation Reset

Upon firing, the primary position spring will snap back to its rest state by this factor. This can be used to make a weapon always fire in the forward direction regardless of current weapon angles.

Position Pause

Upon firing, any forces acting on the primary position spring will freeze and fade back in over this interval in seconds.

Rotation Pause

Upon firing, any forces acting on the primary rotation spring will freeze and fade back in over this interval in seconds. This is typically useful if the weapon has a pronounced Fall Sway and the player fires it in mid-air. Without a Rotation Pause, the weapon may fire upwards or sideways while falling.

Dry Fire Recoil

This parameter multiplies the recoil value when the weapon is out of ammo. This can be used to simulate pulling the trigger with no discharge.

TIP: Make 'MotionDryFireRecoil' about -0.1 for a subtle out-of-ammo effect.

Recoil Delay

This is the delay between the fire button being pressed and the recoil kicking in. Useful for weapons such as energy guns that may have a warmup animation prior to each shot being fired.


Muzzle Flash

The Muzzle Flash foldout handles logic for displaying the weapon's muzzle flash (if any) and animating its rotation and opacity.


Prefab

This should be a mesh with a "Particles/Additive" shader and a vp_MuzzleFlash script added to it. For more information about creating a muzzle flash prefab, see the Muzzle Flashes chapter.

Gameobjects can not be saved using the preset system, so they need to be hooked manually each time you create a new vp_FPWeaponShooter component.

Position

Muzzle flash position offset relative to the FPCamera.

TIP: Set Position Z to a value larger than 0.5 to bring it into view.

Scale

This parameter will scale the muzzle flash object by the set amount.

Fade Speed

This amount of alpha will be deducted from the muzzle flash shader 60 times per second. When the weapon is discharged, the muzzle flash will be set to full alpha. It will then immediately start fading out at "Fade Speed". Note that the default (full) alpha for the "Particles/Additive" shader is 0.5.

Muzzle Flash Delay

This is the delay between the fire button being pressed and Muzzle Flash being shown. Useful for weapons such as energy guns that may have a warmup animation prior to each shot being fired.

Show Muzzle Flash

Toggles muzzle flash visualization on or off for editing purposes. The muzzle flash can only be visualized when the game is playing.

Set Position Z to a value larger than 0.5 to bring it into view.

Shell

The parameters under this foldout govern how shell casings are spawned and set in motion by the weapon.


Prefab

A gameobject that will be ejected from the weapon upon firing. This should be a mesh with a vp_Shell script added to it. For more information about creating a shell prefab, see the Shells chapter.

Gameobjects can not be saved using the preset system, so they need to be hooked manually each time you create a new vp_FPWeaponShooter component.

Scale

This parameter will scale each ejected shell object by the set amount.

Eject Position

Shell eject position offset relative to the FPCamera.

Set Position Z to atleast 0.5 to bring it into view.

Eject Direction

The vector in relation to the FPCamera, along which shells will be ejected from the Eject Position. To send a shell flying forward, upward and to the right, set Eject Direction to 1, 1, 1.

Eject Velocity

The amount of force (positional speed) added to the shell's rigidbody object when instantiated. This is what sends the shell flying.

Eject Spin

When a shell is instantiated it receives a completely random torque (rotation speed, or spin). This parameter scales the spin. A value of 0 means the shell won't spin at all. A value of 1 means it will spin like crazy.

Eject Delay

Time to wait before ejecting the shell after firing. This is very useful for i.e. shotguns and grenade launchers. For example, you could use a traditional animation for a pump action shotgun, and sync "Eject Delay" to the animation.


Sound

The Sound foldout defines how the shooter sounds when fired.


Fire

The standard firing sound of the weapon.

Gameobjects can not be saved using the preset system, so they need to be hooked manually each time you create a new vp_FPWeaponShooter component.

Dry Fire

This sound is played if the player attempts to fire when the weapon is out of ammo.

Fire Pitch

This parameter optionally pitches the sound of each shot fired slightly different to get a more organic firing sound. Variations in pitch should be kept minimal. A typical Min-Max range would be 0.95-1.05. This parameter allows you to use the same audio file with different pitch for different weapons.

Fire Sound Delay

This is the delay between the fire button being pressed and the fire sound being played.

Animation

The Animation foldout contains any animations to be played on the weapon by the shooter component.

TIP: For many weapons (especially firearms with no prominent moving parts) you can often get a long way by just using recoil forces.

For a checklist of the steps needed to play animations on a weapon model, see Weapons > Animation.

For more info about the different use cases of procedural motion versus regular animation, see the chapters Animation Concepts > Animations.

Fire

An animation to be played on the weapon when it is discharged. Fire animations are useful for things like pump action shotguns or a bow and arrow, where you really want more stuff going on than just force recoil.

Melee Attacks

The vp_FPWeaponMeleeAttack component can be used to generate super-fluid melee animations that blend dynamically between each other and react to the environment and forces affecting the player. The system was originally devised to see whether melee combat would be feasible using only spring physics and entirely without traditional animation. It worked out quite well.

For example: If you swing about a melee weapon while running, jumping or falling, the weapon will animate very organically, affected by character velocity as if carried by real, elastic muscles. If you stand close to an explosion, your arm will twist almost as if you're about to loose hold of the weapon. If you hit a solid object, the weapon will stop and bounce back.

Arguably, it would be hard to get these things going at the same level of quality using only traditional animation. However, this system is still in an experimental stage and certainly not the easiest to use! It has been included in the package by popular demand. But rest assured: Here Be Dragons ;)

Tutorial (Basic)

The quickest way to set up a new melee weapon

The quickest way is simply duplicating the existing demo mace, which has a range of melee swings that should work for most prototype purposes.

  1. Open DemoScene1
  2. Unfold the player and camera components and select "4Mace"


  3. Drag it into your project view somewhere to create a prefab
  4. Open another scene with an fps player, for example "cleanscene"
  5. Drag the mace prefab to the camera object of the player
  6. Done. Now you can just change the mesh and sound fx in the Inspector to get your own melee weapons going.

Making adjustments

System Walkthrough

The melee attack system uses a quite complex state setup. Before you move on, you will want to have a thorough understanding of UFPS states and presets. It's also a very good idea to have a look at how the mace and its components are set up in DemoScene1 to get a feeling for how everything is put together. You may also want to study the comments in the melee attack script.

To quickly get a grasp of what's going on, the following walkthrough might help.

Weapon poses

  1. Load DemoScene 1 and press Play.
  2. Go to the second screen, "EXAMPLES", and select the "Barbarian" demo preset.
  3. At the top of the Hierarchy, find the "DemoPlayer" object, unfold its "FPSCamera" child and select the "4Mace" weapon object childed under "4MaceTransform".

  1. Unfold the "vp_FPWeapon" component of the mace and unfold its "States" list (make sure you're in the weapon component and not the weapon melee attack component under it).


  2. In the state list, click on the state named "SwingLeft".
  3. Then toggle the state named "PullRight" on and off while watching the first person game view.

As you can see the mace weapon component has a bunch of states for various poses that might come in handy during melee combat. Toggling them will move the mace by having its springs act like muscles blending between the positions.

However, the motion does not happen automatically (you need to toggle it manually) and the movement is quite sluggish and not very violent. Also, nothing will happen if you hit something. We need to add timing, collision detection, impact effects and violent forces! This is the purpose of the vp_FPWeaponMeleeAttack component.

Attack states

  1. In the Inspector, with the "States" foldout still open, scroll down and unfold the "vp_FPWeaponMeleeAttack" component.
  2. Uncheck the "Pick a random state for each attack" checkbox and open the "States" foldout right above it.


  3. Click on one of the states in the state list, whose names begin with "To" ... (any one except the Default state).
  4. Go to the game view and click the left mouse button. The mace should get swung in the direction you chose. No matter how many times you swing the mace, it gets swung in the same direction. Also, this time around the motion is more violent and there are sound effects. If you hit something, the mace will repel, spawn particles and (in case it was a physics object), add forces to the target.
  5. Go back down and check the "Pick a random state for each attack" checkbox.
  6. Unfold the "Weapon States" tab at the top of the same (FPWeaponMeleeAttack) component.
  7. Again, fire repeatedly and watch the bottom "States" list along with the top "Pull" and "Swing" slots while doing so.

What happens here is that a random melee attack state gets selected every time you press fire. Also, a corresponding "Pull" and a "Swing" state gets enabled. Importantly, they do not get enabled on this (melee attack) component, but on the above weapon component. Also, the states get enabled with a slight delay inbetween them. On top of this, soft angular and positional forces are added to make the motion more dramatic.

  1. Scroll the Inspector so you can see both the unfolded weapon "States" and the unfolded melee attack "States" at the same time.
  2. Go back to the game and press and hold the left mouse button. Watch how the two components work together to manipulate the weapon springs of the mace.

The melee attack sequence

When a melee attack is initiated, this is what happens under the hood:

  1. A random Attack state is chosen on the melee attack component.
  2. The Pull state of the chosen Attack is enabled on the weapon component, moving the weapon back in preparation of attack.
  3. A delay is imposed by the melee attack component. Basically, this is to give the weapon time to pull back before getting swung.
  4. The Swing state of the chosen Attack is enabled on the weapon component. This will make the weapon transition to its final angle.
  5. In order for the transition to become more fast and violent, angular and positional forces are applied to the weapon component.
  6. After a very short delay (about half-way through the attack) a check is done to see if we're hitting anything. If so, particles and damage take effect.
  7. If we hit something, the Swing state is interrupted and the weapon is reset and goes back to its rest state.

Types of states

The system uses 3 types of states. The melee attack component can have an unlimited amount of Attack states, each referencing two states on the weapon component: the Pull state (for raising the weapon) and the Swing state (for slashing). Attacks and their sub-states are alternated randomly when the player holds the attack button. In other words:

Pull

A regular weapon state for pulling back the weapon and gathering force in preparation of the attack. Sits on the weapon component.

Swing

The final orientation of the weapon at the end of the attack (striking / thrusting / slashing). Sits on the weapon component.

Attack

This state generates animation sequences by handling timing, physics and the enabling & disabling of the above states on the weapon component. It sits on the melee attack component.

Default

The regular, bottom-most state of any vp_Component. On the vp_FPWeaponMeleeAttack object, this state is only intended to be used at the design stage. Unless a weapon only has one single attack, each attacks should use a custom state.

Tutorial (Advanced)

Overview

There are basically three stages to designing a melee attack:

  1. Begin by designing its Pull and Swing poses as togglable states on the weapon component.
  2. You then design the motions, forces and effects that go along with those states. This work is done on the Default state of the melee attack component.
  3. The melee attack state is saved to a new preset, then added to the state list of the melee attack component where it can be activated randomly or specifically at runtime.

Workflow

1. Decide how the weapon should move

For this example, we'll create an "up-right to down-left" sword swing. This could be visualized as raising a sword to above your right shoulder then slicing your opponent diagonally from his left shoulder to his right hip.

2. Create the Pull state

Go into you weapon component, open the Position and Rotation foldouts and modify the position and orientation of the weapon until it is raised to the right of - and above - the camera, pointing over your shoulder. Save this tweak by clicking the Preset -> Save Tweaks button (will create a new preset text file containing only the parameters that you have changed). Name this Pull state something fitting, For example "PullUpRight".

TIPS:

  1. You may want to modify the Rendering -> Clipping Planes parameter in case the model gets too close to the camera.
  2. Modifying the pivot position and angle of the model can be used to create more complex motions.

3. Create the Swing state

Same process. Go into you weapon component and modify its Position, Rotation and Rendering settings until the weapon is pointed forward and sits below and to the left of the camera. Save the preset as, e.g. "SwingDownLeft".

4. Assign the states to the weapon component

Add two new states and name them, e.g. "PullUpRight" and "SwingDownLeft". Drag your new presets to the corresponding slots.

5. Create the attack script

Go to the FPWeaponMeleeAttack component and disable "Pick a random state for each attack". This allows you to design an attack using the "Default" state, that is; without other states getting enabled randomly, which may be interrupting and confusing.

IMPORTANT: Make sure the Weapon States foldout has the correct names for the Pull and Swing states you just created on the weapon.

TIP: You can also start off by duplicating an existing attack. In the project view, right click on a melee attack state and select Duplicate. Rename the new script and open it in a text editor. Don't forget to update the names of the WeaponStatePull and WeaponStateSwing with the names of your new pull and swing states.

6. Create an Attack state

Save the state as a new preset. When done, open the "States" foldout, click "Add State" and assign the preset you just saved. It doesn't really matter what you name the states on the melee attack component, unless you mean to enable these states from code later rather than use the random logic. The important thing is that the "Pull" and "Swing" fields in each preset correspond to actual states on the weapon component.

7. Test the attack in-game

As you get more and more weapon poses and melee attack states that use them, the "random attack" mode will become more and more organic and entertaining.

8. Tweak the swing motion

... in the attack script to adjust the speed / violence of the swing. The "SwingPositionSoftForce" and "SwingRotationSoftForce" parameters will add force to the weapon over several frames, the amount of which is determined by "SwingSoftForceFrames". The fewer frames, the more instant the attack will appear. It is recommended to keep it at the default value for smooth motion, and instead regulating the force of the attack using the force parameters.

9. Tweak the recoil force

The recoil force is an impulse that takes effect whenever the weapon hits a solid object such as an enemy or a concrete wall. Typically, the recoil force should be roughly the inverse of the swing force. For example: if the weapon travels left across the screen and hits something, it should repel back to the right.

10. Tweak the physics force

This force is applied to any rigid bodies that we hit. The direction of the force is currently always straight away from the player. The "DamageForce" parameter simply determines the strength of the force impulse.

With the random state checkbox unchecked, you can control which attack gets played by setting the state of the melee attack component from script. For example, you may want to bind a specific slash to a certain button.

Debug objects

When you perform melee attacks with the vp_FPWeaponMeleeAttack's "Swing Motion" foldout open in the Inspector, red and yellow spheres will appear. The big (yellow) spheres show where the spherecast used for collision detection spawns. In reality, it is not made up of spheres, but is a wide, continuous tube. The small (red) sphere shows where the spherecast detects a collision with the environment.

This concludes the docs for the experimental UFPS melee system! As you may have noticed the workflow can be a bit challenging :) but the end result can sometimes be really cool. Hope you'll have fun with it!

Player Body

UFPS comes loaded with player body features, designed for characters with a need to move around and fire guns a lot! Its weapon spring physics make for a novel mix between traditional animation (body) and procedural animation (1st person arms and weapon). The feature set can be divided into five categories, all explained in the following chapters.

Features Overview

Body animator with headlook

The UFPS player event system connected to a Mecanim animator controller, along with specialized body orientation and headlook features.

Full body awareness

Systems to provide the experience of being a human within a body (and not just a floating camera).

3rd person camera view

An experimental "survival horror-style" over-the-shoulder camera view, with logic to make guns fire at the camera's look point.

Hand-aiming & recoil

The rotating of a hand to make it aim a weapon correctly, and the propagation of recoil force from the weapon onto the hand.

Ragdoll handling

The physics-based animation of a human body when a player gets killed and falls to the ground / gets tossed away.

Body animator with headlook

UFPS has its own animator scripts with a headlook logic specialized for gunplay. The headlook animates bone falloffs within the spine according to player states in very lifelike ways.

For example: if you look around without firing or aiming, you head will turn flexibly and freely of your torso. This gives the appearance of a character that is "alertly" scanning the environment around it. The second you aim or fire, the torso and arm will "stiffen up" and turn to where your head is pointed, aiming the gun there. This quite effectively communicates a sudden interest in a world look point. Lower body (legs and feet) rotate independently of the upper body (spine, arms and head). For example: the character can stand still and look around quite freely without moving its feet.

These animator scripts are tightly integrated with the UFPS player event system and designed for use with the provided "UFPSExampleAnimator" Mecanim controller. When an UFPS vp_Activity event starts or stops, a corresponding parameter gets activated in Mecanim, blending the animations into that state. The body animator also maintains floating point values (moving, turning, pitching and jumping), triggers (climbing, reloading, sliding out of control) and info on the weapon type (firearm, melee) and grip (one handed, two handed) for Mecanim to play suitable animations.

Full body awareness

UFPS allows you to look down at your body as you walk, fight, crouch, run and jump around in first person. Since there is such a strong emphasis on wild, spring based camera motions, extra care is taken to keep the camera in sync with your 3d head, making sure the camera view doesn't clip the body model, all while allowing the camera to move around as freely as possible.

In 1st person the material of the 3rd person head and arms is set to an invisible, shadow casting material in order not to clip the camera or interfere with 1st person arms and weapons. If you unwield the current weapon, the Mecanim arms will come back into visibility for walking and sprinting.

Furthermore, the weapon class has logic to procedurally and smoothly move weapons into realistic positions when looking down. When you switch back to 3rd person, the head and arms reassume their original materials and the bodyanimator exchanges some aspects of it logic for movement that looks better in 3rd person.

All in all complicated stuff, and very effectful when it comes together!

Note: When playing in 1st person in the editor, you will spot this guy bouncing around in the Scene view, arms flying everywhere and legs sticking through the ground. Not to worry! This is not how the character will appear in 3rd person or multiplayer - it's just the full body awareness systems at work and this will never be rendered into the actual game.

Nevermind the "headless dude" ...

3rd person camera view

This experimental feature provides a "survival horror-style" camera that collides with the environment, reacts to explosions and allows for some pretty action packed precision gunplay (this feature was originally a by-product of testing the body systems, but turned into a decent feature of its own).

While this works really well with camera-to-level collision and certainly opens the door to your own Tomb Raiders, Resident Evils and MMOs, it is far from glitch-free at time of writing, and for the time being provided as-is, for animation testing purposes and as a starting point for those who may be interested in developing it further.

Except for arms, the 1st and 3rd person player models are actually one and the same. When you switch to 3rd person, the head and arms again become visible and the bodyanimator exchanges some aspects of its logic for motion that looks better in 3rd person.

TIP: For an example of player appearance in 3rd person, open up the "DemoScene3" or "SkyCity" level and press the "Toggle3rdPerson" key

(default: "V").

Hand-aiming & recoil

"Cosmetic" precision aiming is taken care of by a simple script that sits on the player's right hand, rotating it to keep the weapon aimed at the player's look point. This has no real gameplay effect (bullet precision is regulated in the shooter script) but it makes things look fairly alive and "realistic". This aiming script also applies the current weapon's recoil when shooting which is quite cool.

Note that this subset of the body system is still in an early prototype state. The feature is currently "rough around the edges" and quite challenging to calibrate but it gets the job done when setup right.

Ragdoll handling

"Ragdolling" is always lots of fun and very entertaining in action, especially with a suitable application of high explosives! When ragdolling is enabled in UFPS, the body of any killed player will crash to the ground or get tossed away in a "physically realistic" manner adapted to the current situation. Keep in mind that the ragdoll handler doesn't set up a ragdoll for you (the ragdoll components must be added to you character model by means of the Unity ragdoll wizard or some other method).

What it does do is initialize things on startup, enable the ragdoll on death and disable it on respawn. There is also the "VelocityMultiplier", which has the momentum of the charactercontroller carry over into velocity on the ragdoll upon death. This can have quite cool and sometimes hilarious results :).

Player Body Setup

Introduction

To create a brand new player completely from scratch it is easiest to start with an existing (body-less) player prefab. If you want to set up a basic, functioning player for learning purposes, you may want to study this chapter before tackling full player bodies.

The full animated player body system - between UFPS and Mecanim - is really a quite complex beast in total. Good news is: for the most part it's a one-time process per character!

The "Body" child object

The main difference between a basic UFPS player setup and one with a body, is that in addition to the "FPSCamera" child object, the latter also has a "Body" child gameobject. (Edit: in the first release of 1.4.8 this is actually named "Hero".) This object basically contains an animated player model at the local position and rotation (0, 0, 0).

"Weapons" vs. "weapon props"

In UFPS there are two objects for each weapon, a "real" one for 1st person and a "prop" for 3rd person. The 1st person weapon object manages all the game logic and fx. The 3rd person weapon is only a cosmetical one for 3rd person views, AI and multiplayer remote players. That said, spring-based recoil from the vp_FPWeapon can be made to affect the hand and weapon of your 3rd person body model by means of the vp_3rdPersonWeaponAim component.

When you toggle to 3rd person, the 1st person weapon becomes invisible and begins firing any bullets from the world position of the (now visible) 3rd person weapon props. Behind the scenes, though, it is always the same vp_FPWeapons and vp_FPShooters that take care of all the logical dirty work, including accuracy, projectile / shell spawning, muzzleflashes and so on.

Good to know for Artists

Study the Hero player hierarchy in the DemoScene3 and SkyCity maps, aswell as this section on player body anatomy.

Good to know for Scripters

Study the comments in the vp_BodyAnimator and vp_FPBodyAnimator scripts along with the player setup in the scenes, aswell as this section with body scripting notes.

Tutorials

Setting up a basic, ragdolled player body

  1. Begin with a fully working UFPS player without a body, such as the "AdvancedPlayer". You can also set one up from scratch (see this chapter).

  1. Acquire a skinned, Mecanim-ready body model with an avatar. A good place to start is the Unity Asset Store.

  1. Always begin by applying ragdoll components (colliders, joints, rigidbodies) to the model. This can be done using Unity's built-in ragdoll wizard.
  2. Place the free-floating body over a floor collider to make sure it "ragdolls" properly. You can test this by starting and stopping the game a few times while studying the body model in the Scene view.

  1. Name the body object "Body" and make it a child of the root player object (for example: "AdvancedPlayer").

  1. Make sure the body's local position and rotation is (0, 0, 0).

  • IMPORTANT: If the body's local position and rotation is not (0, 0, 0) it will not be attached properly to the charactercontroller.
  • The scale of the Body child object would usually be kept at (1, 1, 1) but can actually be set to any scale you like. Please remember that this is not true for the main player gameobject. For information about scaling the main player gameobject (in the case of giants, dinos, children, hobbits) see this help post.

Start the game and hit the "Toggle3rdPerson" key (default: "V"). The player should now have a basic - albeit stiff - body attached to charactercontroller as it moves around in the scene. To make it animate and ragdoll in response to game events, please see the next tutorial.

Enabling animation, headlook and ragdoll handler

  1. Assign a Mecanim "Animator" component to the "Body" gameobject.

  1. In the "Controller" slot, assign the default "UFPSExampleAnimator".

  1. In the "Avatar" slot, assign a Mecanim avatar that was created for your model.

  1. Root motion should always be set to OFF, or the body model could start walking away from your charactercontroller.

  1. Assign a vp_FPBodyAnimator component to the "Body" gameobject.

  1. Time to configure the animator for headlook. With the "Body" object's vp_FPBodyAnimator visible in the Inspector, unfold the hierarchy until you find the head bone of the character (usually an object named "Head"). Drag this gameobject from the Hierarchy view to the Head Bone slot of the vp_FPBodyAnimator component.

  1. Look a little bit further up the hierarchy to locate the lowest spine bone. The bone directly above the hips / pelvis is usually what works best (likely an object with "Spine" in its name). Drag this gameobject from the Hierarchy view to the Lowest Spine Bone slot of the vp_FPBodyAnimator component.

  1. For now, leave all remaining settings of the vp_FPBodyAnimator at their defaults.

  1. Add a vp_RagdollHandler component to the "Body" gameobject and assign the model's head gameobject to the "Head Bone" slot.

  1. Time to take the animated character for a test drive! Start the game and hit the "Toggle3rdPerson" key (default: "V") and hopefully the player is now moving its arms and legs in response to input, aswell as "ragdolling" when it dies.

Done! Toggle back to 1st person, and you will likely find that the player has too many arms in the 1st person view. Perhaps you can even see the inside of the player model's head (teeth, tongue, eyballs and whatnot). To fix this see the following section.

Removing head clipping and extra arms

If your player appears to have too many arms or you can see inside of the player model's head, you need to make the body model's head and arms invisible in the 1st person view. This can be done in two ways. Here is the easiest one:

  1. Go to the Hierarchy view and select the head and upper right arm bones (gameobjects) of your player.

  1. Give these bones each a scale of (0, 0, 0).

  1. That's it! Head clipping and extra arms should now be resolved for basic 1st person testing.

This quick-fix will not currently work in 3rd person, will break ragdolls and will cause your head and arms to cast no shadows. To solve all of this the proper (but more labor intensive) way please see this tutorial.

Adding weapon props for 3rd person

  1. Unfold your body hierarchy until you find the right hand gameobject, and create a child gameobject under it (alongside the finger bones) named "Weapons". Make sure the new gameobject's local position and rotation is (0, 0, 0). The right hand bone can usually be found under a spine bone -> right shoulder -> right arm and so on down the hierarchy.

  1. Now, for every one of your 1st person weapons (that should also be visible in 3rd person):
  1. Create a child gameobject under the right hand "Weapons" child. Name it the same as the corresponding 1st person weapon. Make sure this gameobject's local position and rotation is (0, 0, 0).
  2. Add the following components to the new 3rd person weapon:
  1. Set up the mesh filter and mesh render to display a 3rd person prop for your 1st person weapon.

TIP: The typical 1st person weapon model is unsuitable for 3rd person because it has animated arms on it. Also, 1st person weapons may be way too highly detailed to be appropriate for AI or multiplayer remote players. Re-using pickup gameobjects can often be a time saver for creating 3rd person weapons. The model and shader can usually stay the same (as long as there are no arms).

Just be sure to
remove any and all pickup components from the gameobject (Sphere Collider, Audio Source, Rigidbody, Box Collider, vp_ItemPickup, vp_Respawner). This is very important to avoid strange gameplay bugs.

Basically, the only remaining components on the 3rd person weapon object (at this point in the tutorial) should be a
Mesh Renderer and a Mesh Filter.

If you start the game now you will notice the player having one or more weapons in its hand. However, the weapons are active always, many at a time, and have no logical connection to their 1st person counterparts. They may also be pointing in all sorts of directions. We need to adjust position and rotation of the weapons.

Adjusting the position and rotation of weapon props

For each weapon prop in turn:

  1. Disable all weapon props except the one you wish to tweak.

  1. Select the first weapon prop and press "F" (this will focus editor scaling and rotation to that weapon which is essential for the task).

  1. Position the weapon so that it sits as snugly / realistically in the character's open hand as possible. The straight index finger should be in line with the trigger. The pistol grip should sit firmly between the base of the thumb and index finger.

TIP: After you have positioned the first weapon prop, you can often just copy position and rotation onto the remaining ones (assuming the models have similar pivot points). To do so, click the little cog wheel of the first weapon's Transform component -> "Copy Component". Then in the Transform component of the next weapon, cog wheel -> "Paste Component Values". This will give you decent positioning for all weapons in a second with only minor tweaks remaining!

IMPORTANT: When done tweaking weapon positions, always make sure to enable all the weapons before you press play. Otherwise their aiming logic could break later. Basically, whenever the game is not playing, in the editor the character should always have a "bundle of guns" in its hand. These will be hidden on startup by the WeaponHandler.

  1. Adjust the transform scale of the weapon if needed. Sometimes this is essential for a realistic grip (scaling of 3rd person weapon props will have no effect on gameplay logic).

  1. Go to the corresponding vp_FPWeapon (childed to the main FPS camera) and unfold its "Rendering" foldout.

  1. Drag the scene gameobject of the 3rd person weapon prop into the "Rendering" -> "3rdPersonWeapon" slot. This will tell UFPS which 3rd person weapon prop to enable when the camera view is toggled from 1st to 3rd person.

Start the game and temporarily disable the player's inventory component for access to all weapons. As you toggle weapons, the player should now hold each weapon properly in its hand. Muzzleflashes and shells ejection may be slightly off, though. Read on to fix this ...

Defining spawnpoints for muzzleflashes and shell casings

If you see muzzleflashes and shells spawning at the wrong positions, you need to create, position and orient "Muzzle" and "Shell" child gameobjects for your weapon props.

Muzzle flash
  1. Create an empty gameobject, name it "Muzzle" and make it a child of the weapon prop.

  1. Set the muzzle transform's localPosition to (0, 0, 0) and then tweak the position until the arrow origin is located ever so slightly in front of the muzzle of the gun.

  1. Set the localRotation to (0, 0, 0) and then tweak it if necessary until the Z axis (blue arrow) points in the exact firing direction of the weapon.

Shell ejection
  1. Create an empty gameobject, name it "Shell" and make it a child of the weapon prop.

  1. Set the shell transform's localPosition to (0, 0, 0) and then tweak the position until the arrow origin is located in the middle of the weapon's shell ejection port.

  1. Set the localRotation to (0, 0, 0) and then tweak it if necessary until the Z axis (blue arrow) points in the direction that you want the shells to fly when firing.

Re-using weapon groups

After you have created a "Weapon" group for one character, you can duplicate and re-use that weapon group on characters that should carry the same arsenal. You may need to reposition the weapons in their hands and you will need to reconnect the weapon props with their new host vp_FPWeapons, but atleast you can save a few minutes of little work this way.

Ok, so far we've covered mosts steps needed to create working 3rd person weapons! However, at this point you will have probably noticed the weapons pointing in slightly different directions from where bullets hit when firing. To fix this see the following tutorial ...

Calibrating 3rd person weapon aim

By default, weapon aiming of the player model is a result of the Mecanim animation used. Along with headlook this will make the arms and weapon point in roughly the right direction (just not right enough to look good in 3rd person).

The vp_3rdPersonWeaponAim component can be used to make a character's main hand + weapon aim more accurately at the screen crosshair. This component also imposes recoil from the active vp_FPWeapon onto the hand of the player model, which looks really cool.

DISCLAIMER: This subset of the body system is still in a prototype state. Logic and workflow is far from ideal and full of lore. Here be dragons!

Please note that melee weapons do not need a vp_3rdPersonWeaponAim component, since they have no need for projectile recoil or aiming.

Preparation checklist
  1. Make sure that you can see the Game View and Scene view simultaneously while playing the game. Also, make sure to not use the "Maximize on play" mode.

  1. Make sure the parent of the 3rd person "Weapons" group is the right hand bone of the character and that its name has the letters "hand" in it. If the name does not, fix this or drag the hand object into the vp_3rdPersonWeaponAim component's "Hand" slot in the Inspector.

  1. Disable the player's vp_PlayerInventory component for access to all weapons while editing.

  1. Always make sure that all the 3rd person weapon props are enabled before you press play (this goes not just for this tutorial, but is always true). Otherwise aiming logic will fail to initialize.

Calibration steps
  1. Select your target 3rd person weapon prop and assign a vp_3rdPersonWeaponAim component to it.

  1. Start the game and hit the "Toggle3rdPerson" key (default: "V").

  1. Select the root player object in the Hierarchy view so that it becomes visible in the Inspector.

  1. Go to the Game view and turn the player around using mouselook until its transform rotation in the Inspector is roughly (0, 0, 0).

  1. Select the target weapon prop object and, in the Inspector, unfold its vp_3rdPersonWeaponAim component.

  1. Scroll down a bit to enable "Keep Aiming". Then go to the Game view, wield the weapon and press the Zoom key (default: right mouse button) to make the player raise its weapon. As long as "Keep Aiming" is enabled the weapon should now remain in the aim state, making tweaking much, much easier.

  1. There is a fair chance the weapon is now being pointed in a completely wrong or even painful direction! Set all of the "Angle Adjust" sliders to "180".

  1. With the weapon prop gameobject selected in the Hierarchy view, press "F" in the Scene view to make the editor focus on the weapon.

  1. Click on the "Z" arm of the Scene Gizmo. Then click the middle of the Scene Gizmo to enable Isometric Mode.

  1. Adjust the Scene view to get a good look of the character from its waist up. Then go back to the current weapon's vp_3rdPersonWeaponAim Inspector and test each slider in turn to find the slider that rolls the hand (that is - rotates it in the way you would if you were to hold out your hand, palm facing the ground, then turned your palm up to see if it was raining).


This could be a different slider for different models and depends on various factors during rigging and export from various 3d art programs.


Restore the other sliders to "
180" then roll the hand until the gun's "top" faces upward properly in the Game view.

  1. Click on the "X" arm of the Scene Gizmo. Then use the remaining two sliders to make the gun face straight forward (pitch, yaw).

  1. If you look around in the Game view now, the character should face the gun more accurately at things. However aim could likely use some fine-calibration.

  1. Look down and fire a shot into the ground about half a meter in front of and to the right of the character. Then aim the crosshair precisely at the resulting bullet hole.

  1. If the gun doesn't point satisfyingly at the bullet hole, make small adjustments to the "Angle Adjust" sliders until it does.

TIP: Any time you want to toggle back and forth between the Inspector and the Game view without firing shots, press ESC to free the mouse cursor from the game, and the right mouse button on top of the Game view to reenable mouselook without firing.

IMPORTANT: When you're happy with the aim, do not stop the game before copying the component values, or your tweaks will be lost! Read on ...

  1. To save your values, click the little cog wheel  of the vp_3rdPersonWeaponAim component -> "Copy Component". Now you can stop the game.

  1. After stopping the game, again click the cog wheel  -> "Paste Component Values".

  1. Done! Your weapon should now point accurately at targets in 3rd person (unless they get really, really close). Don't forget to set the Scene Gizmo back to Perspective Mode if so desired. See the following tutorial for info on how to adjust recoil.

Adjusting 3rd person Recoil

First make sure that your weapon prop has a vp_3rdPersonWeaponAim component (see this tutorial for information on how to set one up).

  1. Make sure your 3rd person weapon is hooked to a 1st person one, and that the 1st person weapon has visible recoil.

  1. Start the game and hit the "Toggle3rdPerson" key (default: "V").

  1. In the Hierarchy view, select the target weapon prop object (under the character's right hand "Weapon" group).

  1. In the Inspector, unfold the vp_3rdPersonWeaponAim component and locate the "Recoil Factor" sliders.

  1. Fire the weapon and observe how the weapon moves. The recoil applied around the various axes in 1st person may not be suitable for 3rd person and the weapon may recoil too much or too little.

  1. Adjust the sliders until things look right in 3rd person. To enhance recoil, increase the value, to invert it use a negative value. To disable recoil around a vector entirely, set the corresponding slider to "0".

Head & Arm materials setup

When you first add a plain human body model to an FPS player, usually you can see too many arms in 1st person plus the inside of the player model's head (teeth, tongue, eyeballs).

To fix this, the head must be made invisible at all times in 1st person, and the arms must be made invisible when wielding any 1st person weapons that come with their own arms.

This result can be temporarily achieved using the "cheat" described here, however that's a quick fix resulting in several unintended glitches, making it useful only for prototyping and quick tests.

UFPS can solve the issue "properly" by applying a little black magic to make the arm and head meshes invisible although still casting shadows in the 3d world. For this to work your player model needs to have one material assignment for the head, one for the arms and one for the rest of the body.

TIP: The following tutorial can be done by hand, but there is also a great add-on asset for UFPS by CodeBison, called FPS Mesh Tool. This excellent piece of software will take care of all the below steps for you and a whole lot more (no need for a standalone art program).


For any new player model you want to use for 1st person:

  1. Open the body model in a 3d art program and split it up so that the head has its own material slot, the arms sharing one material slot, and the rest of the body has one material slot.

  1. In Unity, on the SkinnedMeshRenderer of the body model, assign any material you like to the "Body".

  1. Assign two separate materials to the "Arm" and "Head" slots. Make sure the names of these materials have "head" and "arm" in them, respectively (case insensitive).

  1. Verify that the player body's vp_FPBodyAnimator component has the default UFPS "InvisibleShadowCaster" material assigned to it.

Now, in 1st person mode, the inside of your head should be invisible (like in the real world ;) and there should be no more cases of "too many arms". Toggling to 3rd person view should make the head and arms come instantly back into visibilty, everything in a seamless manner.

The character can of course have many more materials too if you like. What's important is that the arms share a material with the letters "arm" in the name inside Unity, and that the head has a material of its own with the word "head" in its name.

Anatomy of a player body

The following image provides an overview of the functional aspects of a body hierarchy (script components in white):

1) The main Body object, childed to the root player gameobject

Components

On a local, 1st or 3rd (!) person player the animator is always of type vp_FPBodyAnimator, but on a computer controlled AI / bot or multiplayer remote player, it would instead be a vp_BodyAnimator (without the "FP"). This is because any script prefixed "vp_FP" will assume a camera (rendering to a monitor) and input (e.g. mouse and keyboard)

2) The Skinned Mesh Renderer

This is a regular Unity SkinnedMeshRenderer component with three materials for preventing clipping and multiple arms in 1st person. These are manipulated by the bodyanimator script. Basically, when you are in 1st person the "Head" and "Arm" materials are replaced by an invisible, shadow casting shader. If you go unarmed in 1st person, the "Mecanim arms" are again shown (optional). When you toggle to 3rd person these get replaced by a normal material. See this tutorial for info on how to set up body materials.

3) The "Lowest Spine Bone", assigned to slot in the bodyanimator (1)

Used in headlook logic. This could be a uniquely named and located gameobject in every model, but the bone directly above the hips / pelvis is usually what works best.

4) The "Head Bone" assigned to slot in the bodyanimator (1)

Used in headlook logic. This could be a uniquely named and located gameobject in every model, but the bone located as close as possible to the center of the body model's head is usually what works best.

All bones in the hierarchy in direct ascension between this gameobject and the "Head Bone" gameobject will be considered the character's spine (hence the bent, red line in the illustration) and will be automatically included in the headlook mechanism. In the above illustration the bones included will be "Spine", "Spine1", "Spine2", "Spine3", "Neck" and "Head".

The bones "LeftShoulder" and "RightShoulder" in this illustration are not directly rotated by headlook since they are not a parent of "Head". However, as children of "Spine3" they'll still be affected by headlook logic. The arms will turn roughly in the direction the player is aiming, and the animation and weapon aiming scripts will kick in to achieve the last part of a spot-on aim.

5) Right hand gameobject (parent of 3rd person weapons)

This is usually an empty gameobject (no components), but you will navigate to it many times because it is the parent of all the 3rd person weapons (6).

This could be a uniquely named and located gameobject in every model, but it's a very good idea for this object to have the letters "hand" (case insensitive) in its name because of an auto-initialization feature of the weapon aiming script.

6) The Weapon Group

The 3rd person weapon group is an empty gameobject (no components) that contains visual (as opposed to "functional") representations of the 1st person weapons that are childed to the main FPS camera. These are associated with a  vp_FPWeapon under its "Rendering" -> "3rd Person Weapon Model" slot.

7) 3rd Person Weapon Models

These are separate "prop" models depicting 1st person weapons for 3rd person views, AI and multiplayer remote players. Note that the 1st person weapon object still manages all the game logic and fx. In 3rd person, the 1st person weapon is invisible and fires any bullets from the world position of its corresponding 3rd person weapon prop. See this tutorial for info on how to set up 3rd person weapon props.

Mecanim Reference

The vp_BodyAnimator and vp_FPBodyAnimator scripts are tightly integrated with the UFPS player event system and designed for use with the provided "UFPSExampleAnimator" Mecanim controller. In the UFPS demo scenes, whenever a UFPS vp_Activity event starts or stops, a corresponding parameter gets activated in Mecanim, blending the animations into that state.

PLEASE NOTE: Working with these statemachines will require a decent understanding of Unity's animation system, Mecanim, which is outside the scope of this manual. To learn about Mecanim please see these links:

Upper and lower body split

The system assumes an upright player, logically divided into upper and lower body. The UFPSExampleAnimator has three layers: "Base", "Lower Body" and "Upper Body". The lower and upper body layers each have elaborate state machine setups designed for movement and gunplay, respectively. The base layer is currently kept empty and could be used for expanding the system.

Most of the example animation states submit to this upper / lower body split. For example: legs will frequently be running while the upper body is reloading and one doesn't really get affected by what the other is up to.

To open up the Animator window for your player, select its "Body" gameobject (the one with the Animator and the vp_FPBodyAnimator components on it. Then go to the Unity top / main menu and click "Window" -> "Animator" (not to be confused with "Animation").

Full body animations

There are examples of full body animations in the demos, e.g. the "OutOfControl" and "Climb" states. These cases are solved simply by playing the same animation in the upper and lower body layers at the same time. Theoretically, you could also play a full body animation either by having it in the base layer and disabling the two other layers or by disabling the UFPS body animator script altogether and assigning another one, maybe even assigning a different animator controller. Everything is possible. One thing is for sure, though: animation is tricky territory and you will want to know Mecanim and Mecanim scripting well.

State machines

Lower Body

Upper Body (main)

Upper Body -> Firearm

Upper Body -> Unarmed

There is a special case in this state machine when it comes to running vs. crouching, where control is allowed to pass from Crouch to Run even if 'IsRunning' is false. This is necessary or control will always pass via walk due to the activation order of the events.

Upper Body -> Melee Weapon

Note that melee combat has very limited support in the first version of the body system and the melee state machine and animation are placeholders.

Parameters of the UFPSExampleAnimator

Floating point values

Parameter

UFPS source

Mecanim destination

Forward

Player.Velocity

Lower Body -> forward / backward leg animation

Pitch

Player.Rotation

Upper Body -> FireArm -> up / down aim animation

Strafe

Player.InputMoveVector & Crouch, vp_BodyAnimator yaw logic

Lower Body -> sideways (strafing) leg animation

Turn

vp_BodyAnimator yaw logic

Lower Body -> idle turn animation

VerticalMove

Player.MotorThrottle.y (jump input)

Lower Body -> jump animation

Booleans

Parameter

UFPS source

Mecanim destination

IsAttacking

Player.Attack.active

Upper Body -> Firearm & Melee -> attack / zoom animation

IsClimbing

Player.Climb.active

All statemachines -> climb trigger

IsCrouching

Player.Crouch.active

Lower Body -> crouch animation, Upper Body -> CrouchAttackZoom

IsGrounded

vp_FPController.Grounded (vp_FPBodyAnimator)

Lower Body -> most states, Upper Body -> Unarmed -> most states

UpdateGrounded (vp_BodyAnimator)

IsMoving

Player.MotorThrottle (vp_FPBodyAnimator)

Lower Body -> most states, Upper Body -> Unarmed -> most states, Upper Body -> Melee -> most states

Player.Velocity (vp_BodyAnimator)

IsOutOfControl

Player.OutOfControl.active

All statemachines -> out of control trigger

IsReloading

Player.Reload.active

Upper Body -> Firearm -> reload trigger

IsRunning

Player.Run + Player.MotorThrottle (vp_FPBodyAnimator)

Player.Run + Player.Velocity (vp_BodyAnimator)

Lower Body -> most states, Upper Body -> Unarmed -> most states, Upper Body -> Melee -> most states

IsSettingWeapon

Player.SetWeapon.active

Upper Body (main) -> setweapon state

IsZooming

Player.Zoom.active

Upper Body -> Firearm -> attack / zoom animation

Triggers

Parameter

UFPS source

Mecanim destination

StartClimb

Player.Climb (OnStart_)

All statemachines -> climb state

StartOutOfControl

Player.OutOfControl (OnStart_)

All statemachines -> outofcontrol state

StartReload

Player.Reload (OnStart_)

Upper Body -> Firearm -> reload state

Integers (enum indices)

Parameter

UFPS source

Mecanim destination

WeaponGripIndex

Player.CurrentWeaponGrip (vp_Weapon)

Upper Body (main) setweapon state

WeaponTypeIndex

Player.CurrentWeaponType (vp_Weapon)

Upper Body (main) setweapon state

Supported animation content

DISCLAIMER: Regarding the included animation library: UFPS contains a folder with animations which are provided for prototyping, demonstration and testing purposes only.

Most animations come from various free examples by UnityTechnologies. Others have been slapped together in 5 minutes for quick tests. Some of the animations may drop lots of warnings, some may not work as expected, and some may not suite every character rig.

In truth we can not provide support for these animation clips in any meaningful way. They are to be seen as demo content only. For your actual game we strongly recommend obtaining a more comprehensive and higher quality animation library.

Body scripting

The default UFPS player setup is certainly moddable, but the better you know Mecanim, C# scripting and UFPS specific scripting concepts (in that order), the better your chances will be of implementing your own game design. This chapter collects some lore and good-to-know bits for scripters about the UFPS player body systems.

Terminology

Local player

The single in-world player object that is controlled by the human operating this physical machine. A local player can exist in two render modes: 1st and 3rd person.

Remote player

Any in-world player object that is not controlled by the human who operates the local computer. Can be controlled by a human or AI, but never performs rendering (has no camera) and never has a physical input device connected to the local machine.

  1. In multiplayer: the local representation of a player that is actually playing from another machine
  2. This term is sometimes (sloppily) used in reference to an AI controlled player / bot, especially if that player has been created using the 'Generate Remote Player' wizard.

Look Point

On a local player
On a remote player

Look Direction

In Local 1st person
In Local 3rd person / Remote players

IsFirstPerson

This property is used all over the place and reports the 1st/3rd person status of the player. The property will return:

... and may be accessed using the player event handler 'IsFirstPerson' value event, e.g:

        if(Player.IsFirstPerson.Get())

Recommended components and scripts to study

Please investigate the editor inspector and code comments of the following scripts for more insight:

Where to find the 3rd person code?

This code is part of the first person camera class due to the intimate relations of different aspects of camera logic in the two modes. The mode is disabled by default and should incur zero overhead in a first-person-only setup. To enable the mode, set 'Position3rdPersonOffset' in the camera's 'Position Springs' foldout to a non-Vector3.zero value and fire the new 'CameraToggle3rdPerson' message with the player event handler (or just press "V" in DemoScene3).

Why is the bullet always fired from middle of camera in 1st person?

Because of the weapon camera. Sometimes the barrel will appear to be in front of a wall when in fact it's sticking through it. Bullets must be fired from the camera in order to end up where the barrel points on the wall.

What exactly does the ragdoll handler do?

The ragdoll handler scans the player hierarchy on startup to store any (pre-existing) ragdoll joints, rigidbodies and colliders for later quick-toggling on / off. The initial state of all the objects are also stored for respawning purposes. The ragdoll handler then starts listening for the player's death event and, upon death, disables the body animator and activates any ragdoll components. Finally the character controller's world velocity is carried over into the ragdoll rigidbodies. When the player respawns, its ragdoll joints and colliders are returned to their default states and disabled. Control is then given back to the player's body animator.

In case of funky headlook

If headlook "gets weird" somehow, if the head tilts to the shoulder or looks in the wrong direction, this can be a somewhat complicated scripting issue. From a spine-initialization perspective, there is a big difference between starting the game with a character that already exists in the scene, versus one that is instantiated by script at runtime. If you start experiencing this:

NOTE: vp_BodyAnimator's "HeadPoint" rotation can not be set every frame - it should be manipulated as rarely as possible even if it must always point in the correct direction.

Using the "Generate Remote Player" wizard for AI and multiplayer

It is important to note that the main local player prefab has many scripts with the prefix "vp_FP" and these scripts should never be used on remote or AI players because they assume access to camera and keyboard / mouse input. Luckily, the most important player scripts also exist in a base version simply prefixed "vp_" and these scripts can normally be used on non-local player objects.

The 'Generate Remote Player' wizard strips a 1st person player of all scripts that assume camera & input, and in many cases converts the "vp_FP" scripts to their "vp_" equivalents. The resulting gameobject could then be spawned in multiplayer to represent a player of the same type as the local player, or you could design AI enemies using the 1st person player workflow (beginning by making sure they handle and animate well) and convert them into AI foes using the wizard as the second stage in the process.

The wizard is run by selecting the root object of a local player prefab (for example, the "Hero" in DemoScene3) and going to the top main menu: "UFPS -> Wizards -> Generate Remote Player". This will create a stripped down, "remoteplayer-legal" version of the player. This object won't do anything in and of itself. It is just intended as a starting point for adding AI or multiplayer features (in our own upcoming multiplayer adaptation we actually use this raw wizard output exactly as-is and apply any additional components needed for multiplayer at runtime). Of course, you may not want to use all the components retained on the player by the wizard. In this case you can mod the wizard or remove them manually.

For AI, the UFPS event system can be manipulated quite easily. Just add a vp_PlayerEventHandler (without the "FP") script to the player and add custom scripts to interact with it. Note that the wizard doesn't produce a controller or collider - nor movement support - which means you will have to add those and rotate and move the object using your own logic. Other than that it has all the weapons and shooters needed already, and you just need to toggle the 3rd person weapon objects on and off in their hands, make them look at something and send the events that fire the weapons.

It should be noted that all of the local player scripts do incur quite an overhead and are not suitable for spawning legions of furious AI. In the case of a village full of NPCs that just need to stand still and turn towards the player and activate dialogs etc. it would probably be better to make new scripts (or new versions of the included ones) that don't require a player event handler.

Body Troubleshooting

Body related issues

The player model doesn't stick to the center of the charactercontroller, but rotates around it in a huge arc /

The player model walks away from the charactercontroller

My ragdoll keeps falling over backwards, but I want it to fall over forwards

My remote player or 3rd person player starts swiveling around its hip like crazy

My character is invisible and won't move. Upon closer inspection its body floats far away in the air and wobbles about strangely

Verify that the bodyanimator component of the character does not have headlook nodes set to nodes in another model.

The camera shakes violently when I move

The camera collision feature casts a ray to intersect with walls. There may be an active collider on the body (ragdoll or player damage collider) that does not have the correct layer.

The local player starts stopping, stuttering or jumping erratically high up in the air for no apparent reason, especially when moving

Headlook is weird somehow: head tilts to / rests on shoulder or looks in wrong direction

See this note in the body scripting chapter.

Weapon related issues

I have assigned a 3rd person weapon to the hand bone of my character and positioned it correctly but it won't appear in-game

Make sure that you have also assigned the model to the '3rdPersonWeaponModel' slot of the corresponding vp_FPWeapon component (the weapon childed directly under the camera)

When I aim or shoot in 3rd person, the hand of my character points in a wrong / unnatural direction

You must calibrate the aim of the weapon. To do so, please see the weapon aim tutorial.

When I calibrate weapon aim, the next time I start the game it's broken

Always make sure that all 3rd person weapons are activated on the character before starting the game or calibrating weapon aim (basically the character should have a big bundle of guns in its right hand). Otherwise, the "virgin" relative rotations of the weapons inside the hand will not be initialized correctly on startup and weapon aim will break. This is not ideal workflow and something we are planning to fix down the line.

I am building a new player based on an old player prefab. The old weapons are hovering in front of me even though i have removed them from the FPcamera

You must delete the old 3rd person weapons childed to the right hand bone of the player body too.

Firearm shells fly off at an extremely high forward or sideways velocity when I'm moving and shooting

Make sure that your player's main object (with the collider) is set to layer: localplayer, otherwise shells may collide with the player when it is moving.

Presets

The Preset system allows you to take a snapshot of all the settings in a component and save it to a text file. Presets can be loaded via script at runtime and used to quickly manipulate all the parameters of a component as needed by the gameplay. You'll find the "Preset" foldout at the bottom of most components in the inspector.

Load & Save

These buttons will open a file dialog allowing you to load or save presets to disk. Saving a preset will result in all the current parameter values of the component being dumped to disk. Loading a preset will alter the current component values with data from the preset. Preset text files are meant to be assigned to player states under the State foldout (see the States chapter).

IMPORTANT: Assets (such as 3d objects and sounds) can not be loaded or saved via text presets. This is because the Unity Editor AssetDatabase is no longer accessible once the game has been built. Inspector slots for sound, 3d meshes and textures always have to be set manually in the Inspector or via scripting methods.

Save Tweaks

This feature will save partial presets, that is: create or update a preset with only the values modified since the last time you pressed Play or changed the states at runtime. The purpose of this will usually be to create presets for use with the State Manager.

For example: the player may pick up a powerup that should only affect running speed. To create a preset for this, you could select the FPController component in the Inspector, start the game, alter the "MotorAcceleration" parameter and press "Save Tweaks". This would result in a FPController preset with only the acceleration parameter in it. See the States chapter to learn how to assign such a partial preset to a player state and bind it to a button.

States

Any fast-paced FPS will have the player switching between different modifier keys quickly and repeatedly (e.g. crouching, zooming, running). This calls for swapping lots of presets at runtime, usually requiring lots of scripting, for all the special cases and key combos. The UFPS State Manager simplifies this by moving much of the work into the Editor and solvin