아카이브
클릭한 위치에 몬스터 생성/삭제 본문
Test_CreateMonster 오브젝트와 스크립트를 만든다

Test_CreateMonster 스크립트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_CreateMonster : MonoBehaviour
{
[SerializeField]
private GameObject prefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//좌클릭한 화면의 픽셀좌표로 Ray를 만든다
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//ray를 출력
Debug.DrawRay(ray.origin, ray.direction * 1000f, Color.red, 5f);
//Ray와 충돌검사를 위해 타겟(Plane)은 Collider가 있어야 한다
RaycastHit hit;
//충돌을 검사 코드
if (Physics.Raycast(ray, out hit, 1000f))
{
//충돌 지점의 월드 좌표
Debug.Log(hit.point);
//충돌한 콜라이더의 게임오브젝트의 태그가 Ground라면
if (hit.collider.gameObject.tag == "Ground")
{
//프리팹으로 게임오브젝트(프리팹의 인스턴스/복사본) 생성하기
GameObject go = Instantiate(this.prefab);
//위치설정
go.transform.position = hit.point;
}
}
}
//우클릭을 하면 삭제되게 몬스터 만들기
else if(Input.GetMouseButtonDown(1))
{
//레이 만들기
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//출력
Debug.DrawRay(ray.origin, ray.direction * 1000f, Color.green, 5f);
RaycastHit hit;
//충돌검사
if(Physics.Raycast(ray,out hit, 100f))
{
//충돌한 콜라이더의 게임 오브젝트 태그가 monster면
if(hit.collider.gameObject.tag == "Monster")
{
//제거
Destroy(hit.collider.gameObject);
}
}
}
}
}



실행화면

'유니티 기초' 카테고리의 다른 글
페이드인, 페이드 아웃 연습 (0) | 2023.08.14 |
---|---|
아이템 착용하기 (0) | 2023.08.11 |
주말과제(Dog Knight) (1) | 2023.08.06 |
유니티짱 직선으로 움직이기 (0) | 2023.08.04 |
8/1 유니티 복습 (0) | 2023.08.02 |