Unity_虛擬搖桿的實現_065
阿新 • • 發佈:2019-02-17
設定搖桿的背景圖片的錨點如下:
設定搖桿的錨點為背景圖片的中心點。
並給搖桿繫結指令碼如下:
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分量
//設定玩家的朝向
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;
}
}
//拖拽結束的時候
public void OnEndDrag(PointerEventData eventData)
{
this.transform.localPosition = Vector3.zero;
}
}