在游戏中,虚拟摇杆是很常见的,这里我主要是制作第一人称的虚拟摇杆,第三人称的实现原理也是类似的。废话不说,直接说实现方式。
最终效果图如下:
实现方式分为3步:
1:在canvas下创建一个空的子物体,名称为yangan或者你想要的其他名字,这里为yaogan。给子物体添加image组件,添加的方式是Component->UI->Image,给image组件绑定一个图片作为摇杆的背景图片。
2:创建一个Image物体,给image绑定一个图片做为摇杆的滑块,然后拖动Image物体到yaogan下作为摇杆的子物体。
3:代码的创建:
脚本1:挂到刚才创建的yaogan上,实现拖动事件和得到拖动偏移量。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class yaogan : ScrollRect
{
public static bool ifmove=false;//目标是否移动
protected float mRadius = 0f;
float[] message = new float[2];
private object endControl;
protected override void Start()
{
base.Start();
//计算摇杆块的半径
mRadius = (transform as RectTransform).sizeDelta.x * 0.5f;
}
//复写OnDrag方法
public override void OnDrag(UnityEngine.EventSystems.PointerEventData eventData)
{
base.OnDrag(eventData);
var contentPostion = this.content.anchoredPosition;
if (contentPostion.magnitude > mRadius)
{
contentPostion = contentPostion.normalized * mRadius;
SetContentAnchoredPosition(contentPostion);
message[0] = contentPostion.x / contentPostion.magnitude;
message[1] = contentPostion.y / contentPostion.magnitude;
ifmove = true;
GameObject.FindWithTag("MainCamera").SendMessage("GetValue",message);//这里我控制相机,所以给相机发送消息
// Debug.Log(contentPostion.x/ contentPostion.magnitude+" Y"+ contentPostion.y / contentPostion.magnitude);
}
}
//复写OnEndDrag方法
public override void OnEndDrag(PointerEventData eventData)
{
base.OnEndDrag(eventData);
ifmove = false;
}
}
脚本2:挂到要控制的物体上,这里我控制的物体是maincamera.maincamera加了CharacterController组件。
using UnityEngine;
using UnityEngine.EventSystems;
public class shijiao : MonoBehaviour
{
public GameObject Cm;
//方向灵敏度
public float sensitivityX = 10F;
public float sensitivityY = 10F;
//上下最大视角(Y视角)
public float minimumY = -60F;
public float maximumY = 60F;
float rotationY = 0F;
private float movespeed = 20;
CharacterController ctrlor;
float[] mesgs = new float[2];
void Start ()
{
ctrlor = GetComponent<CharacterController>();
}
void Update()
{
if (yaogan.ifmove)
{
Cm.transform.LookAt(new Vector3(Cm.transform.position.x+mesgs[0], Cm.transform.position.y,Cm.transform.position.z+mesgs[1]));
ctrlor.Move(new Vector3(mesgs[0] * movespeed * Time.deltaTime, 0, mesgs[1] * movespeed * Time.deltaTime));
}
}
void GetValue(float[] mesg)
{
Debug.Log(mesg[0]);
mesgs = mesg;
}
}