2016-09-29 50 views
0

我糊塗了,這是我的創造,並記錄浮動升C腳本:統一調試日誌全浮

using UnityEngine; 
using System.Collections; 

public class guicontrol : MonoBehaviour { 
    void CalculatePosition(string ObjectName) { 
     GameObject theobject = GameObject.Find (ObjectName); 
     int selectedwidth = 1366; 
     int selectedheight = 768; 
     int screenwidth = Screen.width; 
     int screenheight = Screen.height; 
     float coordinatey = theobject.transform.localPosition.y; 
     float coordinatex = theobject.transform.localPosition.x; 
     float coordinatez = theobject.transform.localPosition.z; 
     Debug.Log ("work at current stats : " + screenwidth + " " + screenheight); 
     if (screenwidth != selectedwidth || screenheight != selectedheight) { 

      float coordinateytomove = (screenheight/selectedheight) * coordinatey; 
      float coordinatextomove = (screenwidth/selectedwidth) * coordinatex; 
      Debug.Log (coordinateytomove + " " + coordinatextomove); 

     } 

    } 
} 

當我在計算器手動計算的話,的coordinatextomove結果是:

-2.99853587116

,但在調試日誌是:

-3 0

-3coordinateytomove不從目前的變化的座標,但爲什麼如果coordinatextomove改變,其調試記錄0代替-2.99853587116?如果有以前的帖子回答了這個問題,請原諒我,並給我鏈接的帖子:)。

+0

如果你想在你可能想要做的'camera.WorldToScreenPoint(theobject.transform.position)屏幕的面積來選擇對象;',讓你的'coordinatex',並從'coordinatey'。這會給你遊戲對象屏幕上的x和y座標。 –

回答

2

screenheight/selectedheight會給你整數除法,在得到結果後忽略.右邊的任何內容。你需要投兩中的一個作爲浮動你把

float coordinateytomove = ((float)screenheight/selectedheight) * coordinatey; 
float coordinatextomove = ((float)screenwidth/selectedwidth) * coordinatex; 

之前,你也可以只聲明變量float和以後不必做演員。

int selectedwidth = 1366; 
int selectedheight = 768; 
float screenwidth = Screen.width; 
float screenheight = Screen.height; 
+0

標記爲答案! :) – user6668201

+0

有關更多信息,請參閱http://stackoverflow.com/questions/10851273/why-integer-division-in-c-sharp-returns-an-integer-but-not-a-float。 –

+0

謝謝,只需等待8-9分鐘作答標記 – user6668201