[공부] 261019~20 유니티
UI와 캔버스

기본 설정값
점프 구현

public class PlayerController : MonoBehaviour
{
[SerializeField] Rigidbody2D rigid;
[SerializeField] [Range(0, 20f)] float jumpSpeed;
private void Awake()
{
rigid = GetComponent<Rigidbody2D>();// GetComponent = 같은 게임오브젝트에 있는 기능 가져옴
}
// Start is called once before the first execution of Update after the MonoBehaviour is created
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Jump"))
{
Jump();
}
}
private void Jump()
{
rigid.linearVelocityY = jumpSpeed;
}
}
점프 키를 누르면 위쪽 방향으로 속력을 줘서 점프 구현
- rigid.linearVelocityY = jumpSpeed;
- jumpSpeed만큼 위쪽으로 힘을 줌
애니메이션 제어


- 사망 트리거 Die
- 점프 불 Grounded 생성
[Header("애니메이션")]
[SerializeField] Animator animator;
///
private void Jump()
{
rigid.linearVelocityY = jumpSpeed;
jumpSound.Play();
jumpCount--;
animator.SetBool("Grounded", false);
}
///
public void Die()
{
animator.SetTrigger("Die");
rigid.linearVelocity = Vector2.zero;
rigid.simulated = false;
dieSound.Play();
}
사운드 재생(기본)
[SerializeField] AudioSource jumpSound;
private void Jump()
{
rigid.linearVelocityY = jumpSpeed;
jumpSound.Play();
jumpCount--;
animator.SetBool("Grounded", false);
}
[추가기능] 랜덤 플랫폼 생성

using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour
{
[SerializeField] GameObject[] platform;
[SerializeField] float spawnTime;
void Start()
{
StartCoroutine(SpawnPlatform());
}
// Update is called once per frame
void Update()
{
}
public IEnumerator SpawnPlatform()
{
int temp = Random.Range(0, platform.Length);
int ypos = Random.Range(-3, 0);
yield return new WaitForSeconds(spawnTime);
Instantiate(platform[temp], new Vector3(20, ypos, 0), platform[temp].transform.rotation);
StartCoroutine(SpawnPlatform());
}
}
일정 주기마다 넣은 플랫폼중 랜덤 뽑아 생성하는스크립트
- [SerializeField] GameObject[] platform; 넣을 플랫폼을 배열로 받음
- StartCoroutine(SpawnPlatform()); / public IEnumerator SpawnPlatform()
- 코루틴으로 반복 생성
- int temp = Random.Range(0, platform.Length); / int ypos = Random.Range(-3, 0);
- 플랫폼 개수만큼 랜덤으로 / -3에서 0만큼의 y값 변화를 줌
- Instantiate(platform[temp], new Vector3(20, ypos, 0), platform[temp].transform.rotation);
- StartCoroutine(SpawnPlatform());
- 그대로 생성하고 다시 코루틴 반복



