Player Swimming Mechanics.

Hello, I’m trying to allow a player to swim within a collider.
Here is my code below. It works to some extent. the only issue (that I’ve found) is that the player can go under the terrain if the collider is lower then the terrain. Whats the best way to fix this? Thankyou :slight_smile:

By the way, I’m using the default FPSController.

public class swimming_mechanic : MonoBehaviour {

    public bool isSwimming;
    public GameObject player;
    public float swimSpeed;
    public float currentheight;

    void Update () {
        if (isSwimming == true)
        {
            player.transform.position = new Vector3(player.transform.position.x, currentheight, player.transform.position.z);
            if (Input.GetKey(KeyCode.Space))
            {
                currentheight = currentheight + swimSpeed;
            }
            if (Input.GetKey(KeyCode.LeftShift))
            {
                currentheight = currentheight - swimSpeed;
            }
        }
    }
}
public class water_collider : MonoBehaviour {

    public swimming_mechanic sm;
    public GameObject player;

    private void OnTriggerEnter(Collider other)
    {
        sm.currentheight = player.transform.position.y;
        player.GetComponent<Rigidbody>().useGravity = false;
        sm.isSwimming = true;
    }

    private void OnTriggerExit(Collider other)
    {
        sm.isSwimming = false;
        player.GetComponent<Rigidbody>().useGravity = true;
    }
}

Could check with raycast for terrain height in that first script.

Also using transform.position can break physics, try moving rigidbody instead

Thanks, but how would I use a raycast? or implement it?
Sorry, not too good with Unity.

aaaaaah its broken lmao

I’ve replaced

player.transform.position = new Vector3(player.transform.position.x, currentheight, player.transform.position.z);

With

player.GetComponent<Rigidbody>().MovePosition(new Vector3(player.transform.position.x, currentheight, player.transform.position.z));

And it’s now broken lmao. It won’t “swim” it just falls through the collider. acting like the script doesn’t even exist.

Have you tried changing Void Update () to Void FixedUpdate ()? See if that helps.

Yes, I gave that a shot. Didn’t make a difference.

Well. I’m going to put the swimming aside for now. If anyone has some free time, it would be appreciated if you consider making a collider swimming mechanic. Thanks :slight_smile: