MarkerLibrary는
https://assetstore.unity.com/packages/3d/characters/animals/toon-fox-183005
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
public class BallController : MonoBehaviour
{
private float resetTime = 3.0f;
private Rigidbody rBody;
private bool isReady = true; // 처음 던져야함
private Vector2 startPos;
public ARTrackedImageManager arTrackedImageManager;
public TMP_Text textResult; // 결과 출력 UI Text
public float captureRate = 0.3f; // 포획 확률 30%
public GameObject effect;
// Start is called before the first frame update
void Start()
{
this.textResult.text = ""; // 초기화
this.rBody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (isReady == false) return;
//공을 카메라 전방 하단에 배치
SetBallPosition(Camera.main.transform);
//터치하고 준비상태라면
if(Input.touchCount > 0 && isReady)
{
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Began)
{
//터치 시작
startPos = touch.position;
}
else if (touch.phase == TouchPhase.Ended)
{
//터치 끝
float distanceY = touch.position.y - startPos.y;
//방향 구하기
Vector3 c = Camera.main.transform.forward + Camera.main.transform.up;
Vector3 dir = c.normalized;
//던지기
rBody.isKinematic = false;
isReady = false;
var force = distanceY * 0.005f;
//던질 방향 * 드래그 거리 만큼 물리적 힘을 가함
rBody.AddForce(dir * force, ForceMode.VelocityChange);
//3초 후 원래 위치로 초기화
Invoke("ResetBall", resetTime);
}
}
}
private void ResetBall()
{
rBody.isKinematic = true;
rBody.velocity = Vector3.zero;
isReady = true;
gameObject.SetActive(true);
//고양이 찾기
foreach(var trackable in arTrackedImageManager.trackables)
{
//Debug.Log(trackable.trackableId);
trackable.gameObject.SetActive(true);
}
//텍스트 결과 초기화
textResult.text = "";
}
private void SetBallPosition(Transform anchor)
{
Vector3 offset = anchor.forward * 0.5f + anchor.up * -0.2f;
transform.position = anchor.position + offset;
}
private void OnCollisionEnter(Collision collision)
{
if (isReady) return; // 던졌을 때 확인을 해야하기 때문에
float draw = Random.Range(0, 1.0f); // 0 ~ 1.0 사이 실수
if(draw <= captureRate)
{
textResult.text = "포획 성공";
}
else
{
textResult.text = "포획에 실패해 도망쳤습니다...";
}
//이펙트 생성
Instantiate(effect, collision.transform.position, Camera.main.transform.rotation);
collision.gameObject.SetActive(false);
//Destroy(collision.gameObject);
gameObject.SetActive(false);
}
}