Unity - Move object using the accelerometer on device

0

I have a problem since I am new to unity, what I want is that when the object reaches a certain position on the x axis it stops, for example when it reaches 2 or -2 it stops at that point. In the code that I propose when it reaches that position, it stops and no longer moves in the opposite direction. Greetings.

// Update is called once per frame
void Update () {
    float temp = Input.acceleration.x;
    Mover (temp);
}

public void Mover(float temp){

    float posicion = 2.0f;

    if (transform.position.x > -posicion && transform.position.x < posicion) {
        transform.Translate (temp * velocidadPosicion * Time.deltaTime, 0, 0, Space.World);
    }
}
    
asked by marco de vicelis 11.01.2018 в 19:28
source

1 answer

0

I hope you still need help.

The solution would be to do something called Clamp to the position in X of the transform, Clamp is a method of Mathf that what it does is to return a number between a certain range.

Your code should look something like this.

// Update is called once per frame
void Update () {
    float temp = Input.acceleration.x;
    Mover (temp);
}

public void Mover(float temp){

    float posicion = 2.0f;
    transform.Translate (temp * velocidadPosicion * Time.deltaTime, 0, 0, Space.World);

    //Clamp
    transform.position = new Vector3(Math.Clamp(transform.position.x, -2, 2), transform.position.y, transform.position.z);
}

If you do not need it, you can still mark it as verified to help others;)

    
answered by 22.01.2018 / 00:19
source