목표
- 아직 공이 내 벽(혹은 상대벽)에 닿았을때 아무런 동작을 하지 않는다
- 닿았을 때 점수처리(임시) 및 리스폰을 하도록 할 것이다
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;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Paddle"))
{
direction.x = -direction.x;
}
if (collision.gameObject.CompareTag("Wall"))
{
direction.y = -direction.y;
}
if (collision.gameObject.CompareTag("LeftGoalWall")||collision.gameObject.CompareTag("RightGoalWall"))
{
if (collision.gameObject.CompareTag("RightGoalWall"))
{
Debug.Log("goal! left score plus 1");
RespawnBall(true);
}
else
{
Debug.Log("goal! right score plus 1");
RespawnBall(false);
}
}
}
void RespawnBall(bool isLeftWin)
{
transform.position = new Vector2(-0.5f, -0.5f);
if (isLeftWin)
direction = new Vector2(1, 1);
else
direction = new Vector2(-1, 1);
}
// Update is called once per frame
void Update()
{
rigidbody.velocity = direction * speed;
}
}
- 기존 코드에서 골역할하는 벽의 충돌 처리 부분과 리스폰 처리 기능이 추가되었다.
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Paddle"))
{
direction.x = -direction.x;
}
if (collision.gameObject.CompareTag("Wall"))
{
direction.y = -direction.y;
}
if (collision.gameObject.CompareTag("LeftGoalWall")||collision.gameObject.CompareTag("RightGoalWall"))
{
if (collision.gameObject.CompareTag("RightGoalWall"))
{
Debug.Log("goal! left score plus 1");
RespawnBall(true);
}
else
{
Debug.Log("goal! right score plus 1");
RespawnBall(false);
}
}
}
- 골 역할을 하는 벽에 닿았을때 처리 기능이 생겼다.
- tag를 통해 오른쪽 벽인지 왼쪽 벽인지 구분한다.
- 일단 닿았으면 로그를 통해 점수가 증가한것을 알린다.(이부분은 뒤에 최종적으로 ui출력을 하도록 수정 예정)
- 함수 호출을 통해 공을 다시 배치한다.
void RespawnBall(bool isLeftWin)
{
transform.position = new Vector2(-0.5f, -0.5f);
if (isLeftWin)
direction = new Vector2(1, 1);
else
direction = new Vector2(-1, 1);
}
- 위선 position을 수정해 원래 위치로 되돌린다. 필자는 게임 맵의 중앙 좌표가 (-0.5 -0.5)로 되어 있으므로 다음과 같이 설정했다.
- bool값을 통해 누가 이겼는지 구분한다. 왼쪽패들이 이겼다면 공이 오른쪽으로 가게, 오른쪽패들이 이겼다면 공이 왼쪽으로 가게 방향을 다시 설정한다.
'유니티로 Pong 게임 만들기' 카테고리의 다른 글
7) 유니티로 Pong 게임 만들기 - 게임 종료 처리, 타이머 추가, 게임종료ui 추가 (0) | 2024.01.24 |
---|---|
6) 유니티로 Pong 게임 만들기 - 점수 ui 표시 (0) | 2024.01.24 |
4) 유니티로 Pong 게임 만들기 - 공이 패달과 벽에 닿았을때 튕겨내기 (0) | 2024.01.24 |
3) 유니티로 Pong 게임 만들기 - 공 발사되게 하기 (0) | 2024.01.24 |
2) 유니티로 Pong 게임 만들기 - 패들 움직이게 하기 (0) | 2024.01.24 |