1. Unity Project for Mobile Device
เริ่มกันเลยครับ
1. ให้ทำการสร้าง C# Script (TouchController.cs)
2. จากนั้นให้ทำการเพิ่มใน Update()
// mobile carame zoom
private Vector2 touch1Position = Vector2.zero;
private Vector2 touch2Position = Vector2.zero;
private Vector2 lastTouch1 = Vector2.zero;
private Vector2 lastTouch2 = Vector2.zero;
private float currentDistance = 0.0f;
private float lastDistance = 0.0f;
private float zoomFactor = 0.0f;
private float zoomSpeed = 1.0f;
void Update()
{
// ตรวจสอบจำนวนนิ้วที่แตะหน้าจอ ถ้ามีมากกว่า 1 นิ้วให้ทำการตรวจสอบการ Zoom in / Zoom out
if (Input.touchCount >= 2)
{
// เก็บค่านิ้วที่ 1
if(Input.GetTouch(0).phase == TouchPhase.Moved)
{
touch1Position = Input.GetTouch(0).position;
lastTouch1 = touch1Position - Input.GetTouch(0).deltaPosition;
}
// เก็บค่านิ้วที่ 2
if(Input.GetTouch(1).phase == TouchPhase.Moved)
{
touch2Position = Input.GetTouch(1).position;
lastTouch2 = touch2Position - Input.GetTouch(1).deltaPosition;
}
// หาระยะห่างและทำการ Zoom
currentDistance = Vector2.Distance(touch1Position, touch2Position);
lastDistance = Vector2.Distance(lastTouch1, lastTouch2);
zoomFactor = Mathf.Clamp(lastDistance - currentDistance, -30.0f, 30.0f);
transform.Translate(-Vector3.forward * zoomFactor * zoomSpeed * Time.deltaTime);
}
}
4. ทำการ Build สำหรับ Mobile Device แล้วทำการทดสอบเลยครับ
เท่านี้ก็น่าจะนำไปใช้ประยุกต์ในเกมได้แล้วครับ
ปล. มีอะไรแนะนำได้ครับ