//Canvas内の動かしたいobjectにattach
//EventTriggerの設定
//OnBeginDrag
//OnDrag
//OnEndDrag
//JumpPos
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(CanvasGroup))]
public class DragObj : MonoBehaviour
{
private Transform root;
private Transform self;
private CanvasGroup canvasGroup = null;
public Rigidbody2D rb;
// public Transform firePoint;
public GameObject bulletPrefab;
public void Awake()
{
this.self = this.transform;
this.root = this.self.parent;
this.canvasGroup = this.GetComponent();
}
public void OnBeginDrag(BaseEventData eventData)
{
// UI 機能を一時的無効化
this.canvasGroup.blocksRaycasts = false;
}
public void OnDrag(BaseEventData eventData)
{
this.self.localPosition = GetLocalPosition(((PointerEventData)eventData).position, this.transform);
}
private static Vector3 GetLocalPosition(Vector3 position, Transform transform)
{
// 画面上の座標 (Screen Point) を RectTransform 上のローカル座標に変換
RectTransformUtility.ScreenPointToLocalPointInRectangle(
transform.parent.GetComponent(),
position,
Camera.main,
out var result);
return new Vector3(result.x, -480f, 0);
// return new Vector3(result.x, result.y, 0);
}
public void OnEndDrag(BaseEventData eventData)
{
// UI 機能を復元
this.canvasGroup.blocksRaycasts = true;
}
public void JumpPos()
{
if (rb.velocity.y == 0)
{
// rb.AddForce(new Vector2(0, 8), ForceMode2D.Impulse);
Instantiate(bulletPrefab, transform.position, Quaternion.identity);
}
}
}