Paul
Paul

Reputation: 670

Object Rotated by accelerometer doesn't collide properly in unity

First of all, I want to make clear that this is NOT a duplicate of this Question: unity 3d rotate the gameobject according to accelerometer

So, i have managed to rotate an object in unity by using the accelerometer & compass. This works fine normally but, when another object collides with it, it clips through the object which results in the object moving randomly.

I realized that this was due to the fact that i was directly altering the transform of the object. I know that I am not supposed to directly modify the transform and that i should use the rigidBody instead but, I don't know how I can change it to where it doesn't directly alter the transform.

Here is how i currently rotate the object:

float norm=0f;
Rigidbody rb;
// Use this for initialization
void Start () {
    rb = GetComponent<Rigidbody> ();


}

// Update is called once per frame
void Update () {
    Input.compass.enabled = true;
    if (norm == 0) {
        norm = Input.compass.trueHeading;
    }
    float val=Input.compass.trueHeading-norm;


    transform.rotation=Quaternion.Euler( new Vector3 ( (Input.acceleration.y-1)*90,val ,0));
    transform.Rotate (Input.acceleration.x*90*transform.forward);

}

So how could I change this so that I don't directly alter the Transform?

Thanks in Advance!

Upvotes: 0

Views: 210

Answers (1)

Foggzie
Foggzie

Reputation: 9821

Checkout the Documentation for Rigidbody.MoveRotation. It will rotate your RigidBody towards the given rotation while "complying with the Rigidbody's interpolation setting."

As a note: When you're working directly with physics objects you should be using FixedUpdate(), not Update(). If you're unsure why, they cover the differences in the Unity Tutorials. TL;DR It runs in a simulated "fixed framerate frame."

Upvotes: 1

Related Questions