스마트폰 화면을 터치하거나 스와이프하면 해당 캐릭터가 점프하고 점프하면서 사운드(효과음)이 나도록 합니다. 배경 상단의 새 한마리는 좌우 반전(Flip Move)되면서 이동하도록 할거에요.
[SwipeJump.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwipeJump : MonoBehaviour
{
[SerializeField] float jumpForce = 600f;
Vector2 startTouchPos, endTouchPos;
Rigidbody2D rb;
bool jumpAllowed = false;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
TouchCheck();
}
void FixedUpdate()
{
JumpIfAllowed();
}
void TouchCheck()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
startTouchPos = Input.GetTouch(0).position;
}
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
endTouchPos = Input.GetTouch(0).position;
if (endTouchPos.y > startTouchPos.y && rb.velocity.y == 0)
jumpAllowed = true;
}
}
void JumpIfAllowed()
{
if (jumpAllowed)
{
rb.AddForce(Vector2.up * jumpForce);
JumpSound.SoundPlay();
jumpAllowed = false;
}
}
}
[BirdMove.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BirdMove : MonoBehaviour
{
Rigidbody2D rb;
Vector3 localScale;
[SerializeField] float speed = 5, dist = 7;
bool dirRight = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
localScale = transform.localScale;
}
void FixedUpdate()
{
if (transform.position.x > dist)
dirRight = false;
else if (transform.position.x < -dist)
dirRight = true;
if (dirRight)
GoRight();
else
GoLeft();
}
void GoRight()
{
localScale.x = -1f;
transform.transform.localScale = localScale;
rb.velocity = new Vector2(speed, 0);
}
void GoLeft()
{
localScale.x = 1f;
transform.transform.localScale = localScale;
rb.velocity = new Vector2(-speed, 0);
}
}
[JumpSound.cs]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumpSound : MonoBehaviour
{
static AudioSource audioSource;
public static AudioClip audioClip;
void Start()
{
audioSource = GetComponent<AudioSource>(); audioClip = Resources.Load<AudioClip>("Jump");
}
public static void SoundPlay()
{
audioSource.PlayOneShot(audioClip);
}
}
댓글