2017-01-02 38 views
1
public static void MoveObject(Transform transform, Vector2 deltaPosition, Camera camera = null) 
{ 
    if (transform != null) 
    { 
     if (deltaPosition.x != 0.0f || deltaPosition.y != 0.0f) 
     { 
      var rectTransform = transform as RectTransform; 

      // If this is RectTransform then modify the anchoredPosition 
      if (rectTransform != null) 
      { 
       rectTransform.anchoredPosition += deltaPosition; 
      } 
      // If this is Transform then modify the position 
      else 
      { 
       transform.position = MoveObject(transform.position, deltaPosition, camera); 
      } 
     } 
    } 
} 

public static Vector3 MoveObject(Vector3 worldPosition, Vector2 deltaPosition, Camera camera = null) 
{ 
    if (camera == null) camera = Camera.main; 

    if (camera != null) 
    { 
     // Find current screen position of world position 
     var screenPosition = camera.WorldToScreenPoint(worldPosition); 

     // Modify screen position 
     screenPosition += (Vector3)deltaPosition; 

     // Write new world position 
     worldPosition = camera.ScreenToWorldPoint(screenPosition); 
    } 

    return worldPosition; 
} 

回答

0

不要使用==!=比較floats,因爲0.0003F0.0002F不同。改爲使用Mathf.Approximately()

假設y=0是你的地面水平:

if (!Mathf.Approximately(newPosition.y, 0.0F)) 
{ 
    return; //don't move the object. 
} 
0

也@Lincoln回答可能會奏效。但你應該使用一點點範圍而不是==!=而使用浮動。就像在你的榜樣使用這個

if (deltaPosition.x < 0.0f && deltaPosition.x > 0.01f) 

因爲有非常難得的機會,當彩車完全相等...

相關問題