I can't seem to find a way of limiting the rotation of my object on the X-axis through scripting

I have 2 cannons in my game but I can’t seem to figure a way of limiting their x rotation. I feel like this should be simple but it seems like it’s not.

PLEASE HELP!!!

In the Update method just set its rotation to not go past a certain angle? if (transform.rotation.x < 90) { //if smaller than 90 apply rotation orsomething }

3 Answers

3

its the applying rotation or something I cant get right.

if the raycast doesn't hit anything he will let the Hit variable to be null, and you need to make sure that you don't use Hit when is null. You can do this by checking if Hit == null before use or use the if where you made the Raycast: Raycast Hit; {null by default} if(Physics.Raycast(........out Hit)) { {Raycast hit something} { you can use Hit there because Raycast hit something and Hit is not null anymore} } else { {Raycast didn't hit anything } { you cannot use Hit here because Raycast didnt hit anything and Hit remained null } }

I am probably overlooking something, but did you try this?

{
int x=45, y, z;
if (x>15 && x<90){
transform.rotation= new Vector3(x, y, z);
}
else {
//throw exception
}
}

Look up Mathf.Clamp in the Scripting Reference.
So it could be cannon.transform.position.x = Mathf.Clamp (cannon.transform.position.x, yourValueOne, yourValueTwo); where Cannon is your Cannon and both yourValueOne and yourValueTwo are your limitations :wink: