How can I rotate a sprite in Unity 4.3?

I would like to rotate the sprite onto the stage by pressing the left or right arrow keys (think of a spaceship in asteroids).

I placed the sprite on the scene and created a script, but I'm not really sure where to go from there.

My current script is as follows:

using UnityEngine; using System.Collections; public class RotateLeftRight : MonoBehaviour { public float speed = 1.0f; public string axisName = "Horizontal"; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.LeftArrow)) { // left transform.Rotate(-1.0f, 0.0f, 0.0f); // does nothing, just a bad guess } if(Input.GetKeyDown(KeyCode.RightArrow)) { // right transform.Rotate(1.0f, 0.0f, 0.0f); // does nothing, just a bad guess } } } 

I just coded above, not knowing what would happen (and, surprisingly, nothing happens at all).

Any advice on how to rotate the sprite and control the speed of rotation is welcome.

+6
source share
2 answers

I can’t try it with Unity right now, but I assume that it either rotates only 1º, so you cannot notice it or rotate 360º, and therefore it really remains the same.

Try to solve your problem:

  • Instead of transform.Rotate try transform.Translate(20f, 20f, 20f) just to make sure it recognizes the input;
  • Use a different value instead of 1.0f , for example 0.1f and 30.0f (I think 30.0f will be 30º, but I'm not sure);
  • Try changing the rotation on other y and z axes instead of x ;
  • Use the alternative definition of Rotate(Vector3 axis, float angle) .

Hope this helps!

+5
source

@Sailing Judo, here is the best answer if you want to turn it like a wheel. Try to look at your code again and instead of putting / changing the X axis as a parameter, instead put your value on the Z axis. Changing the x or y axis in a circular rotation ended like a coin flipping. Watch and try again.

  if(Input.GetKey(KeyCode.LeftArrow)) { // Clockwise transform.Rotate(0, 0, -3.0f); // --> Instead of "transform.Rotate(-1.0f, 0.0f, 0.0f);" } if(Input.GetKey(KeyCode.RightArrow)) { // Counter-clockwise transform.Rotate(0, 0, 3.0f); // --> Instead of transform.Rotate(1.0f, 0.0f, 0.0f); } 
+3
source

Source: https://habr.com/ru/post/958340/


All Articles