- Instantiate(GameObject original) : original 게임오브젝트(프리팹)를 복제해서 생성 (복제되는 오브젝트의 모든 컴포넌트 정보가 원본과 완전히 동일)
- Instantiate(GameObject original, Vector3 position, Quaternion rotation) :
original 게임오브젝트(프리팹)을 복제해서 생성하고, 생성된 복제본의 위치를 position으로, 회전을 rotation으로 설정
- GameObject clone = Instantiate(GameObject original, Vector3 position, Quaternion rotation) :
생성된 복제 오브젝트의 정보를 clone에 저장, clone과 오브젝트의 정보는 동일, clone의 정보가 바뀌면 Hierachy View에 생성되 오브젝트의 정보가 바뀜
// PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private KeyCode keyCodeFire = KeyCode.Space; // spacebar 키
[SerializeField]
private GameObject bulletPrefab; // 총알 오브젝트
private float moveSpeed = 5.0f; // 플레이어 이동속도
private Vector3 lastMoveDirection = Vector3.right; // 마지막에 움직였던 방향을 저장, 처음엔 오른쪽으로 초기화
// 새로운 위치 = 현재 위치 + (방향 * 속도)
private void Update() {
// Negative left, a : -1
// Positive right, d : +1
// Non : 0
float x = Input.GetAxisRaw("Horizontal"); // 좌우 이동
// Negative down, s : -1
// Positive up, w : +1
// Non : 0
float y = Input.GetAxisRaw("Vertical"); // 위아래 이동
// 이동 방향 이동
transform.position += new Vector3(x, y, 0) * moveSpeed * Time.deltaTime;
// 플레이어 이동 방향키를 입력 받으면 lastMoveDirection에 저장
if(x != 0 || y != 0)
{
lastMoveDirection = new Vector3(x, y, 0);
}
// 플레이어 오브젝트 총알 발사
// 스페이스바를 입력받으면 slimeBall 오브젝트 발사
if(Input.GetKeyDown(keyCodeFire))
{
// bulletPrefab 오브젝트 생성, 생성되는 위치는 이 게임오브젝트의 위치(플레이어),
GameObject clone = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
clone.name = "Bullet"; // 생성한 오브젝트의 이름
clone.transform.localScale = Vector3.one;
clone.GetComponent<Movement2D>().Setup(lastMoveDirection);
// clone.GetComponent<SpriteRenderer>().color = Color.red;
}
}
}
// Movement2D.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement2D : MonoBehaviour
{
private float moveSpeed = 15.0f;
private Vector3 moveDirection;
public void Setup(Vector3 direction)
{
moveDirection = direction;
}
// Update is called once per frame
void Update()
{
transform.position += moveDirection * moveSpeed * Time.deltaTime;
}
}

'Unity' 카테고리의 다른 글
Unity 2D exercise (floppy bird) (0) | 2021.08.02 |
---|---|
Unity 2D exercise (shooting game) (0) | 2021.07.13 |
Unity 2D basic #4 (Trigger) (0) | 2021.07.03 |
Unity 2D basic #3 (Collision) (0) | 2021.07.03 |
Unity 2D basic #2 (Key Input) (0) | 2021.07.03 |