[Solved - sort of] Can't find a way to lock cannon aiming between 2 angle values
So I have been browsing previous questions but haven't had any luck figuring out my specific problem. I have a cannon that I want the user to be able to vertically aim. I can get the cannon to respond to input but now I need to lock it within what I consider valid points.
The cannon is rotated on the x-axis. 0 is straight up and 90 would be pointing forward. So if I only want the player to be able to adjust the cannon between say 45 degrees and 90 degrees, the valid area would look like this:
Ok. So that behaves as expected (watching the inspector as it rotates confirms this.) However, when I try to query what angle the cannon body is at, I get odd results. I currently am trying to get it by euler angles but I have tried pretty much everything I have been able to find or can think of to check the rotation but I always get a weird result. Here are the results logged when I try and check rotation in the code: (also please ignore the spelling errors in rotation)
Here is the code snippet where I log its angle and do actual manipulation: (cannonBody is a gameObject refrence)
print("X roatation: " + cannonBody.transform.eulerAngles.x.ToString());
cannonBody.transform.Rotate(-Input.GetAxis ("Vertical") * 2,0.0f, 0.0f);
So, if I were to say check if the cannon is rotated less than 90 degrees I would get false results back. What is the best way of going about this?
Posting my findings as an answer.
Answer by austingraham · Apr 04, 2017 at 02:02 AM
So I was able to get the behavior I expected after watching this video and adapting the code to suit my configuration.
Here is what I ended up doing:
public float maxAimAngle;
public float minAimAngle;
private float currentRotation = 75.0f;
***
Update calls input handler which calls handleArrowInput()
***
private void handleArrowInput(){
if(Input.GetAxis ("Vertical")!=0){
currentRotation += -Input.GetAxis ("Vertical") * 2;
currentRotation = Mathf.Clamp(currentRotation, minAimAngle, maxAimAngle);
cannonBody.transform.eulerAngles = new Vector3(currentRotation,cannonBody.transform.eulerAngles.y, cannonBody.transform.eulerAngles.z);
}
}
The cannon is started rotated at 75 degrees on the x-axis. So, I just manipulated the variable, clamped it and then set the new rotation to the result.
If anyone does have an answer as to why when I was querying the eulerAngles it gave me odd results I'd love to here it. Also if you know of a better way of accomplishing this please feel free to let me know.
Your answer
Follow this Question
Related Questions
Problem with projectile rotation - 2D 0 Answers
How to rotate an object around a player when pushing a button..? 0 Answers
Creating a simple character controller (Script provided) 1 Answer
Angle between objects taking in consideration their rotations? 0 Answers
using RayCast to aim at different planes 0 Answers