Skip to content

Instantly share code, notes, and snippets.

@takashi1975
Created May 5, 2018 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takashi1975/9e599c05f5ee6e7959b74c04956107ec to your computer and use it in GitHub Desktop.
Save takashi1975/9e599c05f5ee6e7959b74c04956107ec to your computer and use it in GitHub Desktop.
[Unity] RayCast
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallTap : MonoBehaviour, TapBehaviour {
/** タッチしたとき */
public void TapDown(ref RaycastHit hit) {
Debug.Log("TapDown : " + hit);
}
/** 指(マウス)を離したとき */
public void TapUp(ref RaycastHit hit) {
Debug.Log("TapUp : " + hit);
}
}
using UnityEngine;
/**
* UnityでButton的な何かを作る
* https://qiita.com/JunSuzukiJapan/items/7d129f4af223d778bdb6
*/
interface TapBehaviour {
/** タッチしたとき */
void TapDown(ref RaycastHit hit);
/** 指(マウス)を離したとき */
void TapUp(ref RaycastHit hit);
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Unityで画面をタップした時のRayの撃ち方を考えてみた
* https://qiita.com/JunSuzukiJapan/items/1698a21323558e246c4f
*/
public class TouchHandler : MonoBehaviour {
[SerializeField, Tooltip("Rayの届く距離")]
private float distance = 10f;
private void Update() {
if (Input.GetMouseButtonDown(0))
{
// 画面をタッチしたとき
this.raycast((target, hit) => { target.TapDown(ref hit); });
}
else if (Input.GetMouseButtonUp(0)) {
// 画面から指を離したとき
this.raycast((target, hit) => { target.TapUp(ref hit); });
}
}
/**
* メインカメラからクリックした地点を通って、
* クリックした地点の延長線上にあるゲームオブジェクトを探す
*/
private void raycast(System.Action<TapBehaviour, RaycastHit> action) {
this.raycast(Camera.main, Input.mousePosition, this.distance, action);
}
private void raycast(Vector3 position, System.Action<TapBehaviour, RaycastHit> action) {
this.raycast(Camera.main, position, this.distance, action);
}
/**
* 指定したカメラから指定地点を通って、指定した地点からの距離までの延長線上にあるゲームオブジェクトを探す
*/
private void raycast(Camera camera, Vector3 position, float distance, System.Action<TapBehaviour, RaycastHit> action) {
/**
* ScreenPointToRay ... 点をピクセル座標を必要とする
* ViewportPointToRay ... 正規化された座標を 0..1 の範囲
* https://docs.unity3d.com/ja/530/Manual/CameraRays.html
*/
var ray = camera.ScreenPointToRay(position);
var hit = new RaycastHit();
if (Physics.Raycast(ray, out hit, distance)) {
var hitGameObj = hit.collider.gameObject;
var target = hitGameObj.GetComponent<TapBehaviour>();
if (target != null) {
action(target, hit);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment