DAY 12
0
Mobile Development

## 建立魔術方塊模型

### Step 1 建立方塊單位

(將在Scene內組合好了的物件(GameObject) 拉到 Assets 文件夾便可以製作成Prefab)

## 撰寫旋轉程式

### 旋轉物件

``````public GameObject target;
``````

### 旋轉功能

`````` if (Input.touchCount ==2)
{
firstPressPos = new Vector2(Input.touchPosition.x, Input.touchPosition.y);
}
if (Input.touchCount == 2)
{
secondPressPos = new Vector2(Input.touchPosition.x, Input.touchPosition.y);

currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);

currentSwipe.Normalize();
}
``````

`````` if (LeftSwipe(currentSwipe))
{
target.transform.Rotate(0, 90, 0, Space.World);
}
``````
`````` bool LeftSwipe(Vector2 swipe)
{
return currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f;
}
``````

``````print(currentSwipe);
``````

`````` void Update()
{
Swipe();
}
``````

### 讓旋轉更自然

• 點擊拖曳時，魔術方塊也可以跟著轉動
• 在旋轉的過程中加入時間
``````    void Drag()
{
if (Input.touchCount ==2)
{
touchDelta = Input.touchPosition - previousTouchPosition;
touchDelta *= 0.1f;
transform.rotation = Quaternion.Euler(touchDelta.y, -touchDelta.x, 0) * transform.rotation;
}
else
{
if (transform.rotation != target.transform.rotation)
{
var step = speed * Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, target.transform.rotation, step);
}
}
previousTouchPosition = Input.touchPosition;
}
``````