using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BullrtControler : MonoBehaviour
{
public float speed = 1f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
var movement = new Vector3(0, 1, 0)/*vector3.up*/ * this.speed * Time.deltaTime;
//this.transform.Translate(0, 1 * this.speed * Time.deltaTime, 0) ;
this.transform.Translate(movement);
if(this.transform.position.y > 5.5f)
{
//Destroy(this.gameObject);
this.gameObject.SetActive(false);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "enemy")
{
this.gameObject.SetActive(false);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class ShipControler : MonoBehaviour
{
[SerializeField]
private GameObject bullet;
private GameObject[] bullets;
[SerializeField]
private float speed = 1.0f;
public UnityAction DieAction;
public GameObject explosionGo;
private int cnt = 0;
// Start is called before the first frame update
void Start()
{
this.bullets = new GameObject[100];
for (int i = 0; i < 100; i++)
{
GameObject bullet = Instantiate(this.bullet);
bullets[i] = bullet;
bullet.SetActive(false);
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
//var shot = Instantiate(this.bullet, this.transform.position + new Vector3(0, 0.66f, 0),Quaternion.identity);
if (cnt == 100) cnt = 0;
this.bullets[cnt].SetActive(true);
this.bullets[cnt].transform.position = this.transform.position + new Vector3(0, 0.66f, 0);
cnt++;
}
float getX = Input.GetAxisRaw("Horizontal");
float getY = Input.GetAxisRaw("Vertical");
var movement = new Vector3(getX, getY, 0);
movement = movement.normalized * Time.deltaTime * this.speed;
/*if (Input.GetKey(KeyCode.LeftArrow))
{
this.transform.position -= movement;
}
if (Input.GetKey(KeyCode.RightArrow))
{
this.transform.position += movement;
}*/
this.transform.Translate(movement);
}
public void Die()
{
this.DieAction();
Destroy(this.gameObject);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "enemy")
{
Destroy(collision.gameObject);
Instantiate(this.explosionGo, this.transform.position, Quaternion.identity);
this.Die();
}
}
}
지금 ship은 100개의 비활성화된 bullet을 들고있고, 쏠때마다 하나씩 활성화시키고, bullet에 "적에게 닿거나" , "화면밖으로 날아갔을때" 비활성화 되도록 설정해놓는다.
시작하자마자 100개를 만들기때문에 메모리를 사용하게 되지만, 누를때마다 새 총알을 생성하고, 사라질때마다 destroy 시키는 방식에 비해서 컴퓨터의 부담이 훨씬 덜하게 된다.
좋다.
'C# > 수업내용' 카테고리의 다른 글
| 0719 포토샵 단축키 (0) | 2022.07.19 |
|---|---|
| 0718 (0) | 2022.07.18 |
| 0708 슈팅게임 (0) | 2022.07.08 |
| 0707 유니티 (0) | 2022.07.07 |
| 0707 표창날리기 (0) | 2022.07.07 |