Unity3D实现甜品消消乐游戏
前言
解释:
之前用的screentogif录屏,因为上传的.gif最大不超过5mb,所以做了不少删帧和色彩弱化等处理,这才导致色彩看上去不是很舒服,不要盯着它看太久,不然会有点难受...
由于使用的素材是现成的,没有花时间精力去扒,所以细节方面可能不是做的很好。
说明:
这次的甜品消消乐虽然看上去好像挺简单普通的,但是相对于之前的坦克大战,某种程度上已然提升难度了,归类到了算法类层的游戏。
拉到最后看代码你就能理解我的意思了,坦克大战的所有代码加起来还不如消消乐两个类的代码多,其他各种细节,坦克也只能望其项背...
如果坦克大战是低阶的,那么甜品消消乐就是中阶的,有着不少的动画效果和交互(碰撞检测和甜品的控制等),游戏运行的所有机制和功能需要在模型层上进行操控。
这次的消消乐需要一定的逻辑思维、算法基础、unity综合能力和编程基础。
方正粗圆的字体和布灵布灵的闪光特效会赋予游戏可爱风的氛围感。
我们把物体分为模型层和渲染层,这样它们各司其职,降低工作的耦合性。
由于12.29日放假前还剩 两门课设答辩和一门考试,不足之处以后再补充...
项目效果展示
项目概况
素材展示
游戏资源(音频、图片、特效等)
场景和包(动画。渲染精灵和控制器等)
游戏脚本(ui、runtime等)
......太多了,只选择了部分作为展示
场景展示
在gizmos目录下,可以找到对应按钮隐藏摄像机,这样处理场景的时候会舒服很多
clone都放上会有些杂乱,都删掉,只放了一个背景图
场景元素
开始按钮(玩家通过点击开始按钮,进入新的一局游戏)
重玩按钮(玩家可以及时返回开始界面进行相应操作)
时钟(显示游戏剩余时间,一局游戏初始化时间是60s)
计分板(显示当前游戏得分)
普通甜品(甜甜圈、糖果、起司...至少同时有3个在同一排或同一列时,可以消除)
特殊甜品(一定条件下会触发2种特殊甜品道具,一种是带有左右晃动特效的甜品,可以消除一整排的甜品;另一种是带有上下晃动特效的甜品,可以消除一整列的甜品)
积分面板(游戏时间结束后,会用类似飞跃的动画效果产生得分界面窗口,逐渐变大显示,最终定格。点击重玩立即开始下一局游戏,叉掉返回开始界面)
玩法介绍
- 点击开始进入游戏,每一局新开的游戏设时60s(可以根据需要调整),用最快的速度消除出现在同一行或者同一列的相同的甜点会获得相应积分。
- 尽量用最优的策略使得一定时间内的积分最大化(不过这一点,游戏玩熟了可能才能渐渐领悟,属于大师级别的操作了。可以用acm相关算法写个外挂,应该是用动态规划算法处理)。
- 当符合特定消除条件的甜品被消除后,会随机产生两类特殊甜品的一种,这个甜品会瞬间清除一整行或者一整列的甜品,使得积分暴增。
- 相同时间内积分高者或者相同积分用时少者优胜。
版本说明
小虾选用的是unity个人版,采用的是unity一个较新的版本-2021.1.16,这里建议小伙伴们下载和教程相同版本的,不然真的会有可能遇到卡点消耗心情哈。
可以和我一样在unity hub里面安装,hub感觉挺好用的。
但是每次重启后都要手动激活许可证,这是真的挺烦的。
项目源码
小虾在这里主要介绍部分核心代码实现,想知道其他部分实现的小伙伴在下方留言,我再添加~
ui-propertydrawers-menuoptions.cs
using system; using unityeditor.scenemanagement; using unityengine; using unityengine.eventsystems; using unityengine.ui; using unityengine.scenemanagement; using unityeditor.experimental.scenemanagement; namespace unityeditor.ui { /// <summary> /// this script adds the ui menu options to the unity editor. /// </summary> static internal class menuoptions { private const string kuilayername = "ui"; private const string kstandardspritepath = "ui/skin/uisprite.psd"; private const string kbackgroundspritepath = "ui/skin/background.psd"; private const string kinputfieldbackgroundpath = "ui/skin/inputfieldbackground.psd"; private const string kknobpath = "ui/skin/knob.psd"; private const string kcheckmarkpath = "ui/skin/checkmark.psd"; private const string kdropdownarrowpath = "ui/skin/dropdownarrow.psd"; private const string kmaskpath = "ui/skin/uimask.psd"; static private defaultcontrols.resources s_standardresources; static private defaultcontrols.resources getstandardresources() { if (s_standardresources.standard == null) { s_standardresources.standard = assetdatabase.getbuiltinextraresource<sprite>(kstandardspritepath); s_standardresources.background = assetdatabase.getbuiltinextraresource<sprite>(kbackgroundspritepath); s_standardresources.inputfield = assetdatabase.getbuiltinextraresource<sprite>(kinputfieldbackgroundpath); s_standardresources.knob = assetdatabase.getbuiltinextraresource<sprite>(kknobpath); s_standardresources.checkmark = assetdatabase.getbuiltinextraresource<sprite>(kcheckmarkpath); s_standardresources.dropdown = assetdatabase.getbuiltinextraresource<sprite>(kdropdownarrowpath); s_standardresources.mask = assetdatabase.getbuiltinextraresource<sprite>(kmaskpath); } return s_standardresources; } private class defaulteditorfactory : defaultcontrols.ifactorycontrols { public static defaulteditorfactory default = new defaulteditorfactory(); public gameobject creategameobject(string name, params type[] components) { return objectfactory.creategameobject(name, components); } } private class factoryswaptoeditor : idisposable { defaultcontrols.ifactorycontrols factory; public factoryswaptoeditor() { factory = defaultcontrols.factory; defaultcontrols.factory = defaulteditorfactory.default; } public void dispose() { defaultcontrols.factory = factory; } } private static void setpositionvisibleinsceneview(recttransform canvasrtransform, recttransform itemtransform) { sceneview sceneview = sceneview.lastactivesceneview; // couldn't find a sceneview. don't set position. if (sceneview == null || sceneview.camera == null) return; // create world space plane from canvas position. vector2 localplaneposition; camera camera = sceneview.camera; vector3 position = vector3.zero; if (recttransformutility.screenpointtolocalpointinrectangle(canvasrtransform, new vector2(camera.pixelwidth / 2, camera.pixelheight / 2), camera, out localplaneposition)) { // adjust for canvas pivot localplaneposition.x = localplaneposition.x + canvasrtransform.sizedelta.x * canvasrtransform.pivot.x; localplaneposition.y = localplaneposition.y + canvasrtransform.sizedelta.y * canvasrtransform.pivot.y; localplaneposition.x = mathf.clamp(localplaneposition.x, 0, canvasrtransform.sizedelta.x); localplaneposition.y = mathf.clamp(localplaneposition.y, 0, canvasrtransform.sizedelta.y); // adjust for anchoring position.x = localplaneposition.x - canvasrtransform.sizedelta.x * itemtransform.anchormin.x; position.y = localplaneposition.y - canvasrtransform.sizedelta.y * itemtransform.anchormin.y; vector3 minlocalposition; minlocalposition.x = canvasrtransform.sizedelta.x * (0 - canvasrtransform.pivot.x) + itemtransform.sizedelta.x * itemtransform.pivot.x; minlocalposition.y = canvasrtransform.sizedelta.y * (0 - canvasrtransform.pivot.y) + itemtransform.sizedelta.y * itemtransform.pivot.y; vector3 maxlocalposition; maxlocalposition.x = canvasrtransform.sizedelta.x * (1 - canvasrtransform.pivot.x) - itemtransform.sizedelta.x * itemtransform.pivot.x; maxlocalposition.y = canvasrtransform.sizedelta.y * (1 - canvasrtransform.pivot.y) - itemtransform.sizedelta.y * itemtransform.pivot.y; position.x = mathf.clamp(position.x, minlocalposition.x, maxlocalposition.x); position.y = mathf.clamp(position.y, minlocalposition.y, maxlocalposition.y); } itemtransform.anchoredposition = position; itemtransform.localrotation = quaternion.identity; itemtransform.localscale = vector3.one; } private static void placeuielementroot(gameobject element, menucommand menucommand) { gameobject parent = menucommand.context as gameobject; bool explicitparentchoice = true; if (parent == null) { parent = getorcreatecanvasgameobject(); explicitparentchoice = false; // if in prefab mode, canvas has to be part of prefab contents, // otherwise use prefab root instead. prefabstage prefabstage = prefabstageutility.getcurrentprefabstage(); if (prefabstage != null && !prefabstage.ispartofprefabcontents(parent)) parent = prefabstage.prefabcontentsroot; } if (parent.getcomponentsinparent<canvas>(true).length == 0) { // create canvas under context gameobject, // and make that be the parent which ui element is added under. gameobject canvas = menuoptions.createnewui(); undo.settransformparent(canvas.transform, parent.transform, ""); parent = canvas; } gameobjectutility.ensureuniquenameforsibling(element); setparentandalign(element, parent); if (!explicitparentchoice) // not a context click, so center in sceneview setpositionvisibleinsceneview(parent.getcomponent<recttransform>(), element.getcomponent<recttransform>()); // this call ensure any change made to created objects after they where registered will be part of the undo. undo.registerfullobjecthierarchyundo(parent == null ? element : parent, ""); // we have to fix up the undo name since the name of the object was only known after reparenting it. undo.setcurrentgroupname("create " + element.name); selection.activegameobject = element; } private static void setparentandalign(gameobject child, gameobject parent) { if (parent == null) return; undo.settransformparent(child.transform, parent.transform, ""); recttransform recttransform = child.transform as recttransform; if (recttransform) { recttransform.anchoredposition = vector2.zero; vector3 localposition = recttransform.localposition; localposition.z = 0; recttransform.localposition = localposition; } else { child.transform.localposition = vector3.zero; } child.transform.localrotation = quaternion.identity; child.transform.localscale = vector3.one; setlayerrecursively(child, parent.layer); } private static void setlayerrecursively(gameobject go, int layer) { go.layer = layer; transform t = go.transform; for (int i = 0; i < t.childcount; i++) setlayerrecursively(t.getchild(i).gameobject, layer); } // graphic elements [menuitem("gameobject/ui/text", false, 2000)] static public void addtext(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createtext(getstandardresources()); placeuielementroot(go, menucommand); } [menuitem("gameobject/ui/image", false, 2001)] static public void addimage(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createimage(getstandardresources()); placeuielementroot(go, menucommand); } [menuitem("gameobject/ui/raw image", false, 2002)] static public void addrawimage(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createrawimage(getstandardresources()); placeuielementroot(go, menucommand); } // controls // button and toggle are controls you just click on. [menuitem("gameobject/ui/button", false, 2030)] static public void addbutton(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createbutton(getstandardresources()); placeuielementroot(go, menucommand); } [menuitem("gameobject/ui/toggle", false, 2031)] static public void addtoggle(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createtoggle(getstandardresources()); placeuielementroot(go, menucommand); } // slider and scrollbar modify a number [menuitem("gameobject/ui/slider", false, 2033)] static public void addslider(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createslider(getstandardresources()); placeuielementroot(go, menucommand); } [menuitem("gameobject/ui/scrollbar", false, 2034)] static public void addscrollbar(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createscrollbar(getstandardresources()); placeuielementroot(go, menucommand); } // more advanced controls below [menuitem("gameobject/ui/dropdown", false, 2035)] static public void adddropdown(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createdropdown(getstandardresources()); placeuielementroot(go, menucommand); } [menuitem("gameobject/ui/input field", false, 2036)] public static void addinputfield(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createinputfield(getstandardresources()); placeuielementroot(go, menucommand); } // containers [menuitem("gameobject/ui/canvas", false, 2060)] static public void addcanvas(menucommand menucommand) { var go = createnewui(); setparentandalign(go, menucommand.context as gameobject); if (go.transform.parent as recttransform) { recttransform rect = go.transform as recttransform; rect.anchormin = vector2.zero; rect.anchormax = vector2.one; rect.anchoredposition = vector2.zero; rect.sizedelta = vector2.zero; } selection.activegameobject = go; } [menuitem("gameobject/ui/panel", false, 2061)] static public void addpanel(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createpanel(getstandardresources()); placeuielementroot(go, menucommand); // panel is special, we need to ensure there's no padding after repositioning. recttransform rect = go.getcomponent<recttransform>(); rect.anchoredposition = vector2.zero; rect.sizedelta = vector2.zero; } [menuitem("gameobject/ui/scroll view", false, 2062)] static public void addscrollview(menucommand menucommand) { gameobject go; using (new factoryswaptoeditor()) go = defaultcontrols.createscrollview(getstandardresources()); placeuielementroot(go, menucommand); } // helper methods static public gameobject createnewui() { // root for the ui var root = objectfactory.creategameobject("canvas", typeof(canvas), typeof(canvasscaler), typeof(graphicraycaster)); root.layer = layermask.nametolayer(kuilayername); canvas canvas = root.getcomponent<canvas>(); canvas.rendermode = rendermode.screenspaceoverlay; // works for all stages. stageutility.placegameobjectincurrentstage(root); bool customscene = false; prefabstage prefabstage = prefabstageutility.getcurrentprefabstage(); if (prefabstage != null) { undo.settransformparent(root.transform, prefabstage.prefabcontentsroot.transform, ""); customscene = true; } undo.setcurrentgroupname("create " + root.name); // if there is no event system add one... // no need to place event system in custom scene as these are temporary anyway. // it can be argued for or against placing it in the user scenes, // but let's not modify scene user is not currently looking at. if (!customscene) createeventsystem(false); return root; } [menuitem("gameobject/ui/event system", false, 2100)] public static void createeventsystem(menucommand menucommand) { gameobject parent = menucommand.context as gameobject; createeventsystem(true, parent); } private static void createeventsystem(bool select) { createeventsystem(select, null); } private static void createeventsystem(bool select, gameobject parent) { stagehandle stage = parent == null ? stageutility.getcurrentstagehandle() : stageutility.getstagehandle(parent); var esys = stage.findcomponentoftype<eventsystem>(); if (esys == null) { var eventsystem = objectfactory.creategameobject("eventsystem"); if (parent == null) stageutility.placegameobjectincurrentstage(eventsystem); else setparentandalign(eventsystem, parent); esys = objectfactory.addcomponent<eventsystem>(eventsystem); objectfactory.addcomponent<standaloneinputmodule>(eventsystem); undo.registercreatedobjectundo(eventsystem, "create " + eventsystem.name); } if (select && esys != null) { selection.activegameobject = esys.gameobject; } } // helper function that returns a canvas gameobject; preferably a parent of the selection, or other existing canvas. static public gameobject getorcreatecanvasgameobject() { gameobject selectedgo = selection.activegameobject; // try to find a gameobject that is the selected go or one if its parents. canvas canvas = (selectedgo != null) ? selectedgo.getcomponentinparent<canvas>() : null; if (isvalidcanvas(canvas)) return canvas.gameobject; // no canvas in selection or its parents? then use any valid canvas. // we have to find all loaded canvases, not just the ones in main scenes. canvas[] canvasarray = stageutility.getcurrentstagehandle().findcomponentsoftype<canvas>(); for (int i = 0; i < canvasarray.length; i++) if (isvalidcanvas(canvasarray[i])) return canvasarray[i].gameobject; // no canvas in the scene at all? then create a new one. return menuoptions.createnewui(); } static bool isvalidcanvas(canvas canvas) { if (canvas == null || !canvas.gameobject.activeinhierarchy) return false; // it's important that the non-editable canvas from a prefab scene won't be rejected, // but canvases not visible in the hierarchy at all do. don't check for hideanddontsave. if (editorutility.ispersistent(canvas) || (canvas.hideflags & hideflags.hideinhierarchy) != 0) return false; return stageutility.getstagehandle(canvas.gameobject) == stageutility.getcurrentstagehandle(); } } }
editor-eventsystem-eventtriggereditors.cs
using system; using unityengine; using unityengine.eventsystems; namespace unityeditor.eventsystems { [customeditor(typeof(eventtrigger), true)] public class eventtriggereditor : editor { serializedproperty m_delegatesproperty; guicontent m_icontoolbarminus; guicontent m_eventidname; guicontent[] m_eventtypes; guicontent m_addbutoncontent; protected virtual void onenable() { m_delegatesproperty = serializedobject.findproperty("m_delegates"); m_addbutoncontent = editorguiutility.trtextcontent("add new event type"); m_eventidname = new guicontent(""); // have to create a copy since otherwise the tooltip will be overwritten. m_icontoolbarminus = new guicontent(editorguiutility.iconcontent("toolbar minus")); m_icontoolbarminus.tooltip = "remove all events in this list."; string[] eventnames = enum.getnames(typeof(eventtriggertype)); m_eventtypes = new guicontent[eventnames.length]; for (int i = 0; i < eventnames.length; ++i) { m_eventtypes[i] = new guicontent(eventnames[i]); } } public override void oninspectorgui() { serializedobject.update(); int toberemovedentry = -1; editorguilayout.space(); vector2 removebuttonsize = guistyle.none.calcsize(m_icontoolbarminus); for (int i = 0; i < m_delegatesproperty.arraysize; ++i) { serializedproperty delegateproperty = m_delegatesproperty.getarrayelementatindex(i); serializedproperty eventproperty = delegateproperty.findpropertyrelative("eventid"); serializedproperty callbacksproperty = delegateproperty.findpropertyrelative("callback"); m_eventidname.text = eventproperty.enumdisplaynames[eventproperty.enumvalueindex]; editorguilayout.propertyfield(callbacksproperty, m_eventidname); rect callbackrect = guilayoututility.getlastrect(); rect removebuttonpos = new rect(callbackrect.xmax - removebuttonsize.x - 8, callbackrect.y + 1, removebuttonsize.x, removebuttonsize.y); if (gui.button(removebuttonpos, m_icontoolbarminus, guistyle.none)) { toberemovedentry = i; } editorguilayout.space(); } if (toberemovedentry > -1) { removeentry(toberemovedentry); } rect btposition = guilayoututility.getrect(m_addbutoncontent, gui.skin.button); const float addbutonwidth = 200f; btposition.x = btposition.x + (btposition.width - addbutonwidth) / 2; btposition.width = addbutonwidth; if (gui.button(btposition, m_addbutoncontent)) { showaddtriggermenu(); } serializedobject.applymodifiedproperties(); } private void removeentry(int toberemovedentry) { m_delegatesproperty.deletearrayelementatindex(toberemovedentry); } void showaddtriggermenu() { // now create the menu, add items and show it genericmenu menu = new genericmenu(); for (int i = 0; i < m_eventtypes.length; ++i) { bool active = true; // check if we already have a entry for the current eventtype, if so, disable it for (int p = 0; p < m_delegatesproperty.arraysize; ++p) { serializedproperty delegateentry = m_delegatesproperty.getarrayelementatindex(p); serializedproperty eventproperty = delegateentry.findpropertyrelative("eventid"); if (eventproperty.enumvalueindex == i) { active = false; } } if (active) menu.additem(m_eventtypes[i], false, onaddnewselected, i); else menu.adddisableditem(m_eventtypes[i]); } menu.showascontext(); event.current.use(); } private void onaddnewselected(object index) { int selected = (int)index; m_delegatesproperty.arraysize += 1; serializedproperty delegateentry = m_delegatesproperty.getarrayelementatindex(m_delegatesproperty.arraysize - 1); serializedproperty eventproperty = delegateentry.findpropertyrelative("eventid"); eventproperty.enumvalueindex = selected; serializedobject.applymodifiedproperties(); } } }
runtime-uielements-executeevents.cs
using system; using system.collections.generic; using unityengine.pool; namespace unityengine.eventsystems { public static class executeevents { public delegate void eventfunction<t1>(t1 handler, baseeventdata eventdata); public static t validateeventdata<t>(baseeventdata data) where t : class { if ((data as t) == null) throw new argumentexception(string.format("invalid type: {0} passed to event expecting {1}", data.gettype(), typeof(t))); return data as t; } private static readonly eventfunction<ipointermovehandler> s_pointermovehandler = execute; private static void execute(ipointermovehandler handler, baseeventdata eventdata) { handler.onpointermove(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<ipointerenterhandler> s_pointerenterhandler = execute; private static void execute(ipointerenterhandler handler, baseeventdata eventdata) { handler.onpointerenter(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<ipointerexithandler> s_pointerexithandler = execute; private static void execute(ipointerexithandler handler, baseeventdata eventdata) { handler.onpointerexit(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<ipointerdownhandler> s_pointerdownhandler = execute; private static void execute(ipointerdownhandler handler, baseeventdata eventdata) { handler.onpointerdown(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<ipointeruphandler> s_pointeruphandler = execute; private static void execute(ipointeruphandler handler, baseeventdata eventdata) { handler.onpointerup(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<ipointerclickhandler> s_pointerclickhandler = execute; private static void execute(ipointerclickhandler handler, baseeventdata eventdata) { handler.onpointerclick(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<iinitializepotentialdraghandler> s_initializepotentialdraghandler = execute; private static void execute(iinitializepotentialdraghandler handler, baseeventdata eventdata) { handler.oninitializepotentialdrag(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<ibegindraghandler> s_begindraghandler = execute; private static void execute(ibegindraghandler handler, baseeventdata eventdata) { handler.onbegindrag(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<idraghandler> s_draghandler = execute; private static void execute(idraghandler handler, baseeventdata eventdata) { handler.ondrag(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<ienddraghandler> s_enddraghandler = execute; private static void execute(ienddraghandler handler, baseeventdata eventdata) { handler.onenddrag(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<idrophandler> s_drophandler = execute; private static void execute(idrophandler handler, baseeventdata eventdata) { handler.ondrop(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<iscrollhandler> s_scrollhandler = execute; private static void execute(iscrollhandler handler, baseeventdata eventdata) { handler.onscroll(validateeventdata<pointereventdata>(eventdata)); } private static readonly eventfunction<iupdateselectedhandler> s_updateselectedhandler = execute; private static void execute(iupdateselectedhandler handler, baseeventdata eventdata) { handler.onupdateselected(eventdata); } private static readonly eventfunction<iselecthandler> s_selecthandler = execute; private static void execute(iselecthandler handler, baseeventdata eventdata) { handler.onselect(eventdata); } private static readonly eventfunction<ideselecthandler> s_deselecthandler = execute; private static void execute(ideselecthandler handler, baseeventdata eventdata) { handler.ondeselect(eventdata); } private static readonly eventfunction<imovehandler> s_movehandler = execute; private static void execute(imovehandler handler, baseeventdata eventdata) { handler.onmove(validateeventdata<axiseventdata>(eventdata)); } private static readonly eventfunction<isubmithandler> s_submithandler = execute; private static void execute(isubmithandler handler, baseeventdata eventdata) { handler.onsubmit(eventdata); } private static readonly eventfunction<icancelhandler> s_cancelhandler = execute; private static void execute(icancelhandler handler, baseeventdata eventdata) { handler.oncancel(eventdata); } public static eventfunction<ipointermovehandler> pointermovehandler { get { return s_pointermovehandler; } } public static eventfunction<ipointerenterhandler> pointerenterhandler { get { return s_pointerenterhandler; } } public static eventfunction<ipointerexithandler> pointerexithandler { get { return s_pointerexithandler; } } public static eventfunction<ipointerdownhandler> pointerdownhandler { get { return s_pointerdownhandler; } } public static eventfunction<ipointeruphandler> pointeruphandler { get { return s_pointeruphandler; } } public static eventfunction<ipointerclickhandler> pointerclickhandler { get { return s_pointerclickhandler; } } public static eventfunction<iinitializepotentialdraghandler> initializepotentialdrag { get { return s_initializepotentialdraghandler; } } public static eventfunction<ibegindraghandler> begindraghandler { get { return s_begindraghandler; } } public static eventfunction<idraghandler> draghandler { get { return s_draghandler; } } public static eventfunction<ienddraghandler> enddraghandler { get { return s_enddraghandler; } } public static eventfunction<idrophandler> drophandler { get { return s_drophandler; } } public static eventfunction<iscrollhandler> scrollhandler { get { return s_scrollhandler; } } public static eventfunction<iupdateselectedhandler> updateselectedhandler { get { return s_updateselectedhandler; } } public static eventfunction<iselecthandler> selecthandler { get { return s_selecthandler; } } public static eventfunction<ideselecthandler> deselecthandler { get { return s_deselecthandler; } } public static eventfunction<imovehandler> movehandler { get { return s_movehandler; } } public static eventfunction<isubmithandler> submithandler { get { return s_submithandler; } } public static eventfunction<icancelhandler> cancelhandler { get { return s_cancelhandler; } } private static void geteventchain(gameobject root, ilist<transform> eventchain) { eventchain.clear(); if (root == null) return; var t = root.transform; while (t != null) { eventchain.add(t); t = t.parent; } } public static bool execute<t>(gameobject target, baseeventdata eventdata, eventfunction<t> functor) where t : ieventsystemhandler { var internalhandlers = listpool<ieventsystemhandler>.get(); geteventlist<t>(target, internalhandlers); // if (s_internalhandlers.count > 0) // debug.log("executinng " + typeof (t) + " on " + target); var internalhandlerscount = internalhandlers.count; for (var i = 0; i < internalhandlerscount; i++) { t arg; try { arg = (t)internalhandlers[i]; } catch (exception e) { var temp = internalhandlers[i]; debug.logexception(new exception(string.format("type {0} expected {1} received.", typeof(t).name, temp.gettype().name), e)); continue; } try { functor(arg, eventdata); } catch (exception e) { debug.logexception(e); } } var handlercount = internalhandlers.count; listpool<ieventsystemhandler>.release(internalhandlers); return handlercount > 0; } /// <summary> /// execute the specified event on the first game object underneath the current touch. /// </summary> private static readonly list<transform> s_internaltransformlist = new list<transform>(30); public static gameobject executehierarchy<t>(gameobject root, baseeventdata eventdata, eventfunction<t> callbackfunction) where t : ieventsystemhandler { geteventchain(root, s_internaltransformlist); var internaltransformlistcount = s_internaltransformlist.count; for (var i = 0; i < internaltransformlistcount; i++) { var transform = s_internaltransformlist[i]; if (execute(transform.gameobject, eventdata, callbackfunction)) return transform.gameobject; } return null; } private static bool shouldsendtocomponent<t>(component component) where t : ieventsystemhandler { var valid = component is t; if (!valid) return false; var behaviour = component as behaviour; if (behaviour != null) return behaviour.isactiveandenabled; return true; } /// <summary> /// get the specified object's event event. /// </summary> private static void geteventlist<t>(gameobject go, ilist<ieventsystemhandler> results) where t : ieventsystemhandler { // debug.logwarning("geteventlist<" + typeof(t).name + ">"); if (results == null) throw new argumentexception("results array is null", "results"); if (go == null || !go.activeinhierarchy) return; var components = listpool<component>.get(); go.getcomponents(components); var componentscount = components.count; for (var i = 0; i < componentscount; i++) { if (!shouldsendtocomponent<t>(components[i])) continue; // debug.log(string.format("{2} found! on {0}.{1}", go, s_getcomponentsscratch[i].gettype(), typeof(t))); results.add(components[i] as ieventsystemhandler); } listpool<component>.release(components); // debug.logwarning("end geteventlist<" + typeof(t).name + ">"); } /// <summary> /// whether the specified game object will be able to handle the specified event. /// </summary> public static bool canhandleevent<t>(gameobject go) where t : ieventsystemhandler { var internalhandlers = listpool<ieventsystemhandler>.get(); geteventlist<t>(go, internalhandlers); var handlercount = internalhandlers.count; listpool<ieventsystemhandler>.release(internalhandlers); return handlercount != 0; } /// <summary> /// bubble the specified event on the game object, figuring out which object will actually receive the event. /// </summary> public static gameobject geteventhandler<t>(gameobject root) where t : ieventsystemhandler { if (root == null) return null; transform t = root.transform; while (t != null) { if (canhandleevent<t>(t.gameobject)) return t.gameobject; t = t.parent; } return null; } } }
以上就是unity3d实现甜品消消乐游戏的详细内容,更多关于unity3d消消乐游戏的资料请关注其它相关文章!