우주선 위치에 따라 총알 발사하기
: 자식 오브젝트 설정
Transform firePoint
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpaceShipController : MonoBehaviour
{
[SerializeField] private float Speed=1f;
[SerializeField] private Vector2 horizBoundary; //이동제한 범위 설정
[SerializeField] private Vector2 vertBoundary;
[SerializeField] private BulletGenerator bulletGenerator; //프리팹가져오기
[SerializeField] private Transform firePoint; // 자식오브젝트 설정
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
MoveControl();
InCamera();
BulletFire();
}
void MoveControl() //방향키로 움직이기
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
Vector3 dir = new Vector3 (moveX, moveY, 0);
this.transform.Translate(dir.normalized*this.Speed*Time.deltaTime);
}
void InCamera()//화면밖으로 나가지않게 하기
{
float clampX = Mathf.Clamp(this.rb.transform.position.x, this.horizBoundary.x, this.horizBoundary.y);
float clampY = Mathf.Clamp(this.rb.transform.position.y,this. vertBoundary.x,this.vertBoundary.y);
this.rb.transform.position = new Vector2(clampX,clampY);
}
void BulletFire()// 우주선의 위치에 따라 총알 발사하기
{
if(Input.GetKeyDown(KeyCode.Space))
{
GameObject bulletGo = this.bulletGenerator.CreateBullet();
bulletGo.transform.position = this.firePoint.position;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class BulletController : MonoBehaviour
{
[SerializeField]private float speed=4f;
void Update()
{
// 위로 총알 발사
this.transform.Translate(Vector2.up *this.speed*Time.deltaTime);
//화면 밖으로 나가면 사라지게
if(this.transform.position.y > 6.56f)
{
Destroy(this.gameObject);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletGenerator : MonoBehaviour
{
[SerializeField]private GameObject bulletPrefab;
public GameObject CreateBullet()
{
return Instantiate(this.bulletPrefab);
}
}
GetAxis & GetAxisRaw
- Input.GetAxis(string name)
수평, 수직 버튼 입력을 받으면 float
-1f ~ 1f 의 값을 반환한다
부드러운 이동이 필요한경우 사용한다
- Input.GetAxisRaw(string name)
수평, 수직 버튼 입력을 받으면 float
-1f , 0f, 1f 의 값을 반환한다
즉각적인 반응이 필요할때 사용한다
'게임개발 > 게임 클라이언트 프로그래밍' 카테고리의 다른 글
[참조] 폭발효과만들기 (0) | 2024.02.04 |
---|---|
ShootingSpace (2) 적과 총알의 충돌 (0) | 2024.02.03 |
3D 밤송이를 날려라 (0) | 2024.02.03 |
PirateBomb (2) Captain (0) | 2024.02.01 |
PirateBomb(1) BombGuy (0) | 2024.02.01 |