要求
1、支持手機端手指觸屏滑動撞秋,控制物體移動长捧;
2、不能超出屏幕邊界(左吻贿、上串结、右、下)
知識點
1、手指輸入肌割,當前使用Input來實現(xiàn)(也可用EsayTouch5實現(xiàn))
//獲取水平卧蜓、垂直方向增量,范圍(-1~1)把敞,對應鍵盤的wasd按鍵或上下左右按鍵操作弥奸;
Input.GetAxis ("Vertical")
Input.GetAxis ("Horizontal")
//獲取鼠標增量,當前幀和上一幀鼠標移動的距離奋早,移動設備觸摸也可使用盛霎,范圍不局限于(-1~1)
Input.GetAxis ("Mouse X")
Input.GetAxis ("Mouse Y")
所以在移動設備上通過手指移動物體,我們應先獲得鼠標增量值耽装,然后用于設置物體的移動愤炸。
使用控制器和鍵盤輸入時此值范圍在-1到1之間。
如果坐標軸設置為鼠標運動增量,鼠標增量乘以坐標軸靈敏度的范圍將不是-1到1 ;
2掉奄、獲取移動設備屏幕寬高规个,以及左上右下邊界位置:
因為游戲是2D模式,且攝像機的選擇了正交投影Orthographic
我們可以直接通過攝像機獲得設備寬高和邊界信息:
//獲取主攝像機
Camera cam = Camera.main;
//高度為攝像機正交投影大小的兩倍
height = 2f * cam.orthographicSize;
//寬度為高度乘以攝像機視角的寬高比(即移動設備屏幕的寬高比)
width = height * cam.aspect;
//當前攝像機位置為(0姓建,0)诞仓,下面是計算屏幕邊界距離中心點的位置
left = -width / 2;
right = width / 2;
top = height / 2;
bottom = -height / 2;
3、物體的移動方式選擇
2D游戲中引瀑,物體使用了rigidbody2D狂芋,我們不應通過Transform去控制物體的移動(因性能太低);
應通過rigidbody2D來控制物體的移動憨栽,如:
rigidbody.velocity = new Vector2 (h * speed, v * speed);
代碼實現(xiàn)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainMove : MonoBehaviour
{
public float speed = 5f;
private Rigidbody2D rigidbody;
private float velocity_zero = 0;
private float width;
private float height;
private float left;
private float right;
private float top;
private float bottom;
void Awake ()
{
rigidbody = GetComponent<Rigidbody2D> ();
rigidbody.velocity = new Vector2 (velocity_zero, velocity_zero);
Camera cam = Camera.main;
height = 2f * cam.orthographicSize;
width = height * cam.aspect;
left = -width / 2;
right = width / 2;
top = height / 2;
bottom = -height / 2;
}
bool isTouch = false;
float h;
float v;
void Update ()
{
if (h != 0 || v != 0) {
isTouch = true;
} else {
isTouch = false;
}
h = Input.GetAxis ("Mouse X");
v = Input.GetAxis ("Mouse Y");
Debug.Log ("h:" + h + " v:" + v);
if (isTouch) {
if (Mathf.Abs (h) > 0.01f || Mathf.Abs (v) > 0.01f) {
if (isWidthBoundary (h)) {
rigidbody.velocity = new Vector2 (velocity_zero, v * speed);
} else if (isHeightBoundary (v)) {
rigidbody.velocity = new Vector2 (h * speed, velocity_zero);
} else {
rigidbody.velocity = new Vector2 (h * speed, v * speed);
}
Debug.Log (rigidbody.velocity);
} else {
rigidbody.velocity = new Vector2 (velocity_zero, velocity_zero);
}
}
}
bool isWidthBoundary (float h)
{
//在left與right之間帜矾,返回false
//在left左邊,手勢為正方向屑柔,返回false
//在right右邊屡萤,手勢為反方向,返回false
if (transform.position.x > left && transform.position.x < right) {
return false;
}
if (transform.position.x < left && h > 0) {
return false;
}
if (transform.position.x > right && h < 0) {
return false;
}
return true;
}
bool isHeightBoundary (float v)
{
//在top與right之間掸宛,返回false
//在top上邊死陆,手勢為正方向,返回false
//在bottom下邊唧瘾,手勢為反方向措译,返回false
if (transform.position.y > bottom && transform.position.y < top) {
return false;
}
if (transform.position.y > top && v < 0) {
return false;
}
if (transform.position.y < bottom && v > 0) {
return false;
}
return true;
}
}
效果圖
a.gif