Mark Martin
Mark Martin

Reputation: 57

Unity - How to make the accelerometer of object move more smoothly in smartphone?

I want to make my character to move smoothly when I tilt my phone. How I can make it to move smoothly and the velocity and the speed increases as the slope of the phone?

void AccelerometerMove(){

float x = Input.acceleration.x;
Debug.Log("X = " + x);

if (x < -0.1f)
{
    MoveLeft();
}
else if (x > 0.1f)
{
    MoveRight();
}
else
{
    SetVelocityZero();
}
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft()
{
rb.velocity = new Vector2(-speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
rb.velocity = new Vector2(speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}

Upvotes: 0

Views: 542

Answers (1)

Hellium
Hellium

Reputation: 7356

You can directly use the input of the accelerometer to set the speed of your object :

void AccelerometerMove()
{
    float x = Input.acceleration.x;
    Debug.Log("X = " + x);

    if (x < -0.1f)
    {
        MoveLeft(x);
    }
    else if (x > 0.1f)
    {
        MoveRight(x);
    }
    else
    {
        SetVelocityZero();
    }
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 0);
}

And / or use the Mathf.Lerp function to compute the speed :

void AccelerometerMove()
{
    float x = Input.acceleration.x;
    Debug.Log("X = " + x);

    if (x < -0.1f)
    {
        MoveLeft();
    }
    else if (x > 0.1f)
    {
        MoveRight();
    }
    else
    {
        SetVelocityZero();
    }
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft()
{
    rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, -speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
    rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 0);
}

Upvotes: 2

Related Questions