Unity是一个跨平台的游戏引擎,也正因如此,受到广大用户的青睐。在现有游戏公司中,用Unity开发手游的项目比比皆是,典型的成功案例就是腾讯的《王者荣耀》!
Unity发布的APP如何具有触摸操作呢?这是一个关键问题!
但虽然关键,却不复杂。
1. 在PC机上的鼠标左键功能,可以自动变成手机屏幕的单指操作功能。如下面是用射线实现鼠标左键选择对象,并移动对象的程序,把它加载到一个对象的身上,发布到手机上,你会发现,当手指选择到这个对象时,便可以拖拽移动它。
Ray ray;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButton(0))
{
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
hit.transform.GetComponent<Renderer>().material.color = Color.red;
this.transform.position = new Vector3(hit.point.x, hit.point.y, this.transform.position.z);
} else
this.GetComponent<Renderer>().material.color = Color.white;
2. 应用Unity下的Input类中的Touch,实现对游戏对象的单点,以下是单点操作移动对象的例子。
int touchNum = Input.touchCount;
if (touchNum > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
Vector3 move = new Vector3(touch.deltaPosition.x, touch.deltaPosition.y, 0f) * velocity;
transform.Translate(move);
}
}
3. 应用Unity下的Input类中的Touch,实现对游戏对象的多点操作,以下是双指操作缩放对象的例子。
if (Input.touchCount > 1)
{
Touch newTouch1 = Input.GetTouch(0);
Touch newTouch2 = Input.GetTouch(1);
if (newTouch2.phase == TouchPhase.Began)
{
oldTouch2 = newTouch2;
oldTouch1 = newTouch1;
return;
}
float oldDistance = Vector2.Distance(oldTouch1.position, oldTouch2.position);
float newDistance = Vector2.Distance(newTouch1.position, newTouch2.position);
float offset = newDistance - oldDistance;
float scaleFactor = offset / 200f;
Vector3 localScale = this.transform.localScale;
Vector3 scale = new Vector3(localScale.x + scaleFactor, localScale.y + scaleFactor,localScale.z + scaleFactor);
this.transform.localScale = scale;
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
}