Rotate Object in Unity 3D

I can use the following code to rotate object using accelerometer.

transform.rotation = Quaternion.LookRotation(Input.acceleration.normalized, Vector3.up);

But i would like to rotate object like for example screen is rotating - 0, 90, 180 and 360 degrees. How can I do it using Unity 3D?

0

4 Answers

You can use transform.rotation like this:

transform.rotation = new Quaternion(rotx, roty, rotz, rotw);

OR

You can use transform.Rotate like this:

transform.Rotate(rotx, roty, rotz);

Documentation for Quaternion

Documentation for transform.rotation

Example for Rotating screen with accelerometer input:

float accelx, accely, accelz = 0;

void Update ()
{
    accelx = Input.acceleration.x;
    accely = Input.acceleration.y;
    accelz = Input.acceleration.z;
    transform.Rotate (accelx * Time.deltaTime, accely * Time.deltaTime, accelz * Time.deltaTime);
}

If you want to rotate the object to a specific angle use:

float degrees = 90;
Vector3 to = new Vector3(degrees, 0, 0);

transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);

This will rotate 90 degrees around the x axis.

9

In order to rotate your game object on its own

int _rotationSpeed = 15;

void Update () {

    // Rotation on y axis
    // be sure to capitalize Rotate or you'll get errors
    transform.Rotate(0, _rotationSpeed * Time.deltaTime, 0);
}

If you are looking to add this to a game object where you can drop the game object into the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TheNameOfYourScriptHere : MonoBehaviour
{
    public float speed = 100;
    
    public GameObject yourgameobject;
    
    void Update()
    {
          yourgameobject.transform.Rotate(0, speed * Time.deltaTime, 0);
    }
}

Please note this rotation is faster so you can see it better in action.

You can rotate your object via just adding below line in your .cs script.

transform.Rotate(Vector3.up,Here you can put horizonatl speed);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest