在遊戲中,虛擬搖桿是很常見的,這裏我主要是製作第一人稱的虛擬搖桿,第三人稱的實現原理也是類似的。廢話不說,直接說實現方式。
最終效果圖如下:
實現方式分爲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;
}
}