1
\$\begingroup\$

There is a 3D character in my application developed using Unity3D. Now I want to rotate this 3D character when the user press the rotation button. I tried several ways, but didn't work. How can I rotate a character when the player presses the rotation button?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Two basic steps here, detecting when a button is pressed, and rotating the object. Both are pretty simple.

Create a new script, or insert the following into your existing script that is attached to the object you want to manipulate:

float angle = 10;
Vector3 axis = new Vector3(0,1,0);
float anglePerUpdate = 2f;

void OnGUI () {

    //Create a new Button at location 0,0, with a size of 100, 20. 
    //The text in the button will read "Rotate Once"
    if(GUI.Button(new Rect(0,0,100,20), "Rotate Once")) {
        //if button is pressed, perform the following
        //rotate the object to a specified angle rotating around the axis specified
        this.transform.rotation = Quaternion.AngleAxis(angle, axis);
    }

    //create another button below "Rotate Once".
    //this is a  RepeatButton that will continue to perform its action every update
    if(GUI.RepeatButton(new Rect(0,25,100,20), "Rotate Continuous")) {
        //if button is pressed, perform the following
        //rotate the object at a specified speed, around the specified axis
        //take the existing rotation and add a little bit to it
        this.transform.rotation = 
            this.transform.rotation * Quaternion.AngleAxis(anglePerUpdate, axis);
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .