使用Unity怎么实现一个虚拟键盘功能
作者
使用Unity怎么实现一个虚拟键盘功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
具体内容如下
usingUnityEngine; usingSystem.Collections.Generic; publicenumShiftState{Off,Shift,CapsLock} publicclassOnScreenKeyboard:MonoBehaviour{ //INSPECTORVISIBLEPROPERTIES------------------------------------------- //Skinning publicGUIStyleboardStyle; publicGUIStylekeyStyle; publicTexture2DselectionImage; //Boardandbuttonsizes publicRectscreenRect=newRect(0,0,0,0); publicVector2stdKeySize=newVector2(32,32); publicVector2lgeKeySize=newVector2(64,32); //Keyaudio publicAudioClipkeySelectSound=null; publicAudioClipkeyPressSound=null; //Shiftsettings publicboolshiftStateSwitchEnabled=true; publicShiftStateshiftStateDefault=ShiftState.Off; //Joysticksettings publicbooljoystickEnabled=true; publicstringjoyPressButton="Fire1"; publicstringjoyCapsButton="Fire2"; //Ourkeys.Bydefaultwe'llincludeasimplifiedQWERTYkeyboardhandy //fornameentry,butthiscanliterallybeanythingyouwant.Eitherthe //twoarraysmustbeofmatchinglength,orlowerKeysmustbeofsize0. publicstring[]upperKeys={"Q","W","E","R","T","Y","U","I","O","P","<<","<row>", "A","S","D","F","G","H","J","K","L","Done","<row>", "Z","X","C","V","B","N","M","Caps","Space"}; publicstring[]lowerKeys={"q","w","e","r","t","y","u","i","o","p","<<","<row>", "a","s","d","f","g","h","j","k","l","Done","<row>", "z","x","c","v","b","n","m","Caps","Space"}; //Thesizemustmatchthenumberofrows,orbe0 publicfloat[]rowIndents={0.0f,0.2f,0.5f}; //Delaysforrepeatedevents publicfloatinitialRepeatDelay=0.8f; publicfloatcontinuedRepeatDelay=0.2f; publicfloatmoveRepeatDelay=0.3f; //INTERNALDATAMEMBERS-------------------------------------------------- privatestringkeyPressed=""; privateintpSelectedButton; privateGUIStylepressedStyle=null; privatefloatkeyRepeatTimer=0; privateboolkeyDownPrevFrame=false; privateboolkeyReleased=false; privateboollastKeyWasShift=false; privatefloatmoveTimer=0; privateShiftStateshiftState; privatebool[]keySizes; privateRect[]keyRects; privateint[]rowMarkers; privateintselectedButton; privateAudioSourcekeySelectSource=null; privateAudioSourcekeyPressSource=null; //Changethisifit'sconflictingwithyourownGUI'swindows privateintwindowId=0; ///<summary> ///新增属性,控制虚拟键盘在屏幕中的位置 ///</summary> [Header("June_Add_Attribute_Control_keyBoardTF---------------------------------------")] publicfloat_keyBoardTF_X; publicfloat_keyBoardTF_Y; //INITIALISATION--------------------------------------------------------- voidAwake() { //Checkthatourkeyarraysizesmatch if(upperKeys.Length!=lowerKeys.Length&&!(lowerKeys.Length==0&&!shiftStateSwitchEnabled)) { print("Error:OnScreenKeyboardneedsthesamenumberofupperandlowercasekeys,ortheremustbenolowerkeysandcapsswitchmustbedisabled"); Destroy(this); } //Checkforrowmarkersandcountrowlengths List<int>rowMarkersTemp=newList<int>(); for(inti=0;i<upperKeys.Length;i++) if(upperKeys[i]=="<row>")rowMarkersTemp.Add(i); rowMarkers=rowMarkersTemp.ToArray(); //Checkrowindents if(rowIndents.Length<rowMarkers.Length+1) { float[]rowIndentsTemp=newfloat[rowMarkers.Length+1]; for(inti=0;i<rowIndentsTemp.Length;i++) { if(i<rowIndents.Length)rowIndentsTemp[i]=rowIndents[i]; elserowIndentsTemp[i]=0; } } //Checkbuttonsizes-anythingthat'snotasinglecharacterisa"large"key keySizes=newbool[upperKeys.Length]; for(inti=0;i<upperKeys.Length;i++)keySizes[i]=upperKeys[i].Length>1; //Populatethearrayofkeyrectangles keyRects=newRect[upperKeys.Length]; intcurrentRow=0; floatxPos=(rowIndents.Length>0?rowIndents[currentRow]:0)+stdKeySize.x*0.33f; floatyPos=stdKeySize.y*1.33f*currentRow+stdKeySize.y*0.33f; for(inti=0;i<upperKeys.Length;i++) { //Onthestartofanewline,positionthenewkeyaccordingly if(IsRowMarker(i)) { if(i!=0)currentRow++; xPos=(rowIndents.Length>0?rowIndents[currentRow]:0)+stdKeySize.x*0.33f; yPos=stdKeySize.y*1.33f*currentRow+stdKeySize.y*0.33f; } else { //Drawthekey,andsetkeyPressedaccordingly keyRects[i]=newRect(screenRect.x+xPos,screenRect.y+yPos,keySizes[i]?lgeKeySize.x:stdKeySize.x,keySizes[i]?lgeKeySize.y:stdKeySize.y); //Moveovertothenextkey'spositiononthisline xPos+=keySizes[i]?lgeKeySize.x+stdKeySize.x*0.33f:stdKeySize.x*1.33f; } } //Putourselvesinadefaultscreenpositionifwehaven'tbeenexplicitlyplacedyet if(screenRect.x==0&&screenRect.y==0&&screenRect.width==0&&screenRect.height==0) { //Figureouthowbigweneedtobe floatmaxWidth=0; floatmaxHeight=0; for(inti=0;i<keyRects.Length;i++) { if(keyRects[i].xMax>maxWidth)maxWidth=keyRects[i].xMax; if(keyRects[i].yMax>maxHeight)maxHeight=keyRects[i].yMax; } maxWidth+=stdKeySize.x*0.33f; maxHeight+=stdKeySize.y*0.33f; screenRect=newRect(_keyBoardTF_X,_keyBoardTF_Y,maxWidth,maxHeight); } //Ifwe'vegotaudio,createsourcessowecanplayit if(keySelectSound!=null) { keySelectSource=gameObject.AddComponent<AudioSource>()asAudioSource; keySelectSource.spatialBlend=0; keySelectSource.clip=keySelectSound; } if(keyPressSound!=null) { keyPressSource=gameObject.AddComponent<AudioSource>()asAudioSource; keyPressSource.spatialBlend=0; keyPressSource.clip=keyPressSound; } //Settheinitialshiftstate if(shiftStateSwitchEnabled)SetShiftState(shiftStateDefault); //Createapressedbuttonskinforjoysticks pressedStyle=newGUIStyle(); pressedStyle.normal.background=keyStyle.active.background; pressedStyle.border=keyStyle.border; pressedStyle.normal.textColor=keyStyle.active.textColor; pressedStyle.alignment=keyStyle.alignment; //新增字体样式------->按钮按下的时候调用 pressedStyle.font=keyStyle.font; } //GAMELOOP-------------------------------------------------------------- voidUpdate() { //Handlekeysbeingreleased if(!keyDownPrevFrame) { keyRepeatTimer=0; if(!keyReleased)KeyReleased(); } keyDownPrevFrame=false; //Checkmouseinput Vector3guiMousePos=Input.mousePosition; guiMousePos.y=Screen.height-guiMousePos.y; for(inti=0;i<keyRects.Length;i++) { RectclickRect=keyRects[i]; clickRect.x+=screenRect.x;clickRect.y+=screenRect.y; //Checkfortheclickourself,becausewewanttodoitdifferentlytousual if(clickRect.Contains(guiMousePos)) { selectedButton=i; if(Input.GetMouseButtonDown(0))KeyPressed(); elseif(Input.GetMouseButton(0))KeyHeld(); elseif(Input.GetMouseButtonUp(0))KeyReleased(); } } //Ifthejoystickisinuse,updateaccordingly if(joystickEnabled)CheckJoystickInput(); } privatevoidCheckJoystickInput() { //KEYSELECTION floathoriz=Input.GetAxis("Horizontal"); floatvert=Input.GetAxis("Vertical"); moveTimer-=Time.deltaTime; if(moveTimer<0)moveTimer=0; boolhadInput=false; boolmoved=false; if(horiz>0.5f) { if(moveTimer<=0) { SelectRight(); moved=true; } hadInput=true; } elseif(horiz<-0.5f) { if(moveTimer<=0) { SelectLeft(); moved=true; } hadInput=true; } if(vert<-0.5f) { if(moveTimer<=0) { SelectDown(); moved=true; } hadInput=true; } elseif(vert>0.5f) { if(moveTimer<=0) { SelectUp(); moved=true; } hadInput=true; } if(!hadInput)moveTimer=0; if(moved) { moveTimer+=moveRepeatDelay; if(keySelectSource!=null)keySelectSource.Play(); } selectedButton=Mathf.Clamp(selectedButton,0,upperKeys.Length-1); //CAPITALS if(shiftStateSwitchEnabled&& (Input.GetKeyDown(KeyCode.LeftShift)|| Input.GetButtonDown(joyCapsButton))) shiftState=(shiftState==ShiftState.CapsLock?ShiftState.Off:ShiftState.CapsLock); //TYPING if(Input.GetButtonDown(joyPressButton))KeyPressed(); elseif(Input.GetButton(joyPressButton))KeyHeld(); } //Calledonthefirstframewhereanewkeyispressed privatevoidKeyPressed() { keyPressed=(shiftState!=ShiftState.Off)?upperKeys[selectedButton]:lowerKeys[selectedButton]; pSelectedButton=selectedButton; keyRepeatTimer=initialRepeatDelay; keyDownPrevFrame=true; keyReleased=false; lastKeyWasShift=false; if(keyPressSource!=null)keyPressSource.Play(); } //CalledforeveryframeAFTERthefirstwhileakeyisbeingheld privatevoidKeyHeld() { //Ifthekeybeingpressedhaschanged,reverttoaninitialpress if(selectedButton!=pSelectedButton) { KeyReleased(); KeyPressed(); return; } //Checkifwe'rereadytoreportanotherpressyet keyRepeatTimer-=Time.deltaTime; if(keyRepeatTimer<0) { keyPressed=(shiftState!=ShiftState.Off)?upperKeys[selectedButton]:lowerKeys[selectedButton]; keyRepeatTimer+=continuedRepeatDelay; if(keyPressSource!=null)keyPressSource.Play(); } keyDownPrevFrame=true; keyReleased=false; } //Calledtheframeafterakeyisreleased privatevoidKeyReleased() { keyDownPrevFrame=false; keyReleased=true; if(shiftState==ShiftState.Shift&&!lastKeyWasShift) SetShiftState(ShiftState.Off); } //Selectsthekeytotheleftofthecurrentlyselectedkey privatevoidSelectLeft() { selectedButton--; //Ifwe'vehitthestartofarow,wraptotheendofitinstead if(IsRowMarker(selectedButton)||selectedButton<0) { selectedButton++; while(!IsRowMarker(selectedButton+1)&&selectedButton+1<upperKeys.Length)selectedButton++; } } //Selectsthekeytotherightofthecurrentlyselectedkey privatevoidSelectRight() { selectedButton++; //Ifwe'vehittheendofarow,wraptothestartofitinstead if(IsRowMarker(selectedButton)||selectedButton>=upperKeys.Length) { selectedButton--; while(!IsRowMarker(selectedButton-1)&&selectedButton-1>=0)selectedButton--; } } //Selectsthekeyabovethecurrentlyselectedkey privatevoidSelectUp() { //Findthecenterofthecurrentlyselectedbutton floatselCenter=keyRects[selectedButton].x+keyRects[selectedButton].width/2; //Findthestartofthenextbutton; inttgtButton=selectedButton; while(!IsRowMarker(tgtButton)&&tgtButton>=0)tgtButton--; if(IsRowMarker(tgtButton))tgtButton--; if(tgtButton<0)tgtButton=upperKeys.Length-1; //Findthebuttonwiththeclosestcenteronthatline floatnDist=float.MaxValue; while(!IsRowMarker(tgtButton)&&tgtButton>=0) { floattgtCenter=keyRects[tgtButton].x+keyRects[tgtButton].width/2; floattDist=Mathf.Abs(tgtCenter-selCenter); if(tDist<nDist) { nDist=tDist; } else { selectedButton=tgtButton+1; return; } tgtButton--; } selectedButton=tgtButton+1; } //Selectsthekeybelowthecurrentlyselectedkey privatevoidSelectDown() { //Findthecenterofthecurrentlyselectedbutton floatselCenter=keyRects[selectedButton].x+keyRects[selectedButton].width/2; //Findthestartofthenextbutton; inttgtButton=selectedButton; while(!IsRowMarker(tgtButton)&&tgtButton<upperKeys.Length)tgtButton++; if(IsRowMarker(tgtButton))tgtButton++; if(tgtButton>=upperKeys.Length)tgtButton=0; //Findthebuttonwiththeclosestcenteronthatline floatnDist=float.MaxValue; while(!IsRowMarker(tgtButton)&&tgtButton<upperKeys.Length) { floattgtCenter=keyRects[tgtButton].x+keyRects[tgtButton].width/2; floattDist=Mathf.Abs(tgtCenter-selCenter); if(tDist<nDist) { nDist=tDist; } else { selectedButton=tgtButton-1; return; } tgtButton++; } selectedButton=tgtButton-1; } //Returnstherownumberofaspecifiedbutton privateintButtonRow(intbuttonIndex) { for(inti=0;i<rowMarkers.Length;i++) if(buttonIndex<rowMarkers[i])returni; returnrowMarkers.Length; } //GUIFUNCTIONALITY------------------------------------------------------ voidOnGUI() { GUI.Window(windowId,screenRect,WindowFunc,"",boardStyle); } privatevoidWindowFunc(intid) { for(inti=0;i<upperKeys.Length;i++) { if(!IsRowMarker(i)) { //Drawaglowbehindtheselectedbutton if(i==selectedButton) GUI.DrawTexture(newRect(keyRects[i].x-5,keyRects[i].y-5,keyRects[i].width+10,keyRects[i].height+10),selectionImage); //Drawthekey //Notethatwedon'tdoclickdetectionhere,wedoitinupdate GUI.Button(keyRects[i],(shiftState!=ShiftState.Off)?upperKeys[i]:lowerKeys[i], (joystickEnabled&&selectedButton==i&&Input.GetButton(joyPressButton)?pressedStyle:keyStyle)); } } } //Returnstrueiftheyitemataspecifiedindexisarowendmarker privateboolIsRowMarker(intcurrentKeyIndex) { for(inti=0;i<rowMarkers.Length;i++)if(rowMarkers[i]==currentKeyIndex)returntrue; returnfalse; } //CONTROLINTERFACE------------------------------------------------------ //Returnsthelatestkeytobepressed,ornullifnonewkeywaspressed //sincelasttimeyouchecked.Thismeansthatyoucanonlygrabasingle //keypressonce,asit'sclearedonceyou'vereadit.Italsomeansthat //ifyoulettheuserpressmultiplekeysbetweenchecksonlythemost //recentonewillbepickedupeachtime. publicstringGetKeyPressed() { if(keyPressed==null)keyPressed=""; stringkey=keyPressed; keyPressed=""; returnkey; } //Togglethecapsstatefromelsewhere publicvoidSetShiftState(ShiftStatenewShiftState) { if(!shiftStateSwitchEnabled)return; shiftState=newShiftState; if(shiftState==ShiftState.Shift)lastKeyWasShift=true; } publicShiftStateGetShiftState(){returnshiftState;} }
usingUnityEngine; usingUnityEngine.UI; ///<summary> ///这是虚拟键盘插件脚本,June于2020.4.16改 ///</summary> publicclassOnScreenKeyboardExample:MonoBehaviour { publicOnScreenKeyboardosk; ///<summary> ///输入文字 ///</summary> privatestring_inputString; ///<summary> ///输入文本框 ///</summary> publicInputField_inputField; //每次激活清空文本框内容 privatevoidOnEnable() { _inputString=""; } voidUpdate() { //YoucanuseinputfromtheOSKjustbyaskingforthemostrecent //pressedkey,whichwillbereturnedtoyouasastring,ornullif //nokeyhasbeenpressedsinceyoulastchecked.Notethatifmore //thanonekeyhasbeenpressedyouwillonlybegiventhemostrecent. stringkeyPressed=osk.GetKeyPressed(); if(keyPressed!="") { //Takedifferentactiondependingonwhatkeywaspressed if(keyPressed=="Backspace"||keyPressed=="<<") { //Removeacharacter if(_inputString.Length>0) _inputString=_inputString.Substring(0,_inputString.Length-1); } elseif(keyPressed=="Space") { //Addaspace _inputString+=""; } elseif(keyPressed=="Enter"||keyPressed=="Done") { //Changescreens,ordowhateveryouwantto //dowhenyouruserhasfinishedtyping:-) } elseif(keyPressed=="Caps") { //Togglethecapslockstateyourself osk.SetShiftState(osk.GetShiftState()==ShiftState.CapsLock?ShiftState.Off:ShiftState.CapsLock); } elseif(keyPressed=="Shift") { //Toggleshiftstateourselves osk.SetShiftState(osk.GetShiftState()==ShiftState.Shift?ShiftState.Off:ShiftState.Shift); } else { //限制输入 if(_inputField.text.Length>=_inputField.characterLimit)return; //Addalettertotheexistingstring _inputString+=keyPressed; } //将文字赋值给文本框中的文本属性 _inputField.text=_inputString; } } }
看完上述内容,你们掌握使用Unity怎么实现一个虚拟键盘功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注恰卡编程网行业资讯频道,感谢各位的阅读!
目录
推荐阅读
-
VS Code里如何使用Debugger for Unity插件调试
-
Unity如何实现射击小游戏
-
Unity如何实现炸弹人游戏
-
Unity中怎么通过LitJson对JSON数据创建与使用
Unity中怎么通过LitJson对JSON数据创建与使用这篇文章...
-
Unity实现动物识别的代码怎么写
-
怎么用Unity命令行打包WebGL
怎么用Unity命令行打包WebGL本文小编为大家详细介绍“怎么用...
-
如何教训unity与3dmax美工部分的总结
如何教训unity与3dmax美工部分的总结今天给大家介绍一下如何...
-
Unity图形学中的ShaderLab怎么入门
-
Unity怎么实现植物识别
-
Unity渲染管线流程是怎样的
0 条评论
本站已关闭游客评论,请登录或者注册后再评论吧~