实现效果:
实现:
使用NGUI添加虚拟摇杆背景和其子物体按钮,为按钮Attach boxcollider和ButtionScript。为按钮添加如下脚本:
注意:其中的静态属性可以在控制物体移动的代码中访问用于控制。
using UnityEngine;
using System.Collections; public class joyStickControl : MonoBehaviour { public static float h=;
public static float v = ; private float parentHeight;
private float parentWidth; private bool isPress=false; UISprite parentSpirite; void Awake()
{
parentSpirite = transform.parent.GetComponent<UISprite>();
parentWidth = parentSpirite.width;
parentHeight = parentSpirite.height;
} // Update is called once per frame
void Update () { if (isPress)
{
Vector2 touchpos = UICamera.lastTouchPosition; touchpos -=new Vector2(parentWidth / , parentHeight / );
float distance = Vector2.Distance(touchpos, Vector2.zero);
if(distance<)
{
transform.localPosition = touchpos;
}
else
{
transform.localPosition = touchpos.normalized * ;
} h = transform.localPosition.x / ;
v = transform.localPosition.y / ; }
else
{
transform.localPosition = Vector2.zero;
h = ;
v = ;
} } void OnPress(bool isPress)
{
this.isPress = isPress;
}
}
控制物体移动的代码:
注意:在使用虚拟摇杆的时候则忽略键盘控制的移动操作。
using UnityEngine;
using System.Collections; public class MoveCtroller : MonoBehaviour { private float speed = ;
// Use this for initialization
void Start () {
} // Update is called once per frame
void Update () {
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical"); if (joyStickControl.h!=||joyStickControl.v!=)
{
h = joyStickControl.h;
v = joyStickControl.v;
} if (Mathf.Abs(h)>0.3||Mathf.Abs(v)>0.3)
{
GetComponent<CharacterController>().SimpleMove(new Vector3(h * speed, , v * speed));
} }
}
注意:
normalized的属性获取当前向量的方向向量,在这里
transform.localPosition = touchpos.normalized * 53;
用于使按钮保持在虚拟摇杆背景圆的范围类。
touchpos -=new Vector2(parentWidth / 2, parentHeight / 2);则是为了将触点位置与中心按钮的localpositon相一致。
Easy Touch 这个插件想必很多人都有所耳闻,可以迅速实现触摸操作。很适合移动端游戏的触摸输入控制,支持触摸,点击,拖拽,两指缩放。想要节省移动端游戏输入开发的时间可以下载使用