Reputation: 69
Please keep in mind I am a complete beginner.
I am trying to make a space shooter game. I have a 2D sprite facing upwards and this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed = 5.0f;
private void Start()
{
transform.position = Vector3.zero;
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 eulerAngles = transform.rotation.eulerAngles;
//Debug.Log("transform.rotation angles x: " + eulerAngles.x + " y: " + eulerAngles.y + " z: " + eulerAngles.z);
transform.Translate(Vector3.right * speed * horizontalInput * Time.deltaTime, Space.World);
transform.Translate(Vector3.up * speed * verticalInput * Time.deltaTime, Space.World);
if (horizontalInput > 0)
{
transform.Rotate(new Vector3(0, 0, -1) * horizontalInput * Time.deltaTime * 300);
}
else if (horizontalInput < 0)
{
transform.Rotate(new Vector3(0, 0, -1) * horizontalInput * Time.deltaTime * 300);
}
if (eulerAngles.z > 45)
{
//transform.rotation = Quaternion.AngleAxis(45, Vector3.forward);
Debug.Log("45");
if (eulerAngles.z < -45)
{
//transform.rotation = Quaternion.AngleAxis(-45, Vector3.forward);
Debug.Log("-45");
}
For now, I want the log to say "45" when the value in Transform.rotation.z reaches 45, and "-45" when it reaches -45. My real intention (commented out in the code) is to then tell the sprite to stop rotation at 45 or -45 degrees.
When I press the left arrow until it rotates to 45, it works. But here's the problem... When I press right arrow, and the value of Transform.rotation.z becomes negative, and the log immediately says "45" as if any negative number is somehow superior to 45.
I notice that when I rotate the sprite in Unity, the values of Transform.rotation.z go on a sort of loop, until 180 then become negative until 0 and vice versa.
Could someone tell me what I'm missing? Am I overlooking other simpler, more effective ways to achieve what I'm looking for?
Thanks in advance for your help, I really appreciate it. I'm new and still struggling to grasp with many concepts.
Upvotes: 1
Views: 2906
Reputation: 69
I just solved it! I only had to set a range in the condition between 45 and 180, and for the other direction between 315 and 180.
if (eulerAngles.z > 45 && eulerAngles.z < 180)
{
transform.rotation = Quaternion.AngleAxis(-315, new Vector3(0, 0, 45));
Debug.Log("45");
}
if (eulerAngles.z < 315 && eulerAngles.z > 180)
{
transform.rotation = Quaternion.AngleAxis(-315, new Vector3(0, 0, -45));
Debug.Log("-45");
}
This makes it work perfectly. When the sprite (spaceship) is going sideways, it rotates to that side but stops rotating at 45 degrees.
Upvotes: 3