Unity3D 移动摇杆处理

时间:2020-12-02 22:45:02
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using System;
public class JoyStickController : MonoBehaviour,IDragHandler,IEndDragHandler,IBeginDragHandler{ public float maxDragDistance = 50f;
public Vector3 direction;
public Vector3 initPos;
public Vector3 dragPos;
// Use this for initialization
private static JoyStickController _instance; public static JoyStickController instance
{
get
{
return _instance;
}
}
public Vector3 GetDirction()
{
return direction.normalized;
}
void Awake()
{
_instance = this;
}
void Start () {
initPos = transform.position;
Debug.Log(initPos);
} // Update is called once per frame
void Update () { } public void OnBeginDrag(PointerEventData eventData)
{
//Debug.Log(Input.mousePosition);
dragPos = Input.mousePosition;
Debug.Log("OnBeginDrag");
} public void OnDrag(PointerEventData eventData)
{
float dis = Vector3.Distance(dragPos, Input.mousePosition);
direction = Input.mousePosition - dragPos;
if(dis>=maxDragDistance)
{ dis = maxDragDistance; }
transform.localPosition = direction.normalized * dis; Debug.Log("OnDrag"); }
public void OnEndDrag(PointerEventData eventData)
{
this.transform.position = initPos;
direction = Vector3.zero; Debug.Log("OnEndDrag");
Debug.Log(transform.position); }
}

移动处理

using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class HatControl : MonoBehaviour
{
public GameObject effect;
public float fMoveSpeed = 5.0f;
private Vector3 rawPosition;
private Vector3 hatPosition;
private float fMaxWidth; private Vector3 deltaPos;
// Start is called before the first frame update
void Start()
{
Vector3 sceenPos = new Vector3(Screen.width, 0, 0);
Vector3 moveWidth = Camera.main.ScreenToWorldPoint(sceenPos);
float fBallWidth = GetComponent<Renderer>().bounds.extents.x; fMaxWidth = moveWidth.x - fBallWidth; deltaPos = Camera.main.transform.position - transform.position;
} private void Update()
{
Vector3 headPos = gameObject.transform.localPosition;
Vector3 normal = JoyStickController.instance.GetDirction(); float tickTime = Time.deltaTime * fMoveSpeed;
gameObject.transform.localPosition = new Vector3(headPos.x + normal.x * tickTime, headPos.y + normal.y * tickTime, headPos.z); Camera.main.transform.position = transform.position + deltaPos;
} private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.CompareTag("ball"))
{
GameObject newEffect = Instantiate(effect, transform.position, transform.rotation);
newEffect.transform.parent = transform; Destroy(newEffect, 1.0f);
Destroy(collision.gameObject);
} }
}

demo下载地址:

链接:https://pan.baidu.com/s/1sQBm2dPJLEUFB5A5zWPQ2A  密码:3jcg