Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Accelerometer in unity

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 1.20k
    Comment on it

    Accelerometer in unity means to take input from a device by tilting it along x-axis and y-axis and after taking the input transform the object accordingly. To achieve this we need to write few lines of code within update method. So that the input of accelerometer can be retrieve every frame.

    In the below example we will try to rotate a platform about its axis towards forward and backward and sideways via accelerometer:


    Private float TiltAngle; 
    Private float Speed; 
    Private Quaternion target; 
    Void Update()
    {
     float tiltAroundX = Input.acceleration.y * TiltAngle;
    float tiltAroundZ = Input.acceleration.x * TiltAngle;
    target = Quaternion.Euler(tiltAroundX, 0, tiltAroundZ);
    transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * Speed);
    }

    In the above lines of code we will give a maximum TiltAngle which defines extent to which platform can be tilted and speed that defines how fastly changes going to be reflected . We will also give a variable target of type Quaternion that holds tilted value of device in form of angles x,y,z at a particular frame.

    We will take two float variables tiltAroundX and tiltAroundZ within update method where each of the variable holding the direction tilted which is obtained by Input.acceleration because we can tilit the device either in x or y axis. So we will give them the axis Input.acceleration.x and Input.acceleration.y and we will store these values into local variables so that they will be assign to target Quaternion .

    Now We will rotate the platform using transform.rotation and pass the parameters (transform.rotation ie., current rotation axis , target rotation axis and Time.deltaTime * Speed ie., to make changes per frame ) within Slerp method of quaternion so that the rotation looks smoother.


    Thanks,
    For any Queries leaves the Comment

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: