- Home /
Gravity UnderWater
Hi, I wanted to know how to make gravity under 15.2f in the y-axis, I'll paste the code and the rigidbody.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnderWater : MonoBehaviour {
public bool UW;
Rigidbody rb;
// Use this for initialization
void Start () {
rb = this.gameObject.GetComponent<Rigidbody> ();
}
void Update ()
{
if (this.transform.position.y <= 15f) {
new WaitForSeconds (0.2f);
if (transform.position.y < 15f) {
rb.AddForce(Vector3.up * -Physics.gravity.y, ForceMode.VelocityChange);
UW = true;
}
else if (transform.position.y == 15f) {
rb.AddForce(0,0,0);
UW = false;
}
}
}
}
First, your WaitForSeconds won't work and is impossible to use and not recommended in update. Second, adding 0 force is equal to not making the call at all, you can remove it.
Third, the else if could just be an else, because everything not below 15 is above, right? Inessence, UW = transform.position.y < 15f;
but I want to make the player float and that still doesn't work
If you want to be realistic about it, there are buoyancy scripts out there that you can attach to objects to make them behave correctly in water.
Thanks, Habitablabla I searched and I found a buoyancy script.
Answer by · Jun 21, 2017 at 04:53 PM
Gravity is just a global force applied to all rigidbodies that have "useGravity" enabled. Form what i see you are just trying to enable and disable the gravity when reaching y = 15.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnderWater : MonoBehaviour {
public bool UW;
Rigidbody rb;
// Use this for initialization
void Start () {
rb = this.gameObject.GetComponent<Rigidbody> ();
}
void Update ()
{
if (this.transform.position.y <= 15f) {
new WaitForSeconds (0.2f);
if (transform.position.y < 15f) {
rb.useGravity = true;
UW = true;
}
else if (transform.position.y >= 15f) {
rb.useGravity = false;
UW = false;
}
}
}
}
I also changed the if statement. You can not guarantee that the Y will be exactly 15 at any point.