This is more the theory of how to move your character, The actual controller you need to move is in question to me.
I have a similar issue that I’m trying to resolve in this post.
http://forum.unity3d.com/threads/170324-Mecanim-Precise-animation-control.
As I say in that post I was trying to modify rootPosition, with no effect.
I’ve found that if I modify transform.position, It will move my character, and so far hasn’t broken my animation. Please note that I don’t know if this is the correct controller to do this on since I’m new to mecanim.
Regardless of what controller you apply the motion to, the code is the same. I’ll use transform.position in the example
First make sure you have the required variables at the top of your class:
public float swimSpeed = 1.0f; // This is your maximum swimming speed
public float swimHeadingSpeed = 1.0f; // How fast can we turn left /right in water?
public float swimPitchSpeed = 1.0f; // How fast can we tilt up / down in water?
public float f = 0; // Forward speed set by movement axis (left stick +vertical axis)
public float v = 0; // Vertical Look / swim axis (right stick vertical axis)
public float h= 0; // Horizontal Look / swim axis (right stick horizontal axis)
Then add the swimState to your Update() loop
//SwimState
if(currentBaseState.nameHash == swimState)
{
transform.Rotate(Vector3.up, h * swimHeadingSpeed * Time.deltaTime, Space.World); // Spin object around world Y axis
transform.Rotate(Vector3.right, v * swimPitchSpeed * Time.deltaTime, Space.Self); // Spin object around local x axis
// This rotation setup will make sure you get predictable results and leaves the objects z rotation at 0
transform.position += transform.forward * f * speed * Time.deltaTime; // Move object along its forward axis a specified amount
}
Note also that this will not stop you from rotating your character upside down in the water, or handle keeping him upright when on the surface of the water. You’ll have to implement some checks to clamp his rotation in these events.
If your character will only ever swim on the surface of the water you can simply remove the 2nd Rotate() line and get rid of the swimPitchSpeed variable.
There may be a more concise way to write this that someone could point out, but I like splitting the axis’ into y and x so you can see whats happening.
After the rotation is set its as simple as adding the forward vector to the position to get him to move forward, you multiply the forward vector by the speed in this case the maxSpeed * the amount given by the input axis by deltaTime so that all numbers are in meters / sec.
As for your rigidbody… It may need to be set to isKinematic for this to work.