Search Unity

Limiting the Rotation around Z-Axis.

Discussion in 'Scripting' started by enveryurek, Dec 30, 2019.

  1. enveryurek

    enveryurek

    Joined:
    Dec 19, 2019
    Posts:
    2
    I'm developing a Flight Simulator app. I am newbie in this job. I want to limit rotation around z-axis between 80 and -80 degrees. My script are below. How can I do that? Please help me. Thanks :)

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class kontrol : MonoBehaviour
    6. {
    7.     protected DynamicJoystick joystick;
    8.     public float speed = 100f;
    9.     float maxspeed = 300f;
    10.     float minspeed = 35f;
    11.     float rotspeedvertical = 40f;
    12.     float rotspeedhorizontal = 60f;
    13.     private bool rotating = false;
    14.      
    15.     void Start()
    16.     {
    17.         joystick = FindObjectOfType<DynamicJoystick>();
    18.  
    19.     }
    20.  
    21.     void FixedUpdate()
    22.     {
    23.         Vector3 camPos = transform.position - transform.forward * 8f + Vector3.up * 4f;
    24.         float bias = 0.8f;
    25.         Camera.main.transform.position = Camera.main.transform.position*bias + (1.0f-bias)*camPos;
    26.         Camera.main.transform.LookAt(transform.position+transform.forward*20f);
    27.  
    28.         transform.position += transform.forward * Time.deltaTime * speed;
    29.         speed -= transform.forward.y*Time.deltaTime*40f;
    30.         if (speed <minspeed)
    31.         {
    32.             speed = minspeed;
    33.         }
    34.        
    35.         if (speed > maxspeed)
    36.         {
    37.             speed = maxspeed;
    38.         }                        
    39.        
    40.        
    41.        [B] transform.Rotate(new Vector3((-joystick.Vertical*rotspeedvertical*Time.deltaTime), 0f,((-joystick.Horizontal*rotspeedhorizontal*Time.deltaTime)))); [/B]
    42.        
    43.     }
    44. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    What you will need to do is to create a persistent Vector3 representing the Euler angles of your rotation, and add the joystick input values to that. You will be able to easily cap the rotation values to anything there, which you can't do after it's been converted to a Quaternion. Every frame, use transform.rotation = yourEulerVariable; rather than transform.Rotate() to assign the rotation.