需求1:通过Touch实现点击物体跟随
思路:是否触摸,获取触摸位置并记录,游戏物体跟随触摸位置变化
代码
public class TouchTest : MonoBehaviour {
public float speed = 0.1F;
public GameObject cube;
void Update () {
//首先是否有在触摸且输入的第一个触摸相位信息是否在移动
if (Input.touchCount>0&& Input.GetTouch(0).phase==TouchPhase.Moved)
{
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;//最近一帧的位置信息
//在XY平面上移动
cube.transform.Translate(-touchDeltaPosition.x*speed,-touchDeltaPosition.y*speed,0);
}
}
}
需求2:两指触摸放大缩小物体
思路:两个触摸点,触摸点距离变化,缩放因子,对物体进行缩放
/// <summary>
/// 缩放游戏物体
/// </summary>
private void TouchGameObjectScale()
{
//触摸点需在2个以上
if (Input.touchCount <= 1)
{
return;
}
else
{
//记录两个触摸点
//第一帧先记录点,然后退出
//第二帧以后,缩放
Touch newTouch1 = Input.GetTouch(0);
Touch newTouch2 = Input.GetTouch(1);
//是否已经触摸在屏幕上,第一帧进入,第二帧不进入
if (newTouch2.phase == TouchPhase.Began)
{
//记录两个旧点的信息
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
return;//什么都不做返回
}
//新触摸点和旧触摸点位置距离
float oldDistance = Vector2.Distance(oldTouch1.position, oldTouch2.position);
float newDistance = Vector2.Distance(newTouch1.position, newTouch2.position);
//算出距离变大还是变小
float offset = newDistance - oldDistance;
float scaleFactor = offset / 100f;
Vector3 localScale = transform.localScale;
//缩放游戏物体
Vector3 scale = new Vector3(localScale.x + scaleFactor, localScale.y + scaleFactor, localScale.z + scaleFactor);
if (scale.x > 0.03f && scale.y > 0.03f && scale.z > 0.03f)
{
transform.localScale = scale;
}
//下次移动重新缩放大小
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
}