Unity 3D realistic accelerometer control

*爱你&永不变心* 提交于 2019-12-11 02:49:46

问题


How do we achieve a control similar to this game? https://play.google.com/store/apps/details?id=com.fridgecat.android.atiltlite&hl=en


回答1:


You can do this with builtin physics:

  1. create a level from some simple scaled cubes (don't forget the ground).

  1. add the ball - a sphere, then and add a RigidBody to it. Set a constraint on the rigidbody - check freeze position y (or it will be able to jump out of the level if you put the device upside down).

  2. add this script anywhere on the scene (for example to the camera):

    using UnityEngine;
    
    public class GravityFromAccelerometer : MonoBehaviour {
    
        // gravity constant
        public float g=9.8f;
    
        void Update() {
            // normalize axis
            Physics.gravity=new Vector3( 
                Input.acceleration.x,
                Input.acceleration.z,
                Input.acceleration.y
            )*g;
        }
    
    }
    

    or if you want the physics to just affect this one object, add this script to the object and turn off it's rigidbody's affected by gravity:

    using UnityEngine;
    
    [RequireComponent(typeof(Rigidbody))]
    public class ForceFromAccelerometer : MonoBehaviour {
    
        // gravity constant
        public float g=9.8f;
    
        void FixedUpdate() {
            // normalize axis
            var gravity = new Vector3 (
                Input.acceleration.x,
                Input.acceleration.z,
                Input.acceleration.y
            ) * g;
    
            GetComponent<Rigidbody>().AddForce (gravity, ForceMode.Acceleration);
        }
    
    }
    

And now you have working ball physics. To make the ball behave as you'd like, try to play with the rigidbody properties. For example, change the drag to something like 0.1.



来源:https://stackoverflow.com/questions/29332871/unity-3d-realistic-accelerometer-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!