Hello , I am having a hard time already for two days to stabilize angular motion of hovering object. I built a hovering capsule that moves at some fistance from the ground , and controlled with arrows keys .The problem is that when it collides with some object like building it’s rotation (x ,y , z) gets shifted and after this when I am moving it (applying AddForce()to it’s Z it moves according to it’s local space rotation.
How can I cause my rigidbody to return back to it’s initial rotation that has to be (0,some rotation,0)?
Here is my code:
using UnityEngine;
using System.Collections;
public class HoverBody : MonoBehaviour {
public float idealDistance=23;
public float damping=4;
public float baseForce=23;
public float reactionForce=12;
public float moveVelocity=200;
private Vector3 mousePos;
public float speedV=14;
private RaycastHit hit;
private Vector3 xz = Vector3.right + Vector3.forward;
void Start () {
rigidbody.centerOfMass=new Vector3(0,rigidbody.position.y-20,0);
rigidbody.sleepVelocity=2;
}
// Update is called once per frame
void FixedUpdate () {
Vector3 hoverForce=Vector3.zero;
hoverForce=Reaction(rigidbody.position, hit.point,rigidbody.velocity);
Debug.Log(hoverForce+"hover force");
}else{
Debug.Log("NOHIT");
}
/////////////
Vector3 whiskerForce=Vector3.zero;
if (Physics.Raycast(rigidbody.position, transform.right, out hit)) {
whiskerForce += Reaction(rigidbody.position, hit.point, rigidbody.velocity);
}
if (Physics.Raycast(rigidbody.position, -transform.right, out hit)) {
whiskerForce +=Reaction(rigidbody.position, hit.point, rigidbody.velocity);
}
rigidbody.AddForce(hoverForce,ForceMode.Acceleration);
Vector3 moveDirection = new Vector3(0, 0,Input.GetAxis("Vertical"));
Vector3 rotateDirection=new Vector3(0,Input.GetAxis("Horizontal"),0);
Quaternion deltaRotation = Quaternion.Euler(rotateDirection *speedV);
Debug.Log(moveDirection);
rigidbody.MoveRotation(rigidbody.rotation*deltaRotation);
rigidbody.AddRelativeForce(moveDirection*moveVelocity,ForceMode.Impulse);
rigidbody.MoveRotation(rotateDirection*q2);
rigidbody.inertiaTensorRotation = Quaternion.identity;
}
public void OnCollisionStay(Collision colInfo){
Vector3 groundVec = Vector3.Scale(Vector3.zero-rigidbody.position, xz);
transform.localRotation = Quaternion.LookRotation(groundVec);
Debug.Log("collison detected"+ colInfo.collider);
}
public Vector3 Reaction(Vector3 a, Vector3 b, Vector3 relVelocity) {
Vector3 springVec = b - a;
float dist = springVec.magnitude;
float tension = dist - idealDistance;
Vector3 normSpring = springVec / dist;
float damp = Vector3.Dot(relVelocity, normSpring) * damping;
return normSpring * (baseForce + tension * reactionForce - damp);
}
}