rigidbody.AddForce doesn´t work in c#
Hi,
I´m trying to make a FPSCharacter swimm in water at a specific height level. I´m using rigidbody.AddForce to add a force that pushes the rigidbody up. However, AddForce isn´t working. I saw annother Question and it seems like i have to unchek "is kinematik" for it to work. But if i do that, i can run through the terrain and i get a few other Bugs too. If you know how to use AddForce with a kinematik rigid body, please let me know. And also, if you know another way to let a rigidbody swim on water, please let me know to.
Answer by GenericToast · Sep 13, 2017 at 02:17 PM
You should use ForceMode.Impulse for instant forces like jumping and ForceMode.Force for constant forces that are applied every FixedUpdate()
eg.
rigidbody.AddForce(10.0f, ForceMode.Impulse);
That woesn´t the problem. I can swimm now, but one problem was that if I´m walking under water and change the direction with the mouse, like I do over the water, I´m walking in the same direction as before. I have to stop and start walking again to change the direction, any idea why that is happening?
I'm not too sure about that. $$anonymous$$aybe you can show me your script so i get a better picture of what's happening
Ok here is the Script. It isn´t the best, but i think it should work.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Swimmer : $$anonymous$$onoBehaviour { public Vector3 $$anonymous$$Position; public Vector3 maxPosition; public GameObject controllingObject; public GameObject mainLight; public Color defaulColor; public Color underwaterColor; public float underWaterGravity; // Use this for initialization void Start () {
}
// Update is called once per frame
void Update () {
float x = controllingObject.gameObject.transform.position.x;
float y = controllingObject.gameObject.transform.position.y;
float z = controllingObject.gameObject.transform.position.z;
if (x <= maxPosition.x && y <= maxPosition.y && z <= maxPosition.z && x >= $$anonymous$$Position.x && y >= $$anonymous$$Position.y && z >= $$anonymous$$Position.z) {
controllingObject.GetComponent<Rigidbody> ().AddForce (new Vector3 (0f,10f,0f), Force$$anonymous$$ode.Impulse);
print ("under");
//controllingObject.GetComponent<Rigidbody>().
Light mlight = mainLight.GetComponent<Light>();
mlight.color = underwaterColor;
} else {
//Physics.gravity = new Vector3 (0f, -9.81f, 0f);
//controllingObject.GetComponent<Rigidbody> ().AddForce (new Vector3 (0f,0f,0f), Force$$anonymous$$ode.Acceleration);
controllingObject.GetComponent<Rigidbody> ().velocity = new Vector3 (0f,0f,0f);
controllingObject.GetComponent<Rigidbody> ().angularVelocity = Vector3.zero;
Light mlight = mainLight.GetComponent<Light>();
mlight.color = defaulColor;
}
}
}