For Rotation on Axis Z

3

I'm new to the C # code and I'm doing a basic Z-axis rotation in Unity 3d, but I'm having a problem to stop rotating. The initial code is this:

using UnityEngine;
using Sysstem.Collections;

public class voa : MonoBehaviour{

int vel = 150;

// Use this for initialization
void Start (){

}

// Update is called once per frame

void Update () {

if (Input.GetButton("right)){

    transform.Rotate(0,0,vel * Time.deltaTime);

    }

    if (INput.GetButton ("left)){

    transform.Rotate (0,0,-vel * Time.deltaTime);

    }

  }

}

What would be the sequence of this code, so that at the time the object is at 80 degrees (positive or negative), even by pressing the arrow button it does not pass that point.

    
asked by anonymous 30.10.2015 / 10:55

1 answer

6

Your code had some typos and did not work here directly. Well, having them fixed, one idea that can help you is you simply limit the rotation before running it. To do this, accumulate the rotation value for each frame in which this occurs and compare if the accumulated value exceeds (in both the positive and negative sense) its maximum rotation. The following code does this:

using UnityEngine;
using System.Collections;

public class voa : MonoBehaviour{

    int vel = 150;
    float acumulado = 0;
    public float limite_angular = 90;

    // Use this for initialization
    void Start (){

    }

    // Update is called once per frame

    void Update () {

        if(Input.GetButton ("Horizontal")) {

            float angulo = vel * Time.deltaTime * Input.GetAxisRaw("Horizontal");

            if( (acumulado + angulo) >= limite_angular || (acumulado + angulo) <= -limite_angular)
                angulo = 0;

            acumulado += angulo;
            transform.Rotate (0, 0, angulo);
        }

    }

}

Note that I'm just doing this accumulation on the Z axis (which is what you use in your original code). If you need to accumulate on all three axes, change the variable from float to Vector3 and accumulate on each of them. Also note that I'm using the "horizontal" variable instead of "right" and "left" (because this is the Unity standard - at least in the latest version). And finally, note that to have the signal (positive or negative) simply multiply by% w / o% (function that returns -1 or 1 to indicate the direction of movement on the horizontal axis).

Ah, I've set the variable GetAxisRaw to public, so you can change its value directly in the Inspector window.

    
01.11.2015 / 00:39