-
[3D] Raycast 활용하기(Ray, RaycastHit,Instantiate)Unity(유니티) 2022. 4. 22. 14:54
* RaycastHit : raycast로부터 정보를 얻기 위해 사용되는 구조체를 나타냄
* Physics.Raycast : bool 형식으로 어떤 콜라이더와 레이가 충돌했으면 true, 아니면 false
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExampleClass : MonoBehaviour { private void FixedUpdate() { Vector3 fwd = transform.TransformDirection(Vector3.forward); if (Physics.Raycast(transform.position, fwd, 10)) print("There is something in front of the object"); } }
* Instantiate
Object.Instantiate
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExampleClass : MonoBehaviour { public GameObject prefab; private void Start() { for (int i = 0; i < 10; i++) Instantiate(prefab, new Vector3(i * 2.0f, 0, 0), Quaternion.identity); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExampleClass : MonoBehaviour { //Instantiate a prefab with an attached Missile script public Missile missilePrefab; private void Start() { //Instantiate the missile at the position and rotation of this object's transform missilePrefab clone = (Missile)Instantiate(missilePrefab, transform.position, transform.rotation); } }
[MainScript]
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameSystemManager : MonoBehaviour { private Vector3 movePos; //Raycast private Ray ray; private RaycastHit hitInfo; [SerializeField] private GameObject tree; private void Update() { if (Input.GetMouseButtonDown(0)) { CallTargetPos(); } } void CallTargetPos() { ray = Camera.main.ScreenPointToRay(Input.mousePosition); Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 1f); if (Physics.Raycast(ray, out hitInfo)) { movePos = hitInfo.point; //Pond 색 바꾸기 if(hitInfo.transform.tag == "Pond") { hitInfo.transform.GetComponent<MeshRenderer>().material.color = Color.blue; } //Ground에 나무 심기 if(hitInfo.transform.tag == "Ground") { Instantiate(tree, movePos, Quaternion.identity); } //DestroyObj 삭제하기 if(hitInfo.transform.tag == "DestroyObj") { Destroy(hitInfo.transform.gameObject); } } } }
'Unity(유니티)' 카테고리의 다른 글
[3D] 마이크 기능 구현(음성 채팅) (0) 2022.05.04 [3D] WebCam 구현 (0) 2022.05.04 [JohnLemon 3D] 첫 번째 스크립트 작성하기(void Start) (0) 2022.04.20 [3D] 코루틴 사용하기 (0) 2022.04.20 [3D] 오브젝트 이동구현 및 애니메이션 적용 -3 (0) 2022.04.20