Search Unity

limiting rigidbody rotation with c#

Discussion in 'Scripting' started by Mulgy, Sep 13, 2017.

  1. Mulgy

    Mulgy

    Joined:
    Jun 21, 2017
    Posts:
    2
    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<Rigidbody>();
    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));
    }

    }
     
  2. Rob21894

    Rob21894

    Joined:
    Nov 21, 2013
    Posts:
    309
    Try changing rb.rotation to

    Code (CSharp):
    1. transform.localEulerAngles = new Vector3(rotationx, rotationy, -rotationZ);
     
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    One way of doing this, is close to what you have.
    Add to your variable with the input, and clamp it.

    Instead of ..
    Code (csharp):
    1. rotationZ =  rotationSpeed * Input.GetAxis ("Mouse Y");
    2. // do instead
    3. rotationZ += rotationSpeed * Input.GetAxis ("Mouse Y");
    then, when you assign the rotation, you want to just use those values:
    Code (csharp):
    1. rb.rotation = Quaternion.Euler(0,rotationY, rotationZ);
    Please look at this page for posting on the forums: https://forum.unity.com/threads/using-code-tags-properly.143875/
    It will show you how to add code so it appears nicely (and for others to read more easily) :)
     
    Mulgy likes this.
  4. Mulgy

    Mulgy

    Joined:
    Jun 21, 2017
    Posts:
    2
    This worked perfectly, thank you very much.

    Peace.
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You're welcome :)