通过另外一种方式实现Player的移动控制:
通过EventSystems实现屏幕上的手指拖拽,实时记录手指移动的距离;
通过MoveTowards 参照手指移动的距离,移动Player;
通过Mathf.Clamp限制屏幕边界,使得Player不会超出屏幕边界;
EventSystems实现
新建ugui的panel,设置全屏;
新建PlayerTouch脚本,拖拽到panel上;
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class PlayerTouch :MonoBehaviour,IPointerUpHandler,IPointerDownHandler,IDragHandler
{
//单例
public static PlayerTouch instance;
//拖拽距离
public Vector2 dragDistance;
//是否触摸屏幕(按下屏幕)
public bool isTouchDown = false;
//按下位置
Vector2 downPosition;
void Start ()
{
instance = this;
}
//触摸离开事件(手指或鼠标离开事件)
public void OnPointerUp (PointerEventData eventData)
{
//Debug.Log ("OnPointerUp");
isTouchDown = false;
PlayerMove.Instance.resetInitPosition ();
dragDistance = Vector2.zero;
}
//触摸按下事件(手指或鼠标按下事件)
public void OnPointerDown (PointerEventData eventData)
{
//Debug.Log ("OnPointerDown");
downPosition = Camera.main.ScreenToWorldPoint (eventData.position);
isTouchDown = true;
}
//拖拽事件
public void OnDrag (PointerEventData eventData)
{
if (isTouchDown) {
//Debug.Log ("OnDrag: " + eventData.position);
Vector3 position = Camera.main.ScreenToWorldPoint (eventData.position);
dragDistance = new Vector2 (position.x, position.y) - downPosition;
}
}
}
PlayerMove实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour {
public static PlayerMove Instance;
//速度
public float speed = 5f;
//刚体
private Rigidbody2D rigidbody;
//0速度
private float velocity_zero = 0;
//初始位置
private Vector2 position_init = Vector2.zero;
void Awake ()
{
//获得刚体并设置速度
rigidbody = GetComponent<Rigidbody2D> ();
//rigidbody.velocity = new Vector2 (velocity_zero, velocity_zero);
}
public void resetInitPosition(){
position_init.x = transform.position.x;
position_init.y = transform.position.y;
Debug.Log ("position_init: "+position_init);
}
void Start(){
Instance = this;
resetInitPosition ();
}
bool isTouch = false;
float h;
float v;
void Update ()
{
onTouchScreen ();
move ();
}
private void move(){
//判断是否触点了屏幕
if(!PlayerTouch.instance.isTouchDown){
return;
}
//获得目标位置
Vector2 target = position_init + PlayerTouch.instance.dragDistance;
//移动到目标位置
transform.position = Vector2.MoveTowards (transform.position, target, 0.1f * speed);
//限制移动范围
transform.position = new Vector2 (
Mathf.Clamp(transform.position.x, AppCommon.getLeft(), AppCommon.getRight()),
Mathf.Clamp(transform.position.y, AppCommon.getBottom(), AppCommon.getTop()));
}
/// <summary>
/// 根据触屏事件,修改app运动参数
/// </summary>
private void onTouchScreen(){
if (Input.touchCount <= 0 && !Input.GetMouseButton(0)) {
AppCommon.app_velocity = 0.05f;
} else {
AppCommon.app_velocity = 1f;
}
}
}