This is a Unity 5 tutorial about a swimming system for FPS controller. You can use it to swim above the water surface or diving underwater.

Before I started to implement the system I drew a sketch of a Unity character controller (Capsule) in various situations:

Sketch for Unity 5 swimming system

Skecth for Unity 5 swimming system

Then I was able to code the logic for rendering underwater and above and the input handling for swimming.

In this youtube video you can see the system in action and I explain how it is implemented:

I used a reflection utility to get access to the private fileds of the Unity FPS Person Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Assets.SwimmingSystem.Scripts
{
    internal class ReflectionUtil
    {
        private static FieldInfo GetFieldInfo(Type type, string fieldName)
        {
            FieldInfo fieldInfo;
            do
            {
                fieldInfo = type.GetField(fieldName,
                       BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                type = type.BaseType;
            }
            while (fieldInfo == null && type != null);
            return fieldInfo;
        }

        public static object GetFieldValue(object obj, string fieldName)
        {
            Type objType = obj.GetType();
            FieldInfo fieldInfo = GetFieldInfo(objType, fieldName);
            if (fieldInfo == null)
                return null;

            return fieldInfo.GetValue(obj);
        }

        public static void SetFieldValue(object obj, string fieldName, object val)
        {
            Type objType = obj.GetType();
            FieldInfo fieldInfo = GetFieldInfo(objType, fieldName);
            if (fieldInfo == null)
                throw new ArgumentOutOfRangeException("fieldName",
                  string.Format("No field {0} of {1}", fieldName, objType.FullName));
            fieldInfo.SetValue(obj, val);
        }
    }
}
(Visited 155 times, 3 visits today)