关于unity3d模型的重力感应,在这里我们使用unity引擎提供的Input.acceleration重力感应;
Transform trans;
//小球在屏幕的最大范围
float cross_x=0;
float cross_y=0;
float cross_z=0;
float m_x=0;
float m_y=0;
Vector3 screenpioint;
trans = ( Transform ) Instantiate ( m_round, m_round.position, Quaternion.identity );
m_x= trans.GetComponent ( ).mesh.bounds.size.x * trans.localScale.x;
m_y = trans.GetComponent ( ).mesh.bounds.size.y * trans.localScale.y;
cross_x = Screen.width - m_x;
cross_y = Screen.width - m_y;
void OnGUI ( )
{
//整体显示x,y,z的重力分量
GUI.Label ( new Rect ( 0, 0, 400, 200 ), "position is" + Input.acceleration + "--x" + trans.GetComponent ( ).mesh.bounds.size.x * trans.localScale.x + "--" + trans.GetComponent ( ).mesh.bounds.size.y * trans.localScale.y );
GUI.Label ( new Rect ( 2, 30, 400, 200 ), "screenpioint.x is" + screenpioint.x + "screenpioint.y is" + screenpioint.y );
}
// 根据重力分量修改小球的位置
screenpioint=Camera.main.WorldToScreenPoint ( trans.position );
screenpioint.x += Input.acceleration.x * 100 * Time.deltaTime;
screenpioint.y -= Input.acceleration.y * 100 * Time.deltaTime;
if (screenpioint.x <= m_x*2)
screenpioint.x = m_x*2;
if (screenpioint.y <=m_y*2)
screenpioint.y = m_y*2;
if (screenpioint.x >= cross_x)
screenpioint.x = cross_x;
if (screenpioint.y >= cross_y)
screenpioint.y = cross_y;
trans.position = Camera.main.ScreenToWorldPoint ( screenpioint );
例如:
public Transform m_round;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
快来试试吧,哇咔咔!