유니티로 Pong 게임 만들기

3) 유니티로 Pong 게임 만들기 - 공 발사되게 하기

잡동사니123 2024. 1. 24. 03:45

목표

  • 공이 가만히있으면 게임 진행이 안된다
  • 따라서 첫 시작시 공이 움직이게 할 것이다.
  • 일단 공은 player2쪽으로해서 발사되게 할것이다.(랜덤 방향 발사등은 구현x)

 

컴포넌트 추가

  • 공 오브젝트를 눌렀을때 나오는 다음과 같은 창에서 Add Component 클릭 -> Rigidbody 2D 검색해서 클릭

  • gravity scale(중력)값 0으로 설정

Ball.cs (스크립트)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;

public class Ball : MonoBehaviour
{
    private Rigidbody2D rigidbody;
    public float speed = 8f;
    private Vector2 direction;

    // Start is called before the first frame update
    void Start()
    {
        rigidbody = GetComponent<Rigidbody2D>();
        direction = Vector2.one.normalized;
    }


    // Update is called once per frame
    void Update()
    {
        rigidbody.velocity = direction * speed;
    }
}
  • 공을 움직이게 할 스크립트 새로 만들기
    void Start()
    {
        rigidbody = GetComponent<Rigidbody2D>();
        direction = Vector2.one.normalized;
    }
  • 공의 리지드바디를 불러온다.
  • 처음 움직일 방향을 설정한다.
    void Update()
    {
        rigidbody.velocity = direction * speed;
    }
  • 일정속도로 해당 방향을 향해 공이 자동으로 움직이게 한다.

 

스크립트 적용시키기

  • 스크립트를 붙인다.

 

이번 결과

  • 공이 움직인다. 이 외의 처리(벽과 닿았을때, 패들과 닿았을때 등)은 다음 페이지에서 처리할 예정이다.