Unity屏幕滑杆
滑杆代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class TuoUI : MonoBehaviour,IDragHandler,IEndDragHandler
{
public Vector3 dir;
Vector3 yuandian;
RectTransform recttras;
RectTransform rects;
public float a;
public float b;
public Animator ani;
// Use this for initialization
void Start ()
{
recttras = transform as RectTransform;
yuandian = transform.position;
rects=transform.parent as RectTransform;
}
// Update is called once per frame
public Vector3 worldpos;
public void OnDrag (PointerEventData eventData)
{
ani.SetFloat ("runs", 1);
RectTransformUtility.ScreenPointToWorldPointInRectangle (recttras, Input.mousePosition, eventData.pressEventCamera, out worldpos);
transform.position = worldpos;
dir = transform.localPosition-Vector3.zero;
if(Vector2.Distance(Input.mousePosition,yuandian)>rects.rect.width/2)
{
transform.localPosition = Vector3.zero + dir.normalized * rects.rect.width / 2;
}
}
public void OnEndDrag (PointerEventData eventData)
{
transform.localPosition = Vector3.zero;
dir = transform.localPosition-Vector3.zero;
ani.SetFloat ("runs", 0);
}
void Update ()
{
a = dir.x / rects.rect.width / 2;
b = dir.z / rects.rect.height / 2;
}
角色脚本:
public class NinjaMove : MonoBehaviour {
float h;
float v;
public float movespeed;
//public float rotspeed;
public TuoUI yaogan;
Vector3 a;
void Start ()
{
}
void Update ()
{
a = new Vector3 (yaogan.dir.normalized.x, 0, yaogan.dir.normalized.y);
if(a.x != 0 || a.z != 0)
{
transform.rotation = Quaternion.LookRotation (a);
transform.Translate(Vector3.forward* movespeed * Time.deltaTime);
}
}
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!