2016-01-16 44 views
0

我有一个箱子的橱柜。当我在箱子上看,然后按下鼠标按钮,我想打开/关闭它翻译。我想移动框,直到它是X坐标将是1.0(并且起始点是1.345)。但它移动的时间比这点长。如何在需要时停止翻译?

enter image description here

我试图用FixedUpdate,但它并没有帮助..

public LayerMask mask; 

private bool shouldClose; 
private bool changeXCoordinate; 
private Transform objectToMove; 

void Update() 
{ 
    if (changeXCoordinate) 
     OpenCloseBox(); 
    else if(DoPlayerLookAtCupboardBox() && Input.GetMouseButtonDown(0)) 
     changeXCoordinate = true; 
} 

bool DoPlayerLookAtCupboardBox() 
{ 
    RaycastHit _hit; 
    Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0)); 
    bool isHit = Physics.Raycast(_ray, out _hit, 1.5f, mask.value); 

    if (isHit && !changeXCoordinate) 
    { 
     objectToMove = _hit.transform; 
     return true; 
    } 
    else 
     return false; 
} 

void OpenCloseBox() 
{ 
    if (shouldClose) 
    {   
     if(objectToMove.position.x != 1.345f) // It must stop at this point, but it don't 
     { 
      changeXCoordinate = false; 
      shouldClose = !shouldClose; 
     } 
     else 
      objectToMove.Translate(Vector3.right * Time.deltaTime); 
    } 
    else 
    { 
     if (objectToMove.position.x >= 0.1f) // The same problem here.. 
     { 
      changeXCoordinate = false; 
      shouldClose = !shouldClose; 
     } 
     else 
      objectToMove.Translate(Vector3.left * Time.deltaTime);    
    } 
} 

回答

1

在这种情况下,你应该使用动画,这样就可以在任何方面完全控制运动。

如果你真的想使用的代码,你可以使用它通过每帧一定级差量创建从位置A到位置B线性平移Vector3.MoveTowards:

transform.position = Vector3.MoveTowards(transform.position, targetPosition, step * Time.deltaTime); 

至于你的问题,你正在检查头寸是否是某个浮动。但是由于价值的不准确,在计算机上比较float是不准确的。

1.345很可能是1.345xxxxxx,与1.34500000不一样。所以它永远不会平等。

编辑:使用相等还会导致您正在检查值是否大于或等于的事实。但想一想:

start : 10 movement : 3 

if(current >= 0){ move(movement);} 

frame1 : 10 
frame2 : 7 
frame3 : 4 
frame4 : 1 
frame5 : -2 we stop here 

这就是为什么希望移动到确切的点时,你应该使用动画或MoveTowards。或者添加额外的:

if(current >= 0){ move(movement);} 
else { position = 0; } 
+0

1.345很可能是1.33599999,这是不一样的。所以它永远不会平等。也是迪马说'if(objectToMove.position.x> = 0.1f)//同样的问题在这里' –

+0

是的,我编辑考虑这个问题。动画对象时,我不会推荐使用这个原则。 – Everts

+0

我试图使用动画,但有一些问题。但现在它工作正常。无论如何感谢大家的帮助=) – dima

2

其更好地使用吐温引擎,像http://dotween.demigiant.com/

如果安装Dotween的,你可以简单地使用

transform.DOMove(new vector3(1 ,0 , 1) , duration); 

您还可以设置缓解补间。或使用未完成的功能;

transform.DOMove(new vector3(1 ,0 , 1) , duration).SetEase(Ease.OutCubic).OnCompelete(() => { shouldClose = true; }); 

但对于你的问题的答案是,位置是不准确的数字,所以你不应该使用这样的事情!=,则必须使用<或>。 解决你的问题,我会建议你做这样的事情;

if(x > 1.345f) 
{ 
    x = 1.345f 
} 

这将解决您的问题。