DAY 26
0

## Day 26: 觸控、Camera Aspect Ratio

``````public class PlayerMovement : MonoBehaviour
{
//-舊程式碼-
public float movementSpeed;
public float minPosX;
public float maxPosX;
//-舊程式碼-

//記錄螢幕中間的X軸
private float midScreenPosX;

void Start()
{
//初始螢幕中間X軸
midScreenPosX = Screen.width / 2f;
}

void Update ()
{
float movement = 0f;

//-舊程式碼- (鍵盤控制移動)
movement = Input.GetAxis ("Horizontal") * movementSpeed * Time.deltaTime;
//-舊程式碼-

//觸控移動角色
if (Input.touchCount > 0) {  //玩家正在觸控裝置
Touch touch = Input.GetTouch (0); //取得玩家第一個觸控點

//檢查觸控點的位置在螢幕的左方還是右方，並計算出移動值
movement = (touch.position.x < midScreenPosX ? -1f : 1f) * movementSpeed * Time.deltaTime;
}

//-舊程式碼-
Vector3 newPos = new Vector3 (Mathf.Clamp(transform.position.x + movement, minPosX, maxPosX), transform.position.y, transform.position.z); 		transform.position = newPos;
//-舊程式碼-
}
}
``````

`Start()`函數，我以`Screen.width`取得玩家裝置的螢幕寬度，除以2(也就是中間線)，指定給`midScreenPosX`

``````public class ScaleCameraInAspectRatio : MonoBehaviour
{
//長寬比，預設為9:16
public float aspectRatio = 9f / 16f;

void Start()
{
Camera cam = GetComponent<Camera> ();

//裝置螢幕的長寬比
float screenRatio = (float)Screen.width / (float)Screen.height;

//裝置螢幕長寬比和目標長寬比的比值
float scale = screenRatio / aspectRatio;

//裝置螢幕長寬比大於目標長寬比(Main Camera高度應維持，寬度縮小)
if (scale > 1f) {
Rect pixRect = cam.pixelRect; //Main Camera的矩形

//設定寬度
pixRect.width = pixRect.height * aspectRatio;
pixRect.y = 0f;

//顯示寬度要在(過寬的)螢幕正中央，所以要除2
pixRect.x = ((float)Screen.width - pixRect.width) / 2f;

//設定新的Main Camera矩形
cam.pixelRect = pixRect;
}

//裝置螢幕長寬比小於目標長寬比(Main Camera寬度應維持，長度縮小)
else {
Rect pixRect = cam.pixelRect;

//設定高度
pixRect.height = pixRect.width / aspectRatio;
pixRect.x = 0f;

//顯示高度要在(過高的)螢幕正中央，所以要除2
pixRect.y = ((float)Screen.height - pixRect.height) / 2f;

//設定新的Main Camera矩形
cam.pixelRect = pixRect;
}
}
}
``````