About

Search This Blog

Monday, August 24, 2015

Use Accelerometer for Roll-a-ball Movement in unity 3d






  1. using UnityEngine;
  2. using System.Collections;
  3. public class PlayerController : MonoBehaviour
  4. {
  5. // Using same speed reference in both, desktop and other devices
  6. public float speed =1000;
  7. void Main ()
  8. {
  9. // Preventing mobile devices going in to sleep mode
  10. //(actual problem if only accelerometer input is used)
  11. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  12. }
  13. void Update()
  14. {
  15. if (SystemInfo.deviceType == DeviceType.Desktop)
  16. {
  17. // Exit condition for Desktop devices
  18. if (Input.GetKey("escape"))
  19. Application.Quit();
  20. }
  21. else
  22. {
  23. // Exit condition for mobile devices
  24. if (Input.GetKeyDown(KeyCode.Escape))
  25. Application.Quit();
  26. }
  27. }
  28. void FixedUpdate ()
  29. {
  30. if (SystemInfo.deviceType == DeviceType.Desktop)
  31. {
  32. // Player movement in desktop devices
  33. // Definition of force vector X and Y components
  34. float moveHorizontal = Input.GetAxis("Horizontal");
  35. float moveVertical = Input.GetAxis("Vertical");
  36. // Building of force vector
  37. Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical);
  38. // Adding force to rigidbody
  39. rigidbody.AddForce(movement * speed * Time.deltaTime);
  40. }
  41. else
  42. {
  43. // Player movement in mobile devices
  44. // Building of force vector
  45. Vector3 movement = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
  46. // Adding force to rigidbody
  47. rigidbody.AddForce(movement * speed * Time.deltaTime);
  48. }
  49. }
  50. }

  51. Read more

1 comment: