limiting rigidbody rotation with c#

Hi All,

I am quite new to Unity, and i am building an asteroids style game with a spaceship with a turret on top to shoot the incoming asteroids. I am using the mouse to rotate the top of the turret and i want to limit the range of the rotation on the Z axis so it cant point at the ship it mounted on or rotate up past 90 degrees and be upside down but n mater what i try i have been unable to get it to work. Any help would be much appreciated. Below is the script i am using.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Controller : MonoBehaviour {

private Rigidbody rb;
public float rotationSpeed = 1f;
private float rotationZ = 0f;
private float rotationY = 0f;

void Start ()
{

rb = GetComponent();
rb.rotation = Quaternion.Euler (new Vector3(0f, 90f, 0f)); //set rotation to start position

}

void Update ()
{

rotationZ = rotationSpeed * Input.GetAxis (“Mouse Y”);
rotationZ = Mathf.Clamp (rotationZ, -10f, 90f);
rotationY = rotationSpeed * Input.GetAxis (“Mouse X”);

rb.rotation = Quaternion.Euler (rb.rotation.eulerAngles + new Vector3 (0f, rotationY, rotationZ));
}

}

Try changing rb.rotation to

transform.localEulerAngles = new Vector3(rotationx, rotationy, -rotationZ);

One way of doing this, is close to what you have.
Add to your variable with the input, and clamp it.

Instead of …

rotationZ =  rotationSpeed * Input.GetAxis ("Mouse Y");
// do instead
rotationZ += rotationSpeed * Input.GetAxis ("Mouse Y");

then, when you assign the rotation, you want to just use those values:

rb.rotation = Quaternion.Euler(0,rotationY, rotationZ);

Please look at this page for posting on the forums: Using code tags properly
It will show you how to add code so it appears nicely (and for others to read more easily) :slight_smile:

1 Like

This worked perfectly, thank you very much.

Peace.

You’re welcome :slight_smile: