kunkunwoo@blog:~$ 거누권의 생각깜지

6. 유니티 _ 아틀라스, 애니메이션, 이동, 점프

· 배운 것 · 6분 읽기

아틀라스를 사용하는 이유? 드로우콜을 줄이기 위해서 사용 ( 최적화와 관련 )


애니메이션 동작

2d 도트들을 이용해서 만든 애니메이션
2d 도트들을 이용해서 만든 애니메이션

이동, 점프 ( 애니메이션 모션까지 )

이동, 점프 (모션까지 구현)
이동, 점프 (모션까지 구현)

Player C# Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float maxSpeed;
    public float jumpPower;
    bool isJump;
    Rigidbody2D rigid;
    SpriteRenderer spriteRenderer;
    Animator anim;

    private void Awake()
    {
        isJump = false;
        anim = GetComponent<Animator>();
        rigid = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    //단발적인 입력은 update에
    void Update()
    {
        //stop speed
        if(Input.GetButtonUp("Horizontal"))
        {
            //normalized -> 벡터 크기를 1로 만든 상태
            rigid.velocity = new Vector2(rigid.velocity.normalized.x *0.5f, rigid.velocity.y);
        }

        //jump
        if (Input.GetButtonDown("Jump") && isJump == false)
        {
            isJump = true;
            rigid.AddForce(new Vector2(rigid.velocity.x, jumpPower), ForceMode2D.Impulse);
        }

        //방향전환
        if (Input.GetButton("Horizontal"))
        {
            bool v = (Input.GetAxisRaw("Horizontal") == -1.0f);
            spriteRenderer.flipX = v;
        }

        //walking motion
        if (Mathf.Abs(rigid.velocity.x) <= 0.3f)
            anim.SetBool("isWalking", false);
        else
            anim.SetBool("isWalking", true);

        //jump motion
        if(isJump == true)
            anim.SetBool("isJumping", true);
        else
            anim.SetBool("isJumping", false);
    }

    private void FixedUpdate()
    {
        //move by key control
        float h = Input.GetAxisRaw("Horizontal");
        rigid.AddForce(Vector2.right * h, ForceMode2D.Impulse);

        if (rigid.velocity.x > maxSpeed)
            rigid.velocity = new Vector2(maxSpeed, rigid.velocity.y);
        else if (rigid.velocity.x < maxSpeed*(-1))
            rigid.velocity = new Vector2(maxSpeed*(-1), rigid.velocity.y);

        if (rigid.velocity.y < 0)
        {
            //landing platform, 레이저로 쏴서 맞춘 첫번째 물체를 식별
            Debug.DrawRay(rigid.position, Vector3.down, new Color(0, 1, 0));

            RaycastHit2D rayHit = Physics2D.Raycast(rigid.position, Vector3.down, 1,
                                                LayerMask.GetMask("Platform"));

            //땅에 닿았을때 다시 점프가능
            if (rayHit.collider != null)
                if (rayHit.distance <= 0.5)
                    isJump = false;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        
    }
}

참고

https://www.youtube.com/user/GoldmetalYT

골드메탈


후기

간단하고 재밌다.