etc./🕹️unity
unity 물리엔진과 충돌 시스템
yewoneeee
2022. 6. 11. 02:14
#1 DestroyZone
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyZone : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
//너만 죽어라
Destroy(other.gameObject);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
#2 EnemyManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 일정시간마다 적공장에서 적을 만들어서 내 위치에 가져다 놓고 싶다.
public class EnemyManager : MonoBehaviour
{
// 적 공장
public GameObject enemyFactory;
// 현재시간
float currentTime;
// 생성시간
public float createTime=1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// 1.시간이 흐르다가
currentTime += Time.deltaTime;
// 2. 현재시간이 생성시간이 되면
if (currentTime > createTime)
{
// 3. 적 공장에서 적을 만들어서
GameObject enemy = Instantiate(enemyFactory);
// 4. 내 위치에 가져다 놓고 싶다.
enemy.transform.position = transform.position;
// 5. 현재시간을 0으로 초기화 하고싶다.
currentTime = 0;
}
}
}
#3 Enemy 밑에부분 충돌처리
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 태어날 때 30% 확률로 플레이어 방향, 나머지 확률로 아래방향으로 정하고
// 살아가면서 그 방향으로 계속 이동하고 싶다.
public class Enemy : MonoBehaviour
{
// 방향
Vector3 dir;
//속력
public float speed = 5;
// Start is called before the first frame update
void Start()
{
// 태어날 때
// 1. 30% 확률로 플레이어 방향, 나머지 확률로 아래방향으로 정하고
int result = UnityEngine.Random.Range(0, 10); //float형으로하면 0과 10도 포함(0~10), int형으로 쓰면 10은 미포함(0~9)
if (result < 3)
{
//플레이어 방향
GameObject target = GameObject.Find("Player");
// dir = target - me
dir = target.transform.position - transform.position;
dir.Normalize();
}
else
{
//아래방향
dir = Vector3.down;
}
}
// Update is called once per frame
void Update()
{
// 살아가면서 그 방향으로 계속 이동하고 싶다.
transform.position += dir * speed * Time.deltaTime;
}
private void OnCollisionEnter(Collision other)
{
//rigidbody는 움직이는 물체와 움직이지 않는 물체 구분
Destroy(other.gameObject); //너죽고(bullet)
Destroy(gameObject); //나죽자(enemy)
}
}