How to rotate an object around its center in Unity

Unity and me

Hi to all. Today I add a new technology which one I have been working the last year. It’s Unity, a game engine that can make it quite easier to develop a common game, but at the same time Unity offers you a lot of powerful tools to enable you make more complex projects. Yooka-Laylee by Platonic Games is the most recent exaple of a big, famous and mainstream game done using this engine.

Actually I’m using the engine to create augmented reality applications for the company where I’m working at, ANSWARETECH. And while using it I’ve been getting stressed with many problems that I’ll be commenting in different posts.

Rotating the object

Ok, I’ll not extend more your wait. I was trying a way to rotate a 3D Obj that I’ve loaded dinamically from the Web using Simple .OBJ asset to a Vuforia Trackable Object in order to be able to display it in augmented reality over a marker.

After getting it I decided that it would be good if we could add some functionality to the GameObject so I started to add transformation buttons: scale+, scale-, rotateX, rotateY (sorry, not rotateZ).

But I found some problems in the results of the rotate functions. So  after trying some alternatives and playing with Transform.Rotate, Transform.RotateAround, Transform.rotation (Quaternions), I had the idea of using an empty GameObject as parent of my OBJ and position it on its center, this way I could rotate parent easily and avoid anchor problems of my not 0,0,0 located 3d model.

So I finally did it with the following code:

using UnityEngine;
using System.Collections;

// ...

public static class Load3D {

// ...

    public void loadModel() {
    // ... In my 3D loading function

        model.transform.parent = marker.transform; //model is my OBJ model. Marker is the Vuforia thing

        model.transform.rotation = new Quaternion(0,0,0,0); //Resets rotation after adding it to parent

        Vector3 objCenter = model.GetComponent<Renderer>().bounds.center;

        GameObject container = new GameObject(); //new blank parent for my model.

        container.transform.parent = marker.transform;

        container.transform.rotation = new Quaternion(0,0,0,0);

        container.transform.Position = objCenter;

        model.transform.parent = container.transform;
}

    public void RotateMyModel() {
        // ... In my rotation functionality
        model.transform.parent.Rotate(Vector.up * 90);
        //or
        model.transform.parent.Rotate(Vector.right * 90);
        //or
        model.transform.parent.Rotate(Vector.forward * 90);
    }
}

 

Well, and that’s all 🙂

I hope it helps someone and avoid some headaches.

Have a nice coding day!