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 ![]()
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;
}
}