[개인공부]/Unity
[Unity 2D] Player 총알 발사
별빛정원
2022. 7. 11. 03:19
300x250
총알이 생성될 지점 설정해주기
PlayerAction.cs
using UnityEngine;
public class PlayerAction : MonoBehaviour
{
private Transform bulletSpawnPoint;
public GameObject bulletPrefab;
// Start is called before the first frame update
void Start()
{
// 플레이어 오브젝트에 자식오브젝트로 있는 BulletSpawnPoint 찾아와서 위치 설정 해주기
bulletSpawnPoint = this.transform.Find("BulletSpawnPoint");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//총알을 만든다
var bulletGo = Instantiate<GameObject>(this.bulletPrefab);
bulletGo.transform.position = this.bulletSpawnPoint.position;
}
}
}
Bullet.cs
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 5f;
void Update()
{
// 총알이 많이 날라가면 삭제 해주기
if(this.transform.position.y > 5)
{
Destroy(this.gameObject);
}
// Vector3.up = new Vector(0, 1, 0)
this.transform.Translate(Vector3.up * this.speed * Time.deltaTime);
}
}
총알 프리팹 설정, Bullet 스크립트 넣어주기
플레이어한테 넣어주기
300x250