I would like to rotate a sprite on the scene by pressing the left or right arrows keys (think of the spaceship in Asteroids).
I have placed the sprite in question on the scene and created a script, but am not really certain of where to go from there.
My current script looks like this:
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 the above without any knowledge of what would happen (and, hardly surprising, nothing appears to happen at all).
Any advice on how to rotate the sprite and control the speed of the rotation would be greatly appreciated.
To rotate a Transform, use Transform. Rotate, which uses Euler Angles. If you want to match values you see in the Inspector, use the Quaternion. eulerAngles property on the returned Quaternion.
Rotation in Unity typically works by specifying an amount of rotation in degrees around the X, Y or Z axis of an object. In the Inspector, you'll see an object's rotation as a Vector 3 value: In the same way that a game object's position in the world can be set using its Transform component…
I'm not able to try it with Unity right now, but my guess is that it is either rotating just 1º, so you are not able to notice it, or rotating 360º, and so it really stays the same.
Try to break down your problem:
transform.Rotate
try transform.Translate(20f, 20f, 20f)
just to make sure it is recognizing the input;1.0f
, such as 0.1f
and 30.0f
(I think 30.0f would be 30º, but I'm not sure);y
and z
instead of x
;Rotate(Vector3 axis, float angle)
.Hope it helps!
@Sailing Judo, here's the best answer if you want to rotate it like a wheel. Try observe again to your code and instead of putting/changing the X-axis as parameter, put your value at the Z-axis instead. Changing x or y-axis in a circular rotation ended up like flipping coins. Observe 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With