pumpkinChan
pumpkinChan

Reputation: 13

Unity - Sprite Rotation + Get Angle

Im trying to get a sprite rotation by key input (arrow down or up). The point is lifting the arrow (sprite) to choose the angle. Its like a system of a golf game, actually.

So far i tried:

void Update () {

    if (Input.GetKey(KeyCode.UpArrow)){
        transform.Rotate (Vector3.forward * -2);    }
if (Input.GetKey(KeyCode.DownArrow)){
    transform.Rotate (Vector3.forward * +2);    }

}

I will need the angle, since it will be related to a "shot" part i will be doing next. My point is setting the right angle with the keys up and down.

I can move the "arrow" sprite with my code, but i cannot set the max angle (90), minimum (0) and get the angle to use in the shot ^^

Upvotes: 1

Views: 2515

Answers (1)

Michael
Michael

Reputation: 126

Hard question to answer without just simply giving you the code. This code works by assuming your character's forward vector is actually it's right vector (common in 2d sprite games) in order to shoot in the other direction, rotate your objects y axis 180.

float minRotation = 0f;
float maxRotation = 90f;
float rotationSpeed = 40f; //degrees per second

//get current rotation, seeing as you're making a sprite game
// i'm assuming camera facing forward along positive z axis
Vector3 currentEuler = transform.rotation.eulerAngles;
float rotation = currentEuler.z;

//increment rotation via inputs
if (Input.GetKey(KeyCode.UpArrow)){
    rotation += rotationSpeed * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.DownArrow)){
    rotation -= rotationSpeed * Time.deltaTime;
}

//clamp rotation to your min/max
rotation = Mathf.Clamp(rotation, minRotation, maxRotation );

//set rotation back onto transform
transform.rotation = Quaternion.Euler( new Vector3(currentEuler.x, currentEuler.y, rotation));

If you were making a golf game, you'd set the ball's velocity to be transform.right * shotPower

Upvotes: 1

Related Questions