간만에, 지난번에 작업하던 유니티 게임을 분석하고 있습니다.
오늘은 공룡에서 총알이 나오는 부분을 적용해 보았습니다.
실행결과는 스페이스바(JUMP키)를 누르면, 선택한 방향으로 빨간색 총알이 발사됩니다.(아래)
-Bullet프리팻을 만들고, C#코드를 적용했습니다.(핵심코드아래 Movement2D.cs)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement2D : MonoBehaviour
{
[SerializeField]//private변수지만, inspector에서 접근 가능하게 하기 위해서
private float moveSpeed = 5f;
private Vector3 lastMoveDirection = Vector3.right;
// Start is called before the first frame update
void Start()
{
}
public void Setup(Vector3 paramMoveDirection)
{
lastMoveDirection = paramMoveDirection;
}
// Update is called once per frame
void Update()
{
Jump();
//Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
Vector3 movement = lastMoveDirection;
transform.position += movement * Time.deltaTime * moveSpeed;
}
void Jump()
{
//if (Input.GetButtonDown("Jump"))//점프는 KeyCode.Space와 같음.
//{
Debug.Log("여기까지");
//gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 0f), ForceMode2D.Force);
//}
}
}
-Player를 Instantialte로 생성후 clone으로 총알을 복제해서 공룡을 화살표로 선택한 방향으로 발사하는 C#코드(아래)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementPlayer : MonoBehaviour
{
private float moveSpeed = 5.0f;//이동속도
private Vector3 moveDirection = Vector3.zero;//이동방향
private Rigidbody2D rigid2D;
private SpriteRenderer spriteRenderer;
private Color color=Color.white;
[SerializeField]
private KeyCode keyCodeFire = KeyCode.Space;
[SerializeField]//private변수지만, inspector에서 접근 가능하게 하기 위해서
private GameObject bulletPrefab;
private Vector3 lastMoveDirection = Vector3.right;
private void Awake()//초기 1회만 실행
{
//새로운위치 = 현재위치+(방향*속도)
//transform.position = transform.position + new Vector3(1, 0, 0) * 1;
//transform.position+=Vector3.right*1;
rigid2D = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//단축키로 게임캐릭터 이동시키기
//Horizontal: left(Negative=-1), right(Positive=+1)
//Vertical: down(Negative=-1), up(Positive=+1)
float x = Input.GetAxisRaw("Horizontal");//좌우
float y = Input.GetAxisRaw("Vertical");//상하
//이동방향 설정
moveDirection = new Vector3(x, y, 0);
//새로운위치=현재위치+(방향*속도)
transform.position += moveDirection*moveSpeed*Time.deltaTime;
//rigid2D.velocity = new Vector3(x, y, 0) * moveSpeed;
//마지막에 입력된 방향키의 방향을 총알의 발사 방향으로 활용
if(x !=0 || y != 0)
{
lastMoveDirection = new Vector3(x, y, 0);
}
//플레이어 오브젝트 총알 발사
if (Input.GetKeyDown(keyCodeFire))
{
GameObject clone = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
clone.name = "Bullet";
clone.transform.localScale = Vector3.one * 0.5f;
clone.GetComponent<SpriteRenderer>().color = Color.red;
clone.GetComponent<Movement2D>().Setup(lastMoveDirection);
}
}
//충돌이벤트 함수 충돌이 일어나는 순간 1회 호출
private void OnCollisionEnter2D(Collision2D collision)
{
spriteRenderer.color = Color.gray;
}
//충돌이 종료되는 순간 1회 호출
private void OnCollisionExit2D(Collision2D collision)
{
spriteRenderer.color = color;
}
}
댓글 영역