最近,又在弄Unity3D,因为unity3d提供了官方的2d游戏设计工具,用下来还不错。
就比较而言,unity3d和国内比较流行的cocos2d比较而言,unity3d的商城更好用,或者说外部支持做得更好。
在2d游戏中同时拖动多个对象,找了很久没找到代码,只好自己写了。虽然看上去,会有bug,不过,性能比我能想到的其它方法要好。
[csharp]
- using UnityEngine;
- using System.Collections;
- /// <summary>
- /// 多个对象拖动
- /// </summary>
- public class MultipleDrag : MonoBehaviour
- {
- /// <summary>
- /// 触摸总数
- /// </summary>
- private int touchCount = -1;
- /// <summary>
- /// 触摸ID
- /// </summary>
- private int touchID = -1;
- /// <summary>
- /// 每帧更新
- /// </summary>
- private void Update()
- {
- if (Input.touchCount > 0)
- {
- if (touchCount != Input.touchCount)
- {
- //当触摸总数改变,从新获得触摸ID
- touchID = -1;
- touchCount = Input.touchCount;
- for (int i = 0; i < touchCount; i++)
- {
- Vector3 wp = Camera.main.ScreenToWorldPoint(Input.touches.position);
- Vector2 touchPos = new Vector2(wp.x, wp.y);
- if (collider2D == Physics2D.OverlapPoint(touchPos))
- {
- touchID = Input.touches.fingerId;
- break;
- }
- }
- }
- else
- {
- //当触摸总数没变,根据触摸ID定位
- if (touchID > -1)
- {
- for (int i = 0; i < Input.touchCount; i++)
- {
- if (Input.touches.fingerId == touchID)
- {
- Vector3 wp = Camera.main.ScreenToWorldPoint(Input.touches.position);
- transform.position = new Vector2(wp.x, wp.y);
- break;
- }
- }
- }
- }
- }
- else
- {
- touchCount = -1;
- touchID = -1;
- }
- }
- }