简体   繁体   中英

Unity | Rotate the gameObject by specified angle (0~360 degree)

I'm struggling to rotate gameObject with joystick. The joystick send the json data included value of angle to gameObject. The gameOjbect should rotate itself when receive the Jsondata. However, i'm wondering how to rotate it by angle (0 to 360 degree) in unity because all i do know is using (Vector3) position below.

Quaternion.LookRotation
public static Quaternion LookRotation(Vector3 forward, 
                                      Vector3 upwards = Vector3.up);

In conclusion, all i want to know is rotating the gameObject by the angle.

Use RotateAround .

// Rotate around world y.
transform.RotateAround(transform.position, Vector3.up, angle);

// Rotate around local y.
transform.RotateAround(transform.position, transform.up, angle);

You may found other useful stuff in Transform documentation anyway.

transform.eulerAngles = new Vector3(90, 0, 0);

Rotates your gameobject to 90 degrees in x axis.

Or you can rotate smoothly with

Vector3 destination = new Vector3(90,0,0);
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, 
                                     destination, 
                                     Time.deltaTime);

Quick tip for whoever is reading this now. transform.RotateAround is outdated in Unity's latest version. Need to use transform.Rotate(Vector3 eulerAngles) instead.

Here is an example to instantiate projectiles rotated on 'randomAngleRotation' angles.

Projectile newProjectile = Instantiate<Projectile> (projectile,projectileSpawn [i].position, projectileSpawn [i].rotation) as Projectile;
newProjectile.transform.Rotate(new Vector3(Random.Range(randomAngleRotation, randomAngleRotation), Random.Range(randomAngleRotation, randomAngleRotation)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM