unity3d在2d游戏中同时拖动多个collider

最近,又在弄unity3d,因为unity3d提供了官方的2d游戏设计工具,用下来还不错。

就比较而言,unity3d和国内比较流行的cocos2d比较而言,unity3d的商城更好用,或者说外部支持做得更好。


在2d游戏中同时拖动多个对象,找了很久没找到代码,只好自己写了。虽然看上去,会有bug,不过,性能比我能想到的其它方法要好。

/**
 *
 * 作者:红尘不到
 * 日期:2015年2月13日
 * 版本:1.0
 * 说明:多个对象拖动
 **/
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[i].position);
                    Vector2 touchPos = new Vector2(wp.x, wp.y);
                    if (collider2D == Physics2D.OverlapPoint(touchPos))
                    {
                        touchID = Input.touches[i].fingerId;
                        break;
                    }
                }
            }
            else
            {
                //当触摸总数没变,根据触摸ID定位
                if (touchID > -1)
                {
                    for (int i = 0; i < Input.touchCount; i++)
                    {
                        if (Input.touches[i].fingerId == touchID)
                        {
                            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.touches[i].position);
                            transform.position = new Vector2(wp.x, wp.y);
                            break;
                        }
                    }
                }
            }
        }
        else
        {
            touchCount = -1;
            touchID = -1;
        }
    }
}


另外,这个方法只能对collider对象起作用。如果同时拖动多个4.6 ui的对象,我也没想到好的办法。

如果是需要拖动3d界面下的,可以看看高通的这段程序,也许有帮助。https://developer.vuforia.com/resources/dev-guide/unity-drag-ar-object-screen-your-finger


这里是我做的demo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值