반응형
- 코드 작성
PaddleController.cs
using UnityEngine;
public class PaddleController : MonoBehaviour
{
public float speed = 5f;
void Update()
{
float moveInput = Input.GetAxis("Vertical");
transform.Translate(Vector2.up * moveInput * speed * Time.deltaTime);
}
}
BallController.cs
using UnityEngine;
public class BallController : MonoBehaviour
{
public float speed = 5f;
void Start()
{
LaunchBall();
}
void Update()
{
MoveBall();
}
void MoveBall()
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
void LaunchBall()
{
float randomDirection = Random.Range(0, 2) * 2 - 1; // -1 or 1
GetComponent<Rigidbody2D>().velocity = new Vector2(randomDirection, 1).normalized * speed;
}
}
GameManager.cs
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public Text scoreText;
private int score = 0;
void Update()
{
scoreText.text = "Score: " + score;
}
public void IncreaseScore()
{
score++;
}
}
CollisionHandler.cs
using UnityEngine;
public class CollisionHandler : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Ball"))
{
FindObjectOfType<GameManager>().IncreaseScore();
collision.GetComponent<BallController>().LaunchBall();
}
}
}
반응형