Csharp/C#教程:Unity实现游戏卡牌滚动效果分享

最近项目中的活动面板要做来回滚动卡牌预览效果,感觉自己来写的话,也能写,但是可能会比较耗时,看到Github上有开源的项目,于是就借用了,Github的资源地址,感谢作者的分享。

本篇博客旨在告诉大家如何利用这个插件。

插件的核心在于工程中的6个脚本,以下是六个脚本的源码:

DragEnhanceView.cs

usingUnityEngine; usingSystem.Collections; usingUnityEngine.UI; usingUnityEngine.EventSystems; publicclassUGUIEnhanceItem:EnhanceItem { privateButtonuButton; privateImageimage; protectedoverridevoidOnStart() { image=GetComponent<Image>(); uButton=GetComponent<Button>(); uButton.onClick.AddListener(OnClickUGUIButton); } privatevoidOnClickUGUIButton() { OnClickEnhanceItem(); } //Settheitem"depth"2dor3d protectedoverridevoidSetItemDepth(floatdepthCurveValue,intdepthFactor,floatitemCount) { intnewDepth=(int)(depthCurveValue*itemCount); this.transform.SetSiblingIndex(newDepth); } publicoverridevoidSetSelectState(boolisCenter) { if(image==null) image=GetComponent<Image>(); image.color=isCenter?Color.white:Color.gray; } }

EnhanceScrollViewDragController.cs

usingUnityEngine; usingSystem.Collections; publicclassEnhanceScrollViewDragController:MonoBehaviour { privateVector2lastPosition=Vector2.zero; privateVector2cachedPosition=Vector2.zero; privateGameObjectdragTarget; privateCameratargetCamera; privateintrayCastMask=0; privatebooldragStart=false; publicvoidSetTargetCameraAndMask(Cameracamera,intmask) { this.targetCamera=camera; this.rayCastMask=mask; } voidUpdate() { if(this.targetCamera==null) return; #ifUNITY_EDITOR ProcessMouseInput(); #elifUNITY_IOS||UNITY_ANDROID ProcessTouchInput(); #endif } ///<summary> ///ProcessMouseInput ///</summary> privatevoidProcessMouseInput() { if(Input.GetMouseButtonDown(0)) { if(targetCamera==null) return; dragTarget=RayCast(this.targetCamera,Input.mousePosition); lastPosition.x=Input.mousePosition.x; lastPosition.y=Input.mousePosition.y; } if(Input.GetMouseButton(0)) { if(dragTarget==null) return; cachedPosition.x=Input.mousePosition.x; cachedPosition.y=Input.mousePosition.y; Vector2delta=cachedPosition-lastPosition; if(!dragStart&&delta.sqrMagnitude!=0f) dragStart=true; if(dragStart) { //Notifytarget dragTarget.SendMessage("OnEnhanceViewDrag",delta,SendMessageOptions.DontRequireReceiver); } lastPosition=cachedPosition; } if(Input.GetMouseButtonUp(0)) { if(dragTarget!=null&&dragStart) { dragTarget.SendMessage("OnEnhaneViewDragEnd",SendMessageOptions.DontRequireReceiver); } dragTarget=null; dragStart=false; } } ///<summary> ///ProcessTouchinput ///</summary> privatevoidProcessTouchInput() { if(Input.touchCount>0) { Touchtouch=Input.GetTouch(0); if(touch.phase==TouchPhase.Began) { if(targetCamera==null) return; dragTarget=RayCast(this.targetCamera,Input.mousePosition); } elseif(touch.phase==TouchPhase.Moved) { if(dragTarget==null) return; if(!dragStart&&touch.deltaPosition.sqrMagnitude!=0f) { dragStart=true; } if(dragStart) { //Notifytarget dragTarget.SendMessage("OnEnhanceViewDrag",touch.deltaPosition,SendMessageOptions.DontRequireReceiver); } } elseif(touch.phase==TouchPhase.Ended) { if(dragTarget!=null&&dragStart) { dragTarget.SendMessage("OnEnhaneViewDragEnd",SendMessageOptions.DontRequireReceiver); } dragTarget=null; dragStart=false; } } } publicGameObjectRayCast(Cameracam,Vector3inPos) { Vector3pos=cam.ScreenToViewportPoint(inPos); if(float.IsNaN(pos.x)||float.IsNaN(pos.y)) returnnull; if(pos.x<0f||pos.x>1f||pos.y<0f||pos.y>1f)returnnull; Rayray=cam.ScreenPointToRay(inPos); floatdis=100f; RaycastHit[]hits=Physics.RaycastAll(ray,dis,rayCastMask); if(hits.Length>0) { for(inti=0;i<hits.Length;i++) { GameObjectgo=hits[i].collider.gameObject; DragEnhanceViewdragView=go.GetComponent<DragEnhanceView>(); if(dragView==null) continue; else { //justreturncurrenthoverobjectourdragtarget returngo; } } } returnnull; } }

EnhanceItem.cs

usingUnityEngine; usingSystem.Collections; publicclassEnhanceItem:MonoBehaviour { //Startindex privateintcurveOffSetIndex=0; publicintCurveOffSetIndex { get{returnthis.curveOffSetIndex;} set{this.curveOffSetIndex=value;} } //Runtimerealindex(Becalculatedinruntime) privateintcurRealIndex=0; publicintRealIndex { get{returnthis.curRealIndex;} set{this.curRealIndex=value;} } //Curvecenteroffset privatefloatdCurveCenterOffset=0.0f; publicfloatCenterOffSet { get{returnthis.dCurveCenterOffset;} set{dCurveCenterOffset=value;} } privateTransformmTrs; voidAwake() { mTrs=this.transform; OnAwake(); } voidStart() { OnStart(); } //UpdateItem'sstatus //1.position //2.scale //3."depth"is2DorzPositionin3Dtosetthefrontandbackitem publicvoidUpdateScrollViewItems( floatxValue, floatdepthCurveValue, intdepthFactor, floatitemCount, floatyValue, floatscaleValue) { Vector3targetPos=Vector3.one; Vector3targetScale=Vector3.one; //position targetPos.x=xValue; targetPos.y=yValue; mTrs.localPosition=targetPos; //Setthe"depth"ofitem //targetPos.z=depthValue; SetItemDepth(depthCurveValue,depthFactor,itemCount); //scale targetScale.x=targetScale.y=scaleValue; mTrs.localScale=targetScale; } protectedvirtualvoidOnClickEnhanceItem() { EnhanceScrollView.GetInstance.SetHorizontalTargetItemIndex(this); } protectedvirtualvoidOnStart() { } protectedvirtualvoidOnAwake() { } protectedvirtualvoidSetItemDepth(floatdepthCurveValue,intdepthFactor,floatitemCount) { } //Settheitemcenterstate publicvirtualvoidSetSelectState(boolisCenter) { } }

EnhanceScrollView.cs

usingUnityEngine; usingSystem.Collections; usingSystem.Collections.Generic; publicclassEnhanceScrollView:MonoBehaviour { publicenumInputSystemType { NGUIAndWorldInput,//useEnhanceScrollViewDragController.cstogettheinput(keyboardandtouch) UGUIInput,//useUDragEnhanceViewforeachitemtogetdragevent } //Inputsystemtype(NGUIor3dworld,UGUI) publicInputSystemTypeinputType=InputSystemType.NGUIAndWorldInput; //Controltheitem'sscalecurve publicAnimationCurvescaleCurve; //Controlthepositioncurve publicAnimationCurvepositionCurve; //Controlthe"depth"'scurve(In3dversionjusttheZvalue,in2DUIyoucanusethedepth(NGUI)) //NOTE: //1.InNGUIsetthewidget'sdepthmaycauseperformanceproblem //2.Ifyouuse3DUIjustsettheItem'sZposition publicAnimationCurvedepthCurve=newAnimationCurve(newKeyframe(0,0),newKeyframe(0.5f,1),newKeyframe(1,0)); //Thestartcenterindex [Tooltip("TheStartcenterindex")] publicintstartCenterIndex=0; //Offsetwidthbetweenitem publicfloatcellWidth=10f; privatefloattotalHorizontalWidth=500.0f; //verticalfixedpositionvalue publicfloatyFixedPositionValue=46.0f; //Lerpduration publicfloatlerpDuration=0.2f; privatefloatmCurrentDuration=0.0f; privateintmCenterIndex=0; publicboolenableLerpTween=true; //centerandpreCentereditem privateEnhanceItemcurCenterItem; privateEnhanceItempreCenterItem; //ifwecanchangethetargetitem privateboolcanChangeItem=true; privatefloatdFactor=0.2f; //originHorizontalValueLerptohorizontalTargetValue privatefloatoriginHorizontalValue=0.1f; publicfloatcurHorizontalValue=0.5f; //"depth"factor(2dwidgetdepthor3dZvalue) privateintdepthFactor=5; //Dragenhancescrollview [Tooltip("Camerafordragraycast")] publicCamerasourceCamera; privateEnhanceScrollViewDragControllerdragController; publicvoidEnableDrag(boolisEnabled) { if(isEnabled) { if(inputType==InputSystemType.NGUIAndWorldInput) { if(sourceCamera==null) { Debug.LogError("##SourceCamerafordragscrollviewisnull##"); return; } if(dragController==null) dragController=gameObject.AddComponent<EnhanceScrollViewDragController>(); dragController.enabled=true; //setthecameraandmask dragController.SetTargetCameraAndMask(sourceCamera,(1<<LayerMask.NameToLayer("UI"))); } } else { if(dragController!=null) dragController.enabled=false; } } //targetsenhanceiteminscrollview publicList<EnhanceItem>listEnhanceItems; //sorttogetrightindex privateList<EnhanceItem>listSortedItems=newList<EnhanceItem>(); privatestaticEnhanceScrollViewinstance; publicstaticEnhanceScrollViewGetInstance { get{returninstance;} } voidAwake() { instance=this; } voidStart() { canChangeItem=true; intcount=listEnhanceItems.Count; dFactor=(Mathf.RoundToInt((1f/count)*10000f))*0.0001f; mCenterIndex=count/2; if(count%2==0) mCenterIndex=count/2-1; intindex=0; for(inti=count-1;i>=0;i--) { listEnhanceItems[i].CurveOffSetIndex=i; listEnhanceItems[i].CenterOffSet=dFactor*(mCenterIndex-index); listEnhanceItems[i].SetSelectState(false); GameObjectobj=listEnhanceItems[i].gameObject; if(inputType==InputSystemType.NGUIAndWorldInput) { DragEnhanceViewscript=obj.GetComponent<DragEnhanceView>(); if(script!=null) script.SetScrollView(this); } else { UDragEnhanceViewscript=obj.GetComponent<UDragEnhanceView>(); if(script!=null) script.SetScrollView(this); } index++; } //setthecenteritemwithstartCenterIndex if(startCenterIndex<0||startCenterIndex>=count) { Debug.LogError("##startCenterIndex<0||startCenterIndex>=listEnhanceItems.Countoutofindex##"); startCenterIndex=mCenterIndex; } //sorteditems listSortedItems=newList<EnhanceItem>(listEnhanceItems.ToArray()); totalHorizontalWidth=cellWidth*count; curCenterItem=listEnhanceItems[startCenterIndex]; curHorizontalValue=0.5f-curCenterItem.CenterOffSet; LerpTweenToTarget(0f,curHorizontalValue,false); // //enablethedragactions // EnableDrag(true); } privatevoidLerpTweenToTarget(floatoriginValue,floattargetValue,boolneedTween=false) { if(!needTween) { SortEnhanceItem(); originHorizontalValue=targetValue; UpdateEnhanceScrollView(targetValue); this.OnTweenOver(); } else { originHorizontalValue=originValue; curHorizontalValue=targetValue; mCurrentDuration=0.0f; } enableLerpTween=needTween; } publicvoidDisableLerpTween() { this.enableLerpTween=false; } /// ///UpdateEnhanceItemstatewithcurvefTimevalue /// publicvoidUpdateEnhanceScrollView(floatfValue) { for(inti=0;i<listEnhanceItems.Count;i++) { EnhanceItemitemScript=listEnhanceItems[i]; floatxValue=GetXPosValue(fValue,itemScript.CenterOffSet); floatscaleValue=GetScaleValue(fValue,itemScript.CenterOffSet); floatdepthCurveValue=depthCurve.Evaluate(fValue+itemScript.CenterOffSet); itemScript.UpdateScrollViewItems(xValue,depthCurveValue,depthFactor,listEnhanceItems.Count,yFixedPositionValue,scaleValue); } } voidUpdate() { if(enableLerpTween) TweenViewToTarget(); } privatevoidTweenViewToTarget() { mCurrentDuration+=Time.deltaTime; if(mCurrentDuration>lerpDuration) mCurrentDuration=lerpDuration; floatpercent=mCurrentDuration/lerpDuration; floatvalue=Mathf.Lerp(originHorizontalValue,curHorizontalValue,percent); UpdateEnhanceScrollView(value); if(mCurrentDuration>=lerpDuration) { canChangeItem=true; enableLerpTween=false; OnTweenOver(); } } privatevoidOnTweenOver() { if(preCenterItem!=null) preCenterItem.SetSelectState(false); if(curCenterItem!=null) curCenterItem.SetSelectState(true); } //Gettheevaluatevaluetosetitem'sscale privatefloatGetScaleValue(floatsliderValue,floatadded) { floatscaleValue=scaleCurve.Evaluate(sliderValue+added); returnscaleValue; } //GettheXvaluesettheItem'sposition privatefloatGetXPosValue(floatsliderValue,floatadded) { floatevaluateValue=positionCurve.Evaluate(sliderValue+added)*totalHorizontalWidth; returnevaluateValue; } privateintGetMoveCurveFactorCount(EnhanceItempreCenterItem,EnhanceItemnewCenterItem) { SortEnhanceItem(); intfactorCount=Mathf.Abs(newCenterItem.RealIndex)-Mathf.Abs(preCenterItem.RealIndex); returnMathf.Abs(factorCount); } //sortitemwithXsowecanknowhowmuchdistanceweneedtomovethetimeLine(curvetimeline) staticpublicintSortPosition(EnhanceItema,EnhanceItemb){returna.transform.localPosition.x.CompareTo(b.transform.localPosition.x);} privatevoidSortEnhanceItem() { listSortedItems.Sort(SortPosition); for(inti=listSortedItems.Count-1;i>=0;i--) listSortedItems[i].RealIndex=i; } publicvoidSetHorizontalTargetItemIndex(EnhanceItemselectItem) { if(!canChangeItem) return; if(curCenterItem==selectItem) return; canChangeItem=false; preCenterItem=curCenterItem; curCenterItem=selectItem; //calculatethedirectionofmoving floatcenterXValue=positionCurve.Evaluate(0.5f)*totalHorizontalWidth; boolisRight=false; if(selectItem.transform.localPosition.x>centerXValue) isRight=true; //calculatetheoffset*dFactor intmoveIndexCount=GetMoveCurveFactorCount(preCenterItem,selectItem); floatdvalue=0.0f; if(isRight) { dvalue=-dFactor*moveIndexCount; } else { dvalue=dFactor*moveIndexCount; } floatoriginValue=curHorizontalValue; LerpTweenToTarget(originValue,curHorizontalValue+dvalue,true); } //Clicktherightbuttontoselectthenextitem. publicvoidOnBtnRightClick() { if(!canChangeItem) return; inttargetIndex=curCenterItem.CurveOffSetIndex+1; if(targetIndex>listEnhanceItems.Count-1) targetIndex=0; SetHorizontalTargetItemIndex(listEnhanceItems[targetIndex]); } //Clicktheleftbuttontheselectnextnextitem. publicvoidOnBtnLeftClick() { if(!canChangeItem) return; inttargetIndex=curCenterItem.CurveOffSetIndex-1; if(targetIndex<0) targetIndex=listEnhanceItems.Count-1; SetHorizontalTargetItemIndex(listEnhanceItems[targetIndex]); } publicfloatfactor=0.001f; //OnDragMove publicvoidOnDragEnhanceViewMove(Vector2delta) { //Indeveloping if(Mathf.Abs(delta.x)>0.0f) { curHorizontalValue+=delta.x*factor; LerpTweenToTarget(0.0f,curHorizontalValue,false); } } //OnDragEnd publicvoidOnDragEnhanceViewEnd() { //findcloseditemtobecentered intclosestIndex=0; floatvalue=(curHorizontalValue-(int)curHorizontalValue); floatmin=float.MaxValue; floattmp=0.5f*(curHorizontalValue<0?-1:1); for(inti=0;i<listEnhanceItems.Count;i++) { floatdis=Mathf.Abs(Mathf.Abs(value)-Mathf.Abs((tmp-listEnhanceItems[i].CenterOffSet))); if(dis<min) { closestIndex=i; min=dis; } } originHorizontalValue=curHorizontalValue; floattarget=((int)curHorizontalValue+(tmp-listEnhanceItems[closestIndex].CenterOffSet)); preCenterItem=curCenterItem; curCenterItem=listEnhanceItems[closestIndex]; LerpTweenToTarget(originHorizontalValue,target,true); canChangeItem=false; } }

NGUIEnhanceItem.cs

usingUnityEngine; usingSystem.Collections; ///<summary> ///NGUIEnhanceitemexample ///</summary> publicclassNGUIEnhanceItem:EnhanceItem { privateUITexturemTexture; protectedoverridevoidOnAwake() { this.mTexture=GetComponent<UITexture>(); UIEventListener.Get(this.gameObject).onClick=OnClickNGUIItem; } privatevoidOnClickNGUIItem(GameObjectobj) { this.OnClickEnhanceItem(); } //Settheitem"depth"2dor3d protectedoverridevoidSetItemDepth(floatdepthCurveValue,intdepthFactor,floatitemCount) { if(mTexture.depth!=(int)Mathf.Abs(depthCurveValue*depthFactor)) mTexture.depth=(int)Mathf.Abs(depthCurveValue*depthFactor); } //Itemiscentered publicoverridevoidSetSelectState(boolisCenter) { if(mTexture==null) mTexture=this.GetComponent<UITexture>(); if(mTexture!=null) mTexture.color=isCenter?Color.white:Color.gray; } protectedoverridevoidOnClickEnhanceItem() { //itemwasclicked base.OnClickEnhanceItem(); } }

UGUIEnhanceItem.cs

usingUnityEngine; usingSystem.Collections; usingUnityEngine.UI; usingUnityEngine.EventSystems; publicclassUGUIEnhanceItem:EnhanceItem { privateButtonuButton; privateImageimage; protectedoverridevoidOnStart() { image=GetComponent<Image>(); uButton=GetComponent<Button>(); uButton.onClick.AddListener(OnClickUGUIButton); } privatevoidOnClickUGUIButton() { OnClickEnhanceItem(); } //Settheitem"depth"2dor3d protectedoverridevoidSetItemDepth(floatdepthCurveValue,intdepthFactor,floatitemCount) { intnewDepth=(int)(depthCurveValue*itemCount); this.transform.SetSiblingIndex(newDepth); } publicoverridevoidSetSelectState(boolisCenter) { if(image==null) image=GetComponent<Image>(); image.color=isCenter?Color.white:Color.gray; } }

导入上述就是C#学习教程:Unity实现游戏卡牌滚动效果分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/908371.html

(0)
上一篇 2021年10月25日
下一篇 2021年10月25日

精彩推荐