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