Paul McGlinchey
Paul McGlinchey

Reputation: 23

In Unity I'm trying to "fake float" my character controller, gravity turned off but something is still pulling downwards (Y direction)

Should mention I'm trying to make it work with C# but open to JS options.

So my idea is for my CharacterController to hit my water object which has a OnTriggerEnter function attached, causing 3 things to happen:

  1. My animation changes from idle/walking/running to TreadWater (works fine, just needs tweaking)
  2. Turn gravity off of the rigidbody (the char controller)
  3. Set the Y position of the rigidbody to the surface of the water so that it appears to be floating

CharacterController controller; Animator Animator; bool WaterImpact; GameObject WaterProDaytime; public Rigidbody Model; void Start() { Animator = GetComponent<Animator>(); Model = GetComponent<Rigidbody> (); Model.velocity = Vector3.zero; Model.angularVelocity = Vector3.zero; } void OnTriggerEnter (Collider col) { if (col.gameObject.name == "WaterProDaytime") { WaterImpact = true; //PlayerController.gravity = 0; } Debug.Log (col.gameObject.name); Debug.Log (WaterImpact); } void Update() { if (WaterImpact) { transform.position = new Vector3 (transform.position.x, -1.4f, transform.position.z); //Debug.Log (PlayerController.gravity); //Debug.Log ("WaterHit"); } }

Tried using a void Update()function and setting the position every update too and while that does it work, there appears to be an opposing force causing the character to "jitter" very rapidly.

Ideally I would just like all opposing forces to be turned off and the transform.position.y to be locked to the surface of the water.

Been looking at this for 2 days, would appreciate any help whatsoever but please go easy on me, very new to Unity and C#

Cheers

Edited script.

Upvotes: 0

Views: 1297

Answers (1)

Kardux
Kardux

Reputation: 2157

May it simply be caused by the this.GetComponent<Rigidbody> ().useGravity = true; line?
I guess from your explanation point 2. that it should be this.GetComponent<Rigidbody> ().useGravity = false; instead.

Also please note you can simply call GetComponent<Rigidbody>() instead of this.GetComponent<Rigidbody>().

Last point: when dealing with physics, try to always stick with the provided engine tools. transform.position = new Vector3 (transform.position.x, -1.5f, transform.position.z); line can mess up with physics as you change the position of the object arbitrarily. Calling GetComponent<Rigidbody>().MovePosition(new Vector3 (transform.position.x, -1.5f, transform.position.z)); is much safer.

Hope this helps,

Upvotes: 1

Related Questions