- Home /
How to have a gameobject only rotate 180 degrees
I have a cannon that can rotate 360 degrees, but I need it to only spin 180 degrees. How do I do that? Here is my code:
public int rotationOffset = -90;
// Update is called once per frame
void Update()
{
var mouse = Input.mousePosition;
var screenPoint = Camera.main.WorldToScreenPoint(transform.localPosition);
var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle + rotationOffset);
}
Answer by callen · Jan 24, 2018 at 08:25 PM
Try adding a Clamp right after the "var angle = ..." line.
angle = Mathf.Clamp(angle, -90, 90);
You can change the clamp parameters to restrict it as needed, but I believe -90 to 90 will work for what you described. Good luck!
@callen O$$anonymous$$, but there are 2 problems with your code, first I need my cannon to be able to rotate for the left, to be able to go up and to the right, yours goes top to bottom and after playing with your code I could not get it to work right so how do you do that? and I found if you rotate the cannon all the way to the left it will glitch to the other side of the clamp, can you stop that from happening?
Answer by bhavinbhai2707 · Jan 24, 2018 at 08:26 PM
Probably check this thread link
@bhavinbhai2707 Sorry, that doesn't work, that includes a lot of other including turn speed and more which I don't have and can't have, if you would be willing to modify that code to work with what I've got that would be great.
@Gamegenorator all those speed code in the question is not needed at all!! The answer given by platformSix is the solution for your question as well!! That code has been tested by me as well and works perfectly!!
@bhavinbhai But I'm also working in 2D so is there a way to modify the code for that?
Answer by E_101 · Jan 24, 2018 at 08:30 PM
Hello, looks like you could add in an "if" statement of sorts to check the rotation and use it to halt the movement. However it looks like the answers before mine seem to be more accurate to your question. You can utilize the (cannon.transform.rotation.eulerAngles.z <= 90)
code to achieve this same effect. You will probably need to add this either before or after the angle variable. Hopefully this is enough information as I realize this is a very short answer. Good luck!