Rotation script with accelerometer (android)

Hi i hope someone can help me out because that really would be great. I have a little piece of code i cannot get fixed. I want an object in the scene get tilted when the phone gets tilted.

This is what i have so far but i can’t get anything working on the phone. I don’t know how to write the code this way that it tilts on both axes…

This is what i have so far:

if (Input.acceleration.x > 200) {
			transform.Rotate((Input.GetAxis("Vertical")*Time.deltaTime*80),0,0); 
		}

		if (Input.acceleration.y > 200){
			transform.Rotate((0.8-divesalto)*(Input.GetAxis("Vertical")*Time.deltaTime*80),0,0); 
		}

2 Answers

2

You check the Input.acceleration.x variable for the phone, but Input.GetAxis(“Horizontal”) and Input.GetAxis(“Vertical”) returns the mouse or controller axis I think.

Try using the Input.acceleration.x and .y for your rotation speed.

I havent got access to the phone API, but here is my attempt of a solution:

Make a TiltAround.cs (C#) file and copy/paste this:

using UnityEngine;
using System.Collections;

public class TiltAround : MonoBehaviour 
{
	private Quaternion localRotation; // 
	public float speed = 1.0f; // ajustable speed from Inspector in Unity editor

	// Use this for initialization
	void Start () 
	{
		// copy the rotation of the object itself into a buffer
		localRotation = transform.rotation;
	}
	
	
    void Update() // runs 60 fps or so
    {
        // find speed based on delta
        float curSpeed = Time.deltaTime * speed;

		// first update the current rotation angles with input from acceleration axis
		localRotation.y += Input.acceleration.x * curSpeed;
		localRotation.x += Input.acceleration.y * curSpeed;
		
		// then rotate this object accordingly to the new angle
		transform.rotation = localRotation;
	
	}
	
}

and let me know if that works or not.

Now you can use your accelerometer to Do rotation. All devices can be compatible for VR Or to rotate the camera with accelerometer, And works on all axes. Thanks to this asset: