Unity虛擬搖桿的實現(xiàn)方法
更新時間:2020年04月15日 14:19:09 作者:yy763496668
這篇文章主要為大家詳細介紹了Unity虛擬搖桿的實現(xiàn)方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Unity實現(xiàn)虛擬搖桿的具體代碼,供大家參考,具體內(nèi)容如下
設(shè)置搖桿的背景圖片的錨點如下:

設(shè)置搖桿的錨點為背景圖片的中心點。
并給搖桿綁定腳本如下:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System;
public class JoyStickController : MonoBehaviour,IDragHandler,IEndDragHandler {
//最大的拖動距離
public float maxDragDistance = 50f;
//虛擬搖桿的方向
public Vector3 direction;
//玩家
public GameObject player;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
//屏幕上的y軸分量 當作游戲世界里的z分量
//設(shè)置玩家的朝向
player.transform.forward = new Vector3(direction.x,0,direction.y);
int flag = Vector3.Distance(Vector3.zero, this.transform.localPosition) <1f ? 0 : 1;
player.transform.Translate(Vector3.forward * flag * Time.deltaTime,Space.Self);
}
//拖拽中的時候
public void OnDrag(PointerEventData eventData)
{
this.transform.position = Input.mousePosition;
if (Vector3.Distance(Vector3.zero,this.transform.localPosition) > maxDragDistance)
{
direction = this.transform.position - Vector3.zero;
this.transform.localPosition = direction.normalized * maxDragDistance;
}
}
//拖拽結(jié)束的時候
public void OnEndDrag(PointerEventData eventData)
{
this.transform.localPosition = Vector3.zero;
}
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

