Skip to content

Instantly share code, notes, and snippets.

@tubakihimeLoveHate
Created November 4, 2019 12:52
Show Gist options
  • Save tubakihimeLoveHate/02c108b23a3b28b99394392d912587dc to your computer and use it in GitHub Desktop.
Save tubakihimeLoveHate/02c108b23a3b28b99394392d912587dc to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ControllerUI : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler{
[SerializeField]
float speed = 3f;
//歩行時=1,走行時=2
float pulusSpeed=1;
Vector2 startPosition;
Vector2 endPosition;
[SerializeField]//コントローラーが動ける範囲
float radius=50;
bool isMove = false;
[SerializeField]//動かしたいオブジェクトを選択
Transform charactor;
[SerializeField]
Animator animator;
//コントローラーを動かした距離
float distance;
//ラジアン
private float deg = 0;
//回転間隔
float deltaTime = 0.1f;
void Start(){}
void Update(){
if(isMove){
Vector3 velocity = new Vector3(0, 0, 1);
// キャラクターのローカル空間での方向に変換
velocity = charactor.TransformDirection(velocity);
float speedCache = speed *pulusSpeed* Time.deltaTime;
// キャラクターの移動
charactor.localPosition += velocity * speedCache;
//アニメーション
animator.SetBool("walking",true);
}else{
animator.SetBool("walking",false);
}
}
// ドラックが開始したとき
public void OnBeginDrag(PointerEventData eventData){
startPosition = transform.position;
isMove = true;
}
// ドラック中
public void OnDrag(PointerEventData eventData){
//コントローラーを円から出さない用制御+speed調節
distance = Vector2.Distance(startPosition,eventData.position);
if(distance<radius)transform.position = eventData.position;
else distance=radius;
     //角度算出
deg = GetAngle(startPosition,eventData.position);
//方向変換
charactor.eulerAngles = new Vector3(0,deg,0);
}
// ドラックが終了したとき
public void OnEndDrag(PointerEventData eventData){
transform.localPosition = new Vector2(0,0);
distance =0;
isMove = false;
}
float GetAngle(Vector2 start,Vector2 target){
Vector2 dt = target - start;
float rad = Mathf.Atan2 (dt.x, dt.y);
float degree = rad * Mathf.Rad2Deg;
if (degree < 0)degree += 360;
return degree;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment