倾斜控制类似于Temple run

时间:2013-07-03 09:58:54

标签: unity3d accelerometer tilt

我想像太阳穴一样创造倾斜效果。我在游戏中有一个角色控制器(玩家),它通过控制器向前移动。移动(transform.forward)之后我应用倾斜到它倾斜它左右。之前我倾向于通过使用transform.translate /tranform.position直接通过这样的加速度计读数修改玩家位置:

mytransform.translate(acceleration.x*Time.delaTime*5.0f);

但是有一个问题,当我摇动设备时,我的相机开始抖动,然后播放器也使用以下代码在正Z轴上创建倾斜

Vector3 dir = new Vector3(accel.x*8f, 0,0);
    if (dir.sqrMagnitude > 1) 
{
    dir.Normalize();

}
dir.x = Mathf.Round(dir.x * 10f) / 10f;

//mytemp is used for temp storage of player position added with the acceleration 
mytemp = mytransform.position+(mytransform.right*dir.x*Time.deltaTime*5.0f);

Vector3 diffVec=Vector3.zero;
///position of the element on which the player is colliding;
Vector3 col_pos=Collidingelement.transform.position;
Vector3 unitvec=new Vector3(1,0,0);
//removing x and z of the collider
diffVec= Vector3.Scale(col_pos,unitvec);
//nullify the y,z of the updated mytransform position so that the distance is only measured on X
Vector3 ppos = Vector3.Scale(mytemp,unitvec);
//calculate the distance between player & colliding element
 disti=Vector3.Distance( ppos,diffVec);
disti=Mathf.Clamp(disti,-1.5f,1.5f);
disti = Mathf.Round(disti * 10f) / 10f;
//update the player position and apply tilt to it if the distance is less than 1.5f
if(disti<=1.50f)
{
mytransform.position=mytemp;

}

现在这有一个问题,如果让我说我的加速度值为0.1,它继续更新我的温度,如果距离较小,我的玩家将开始向一侧倾斜虽然我把我的设备放在同一位置上加速度值始终为0.1

1 个答案:

答案 0 :(得分:0)

为什么不直接计算增量加速度。

bool isMoved = false;
Vector2 lastAccel = Vector2.Zero;
Vector2 margin = new Vector2(0.05f, 0.05f);  //not processing if its in margin.
Vector2 deltaAccel = currAccel - lastAccel ;

if(deltaAccel.x < margin.x)
{
   //don't process
   isMove = false;
}
else
{
   isMove = true;
   lastAccel = currAccel;
}

if(isMove)
{
//Process with deltaAccel here
}