2017-04-13 71 views
2

所以我现在有2个值x和y,我希望x减少/增加y,直到它变为0而没有超过。不过度增加/减少值

float x = 9; 
float y = 4; 

if (x != 0) { 

    if (x > 0) { 
     x -= y; 
    } 

    else if (x < 0) { 
     x += y; 
    } 
} 

如果这是运行X会由y在-2减去3次离开x的值在下一帧,将再次运行,并添加Y,它会再次走了过来。

+0

如果'x == 0'成立,会发生什么? – Codor

+0

@Codor认为它是一个轴沿着一个点我想从X到0的步骤Y – Blukzen

回答

0

您可以通过在减法或加法之后在0处引入限幅来更改实施。

if (x != 0) { 
    if (x > 0) { 
     x -= y; 
     x = Math.Max(x, 0.0f); 
    } 
    else if (x < 0) { 
     x += y; 
     x = Math.Min(x, 0.0f); 
    } 
} 
0

为此,您可以使用这样的事情:

if (x != 0) 
{ 
    x = x < 0 ? Math.Min(x + y, 0) : Math.Max(x - y, 0); 
} 
+0

谢谢,但看到,仍然有我试图避免的问题!我不希望它结束​​减或增加所以而不是-3我希望它降落在0而不是在 – Blukzen

+0

@Blukzen好吧,这是从我身边的误解,修复这个问题:) –

0

不知道如果我理解正确的,但如果你想X将递减/由y递增,直到它到达0足不出户在,这应该这样做:

for(; x>=0; x = x - y); 
x = x + y; 
0

此功能将给予你这个结果的意见,对错误的参数就会避免去无限和返回X:

//[9, 4] = 1 
//[-9, -4] = -1  
private static float Unnamed(float x, float y) 
     { 
      float tmp = x; 
      float result = x; 
      while (true) 
      { 
       tmp -= y; 
       if (y > 0) 
       { 
        if (tmp > 0 && tmp < x) 
         result = tmp; 
        else 
         break; 
       } 
       else 
       { 
        if (tmp < 0 && tmp > x) 
         result = tmp; 
        else 
         break; 
       } 
      } 
      return result; 
     } 
0

好了,所以基于@ Codor的答案,我得到这个

private float Approach(float value, float targetValue, float step) { 

     float result; 

     if (value < targetValue) { 
      result = Mathf.Min (value + step, targetValue); 
     } else { 
      result = Mathf.Max (value - step, targetValue); 
     } 

     return result; 
    } 

其工作正常和不正是我想要的,绝不会走过去的目标值。然后我遇到了一个已经内置的函数,它完全符合我想要的Mathf.MoveTowards(value, targetValue, step)