unity 觸屏程式碼(一)物體運動
// 縮放係數
private float distance = 1f;
// 左右滑動移動速度
private float xSpeed = 250.0f;
private float ySpeed = 120.0f;
// 縮放限制係數
private float MinScale = 1;
private float MaxScale = 5;
// 記錄上一次手機觸控位置判斷使用者是在做放大還是縮小手勢
private Vector2 oldPosition1 = new Vector2(0, 0);
private Vector2 oldPosition2 = new Vector2(0, 0);
private Vector2 firstPos = new Vector2(0, 0);
private Vector2 lastPos = new Vector2(0, 0);
// 旋轉增量位置
private float xx = 0.0f;
private float yy = 0.0f;
//初始化遊戲資訊設定
void Start()
{
}
void Update()
{
//// 判斷觸控數量為單點觸控,旋轉
if (Input.touchCount == 1)
{
if (Input.touches[0].phase == TouchPhase.Began)
{
firstPos = Input.touches[0].position; //記錄手指剛觸碰的位置
lastPos = Input.touches[0].position;
}
if (Input.touches[0].phase == TouchPhase.Moved) //手指在螢幕上移動,移動攝像機
{
lastPos = Input.touches[0].position;
xx = -(lastPos.x - firstPos.x) / 10;
yy = (lastPos.y - firstPos.y) / 10;
}
else
{
xx = 0;
yy = 0;
}
}
transform.Rotate(yy, xx, 0);
firstPos = lastPos;
//// 判斷觸控數量為多點點觸控
if (Input.touchCount > 1)
{
// 前兩隻手指觸控型別都為移動觸控
if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved)
{
// 計算出當前兩點觸控點的位置
var tempPosition1 = Input.GetTouch(0).position;
var tempPosition2 = Input.GetTouch(1).position;
// 函式返回真為放大,返回假為縮小
if (isEnlarge(oldPosition1, oldPosition2, tempPosition1, tempPosition2))
{
// 放大係數超過3以後不允許繼續放大
// 這裡的資料是根據我專案中的模型而調節的,大家可以自己任意修改
distance = transform.localScale.x;
if (distance > MinScale)
{
distance -= 0.1f;
transform.localScale = new Vector3(distance, distance, distance);
}
}
else
{
// 縮小系數返回18.5後不允許繼續縮小
// 這裡的資料是根據我專案中的模型而調節的,大家可以自己任意修改
distance = transform.localScale.x;
if (distance < MaxScale)
{
distance += 0.1f;
transform.localScale = new Vector3(distance, distance, distance);
}
}
// 備份上一次觸控點的位置,用於對比
oldPosition1 = tempPosition1;
oldPosition2 = tempPosition2;
}
}
}
// 函式返回真為放大,返回假為縮小
bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2)
{
// 函式傳入上一次觸控兩點的位置與本次觸控兩點的位置計算出使用者的手勢
float leng1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));
float leng2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));
if (leng1 > leng2)
{
// 放大手勢
return true;
}
else
{
// 縮小手勢
return false;
}
}