반응형
- 코드 작성
using UnityEngine;
public class BlockBreaker : MonoBehaviour
{
public int rows = 4;
public int columns = 5;
public float paddleSpeed = 10f;
public GameObject blockPrefab;
public Transform paddle;
public GameObject ballPrefab;
public Transform ballSpawnPoint;
private Rigidbody2D ballRigidbody;
private bool isBallReleased;
private int blockCount;
private void Start()
{
SpawnBlocks();
SpawnBall();
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
Vector3 paddlePosition = paddle.position + new Vector3(horizontalInput * paddleSpeed * Time.deltaTime, 0f, 0f);
paddlePosition.x = Mathf.Clamp(paddlePosition.x, -8.5f, 8.5f);
paddle.position = paddlePosition;
if (Input.GetKeyDown(KeyCode.Space) && !isBallReleased)
{
ballRigidbody.isKinematic = false;
ballRigidbody.AddForce(new Vector2(0f, 300f));
isBallReleased = true;
}
}
private void SpawnBlocks()
{
blockCount = 0;
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
Vector3 blockPosition = new Vector3(column - (columns / 2) + 0.5f, row + 0.5f, 0f);
Instantiate(blockPrefab, blockPosition, Quaternion.identity);
blockCount++;
}
}
}
private void SpawnBall()
{
GameObject ball = Instantiate(ballPrefab, ballSpawnPoint.position, Quaternion.identity);
ballRigidbody = ball.GetComponent<Rigidbody2D>();
isBallReleased = false;
}
public void BlockDestroyed()
{
blockCount--;
if (blockCount <= 0)
{
Debug.Log("You Win!");
// 이겼을 경우
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Block"))
{
Destroy(collision.gameObject);
BlockDestroyed();
}
}
}
반응형