안드로이드 폰의 화면을 스와이프(Input.GetTouch | AddForce)하여 농구공을 바스켓에 넣는 농구게임을 제작해 봅니다. 농구공이 바스켓에 부딪힐 때 효과음이 발생하도록 구현하고 Edge Collider 2D를 활용해서 배경에 충돌 영역을 지정해봅니다.
#농구게임만들기 #InputGetTouch #AddForce
[SwipeAddforce.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeAddforce : MonoBehaviour
{
Rigidbody2D rb;
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish, timeInterval;
[SerializeField][Range(0.05f, 1f)] float throwForce = 0.3f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
touchTimeStart = Time.time;
startPos = Input.GetTouch(0).position;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
touchTimeFinish = Time.time;
timeInterval = touchTimeFinish - touchTimeStart;
endPos = Input.GetTouch(0).position;
direction = startPos - endPos;
rb.AddForce(-direction / timeInterval * throwForce);
}
}
}
[BasketSound.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasketSound : MonoBehaviour
{
static AudioSource audioSource;
public static AudioClip audioClip;
void Start()
{
audioSource = GetComponent<AudioSource>(); audioClip = Resources.Load<AudioClip>("Backboard");
}
public static void SoundPlay()
{
audioSource.PlayOneShot(audioClip);
}
}
[Basket.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Basket : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
BasketSound.SoundPlay();
}
}
댓글