jump 후 중력을 받아 바닥으로 떨어질 때 뛸 때와 달리 천천히 떨어진다. 이를 조절하기 위해서는 Project Setting에서 Physics 2D에서 Gravity를 바꿔주거나 Rigidbody 2D에서 Gravity Scale을 바꿔주면 된다.
제자리에서 jump를 한다면 animation이 breath - jump - breath 순으로 바뀌어야 한다.
이를 위해 오브젝트 검색을 위해 Ray를 쏘는 방식인 RayCast를 이용했다.
DrawRay() - 에디터 상에서만 Ray를 그려주는 함수
Debug이므로 실제 게임창에는 나타나지 않는다.
RayCastHit 변수의 콜라이더로 검색 확인이 가능하다.
LayerMask - 물리 효과를 구분하는 정수값
jump animation이 추가되므로 다음과 같이 animator를 설정해주면 된다. <해야할 것>은 똑같다.

<코드>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float maxSpeed;
public float jumpPower;
Rigidbody2D rigid;
SpriteRenderer spriteRenderer;
Animator anim;
// Start is called before the first frame update
void Awake() {
rigid = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{ //Jump
if(Input.GetButtonDown("Jump") && !anim.GetBool("isJumping")){
rigid.AddForce(Vector2.up*jumpPower, ForceMode2D.Impulse);
anim.SetBool("isJumping",true);}
//Stop Speed
if(Input.GetButtonUp("Horizontal")){
rigid.velocity = new Vector2(rigid.velocity.normalized.x*0.2f, rigid.velocity.y);
}
//Direction Sprite
if(Input.GetButton("Horizontal")){
spriteRenderer.flipX = Input.GetAxisRaw("Horizontal") == -1;
}
//Walk <-> Breath
if(Mathf.Abs(rigid.velocity.x)<0.3f)
anim.SetBool("isWalking",false);
else
anim.SetBool("isWalking",true);
}
void FixedUpdate()
{
//Move By 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); // Right Max Speed
else if(rigid.velocity.x < maxSpeed*(-1))
rigid.velocity = new Vector2(maxSpeed*(-1), rigid.velocity.y); // Left Max Speed
//Landing Platform
if(rigid.velocity.y < 0){
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.5f){
anim.SetBool("isJumping", false);
}
}
}
}
}
'game > unity(C#)' 카테고리의 다른 글
나만의 리듬게임 개발일지 - 2 (0) | 2022.08.10 |
---|---|
나만의 리듬게임 개발일지 - 1 (0) | 2022.07.27 |
2D 기초 - 2 (Player 이동 구현) (0) | 2022.07.14 |
2D 기초 - 1 (Component, Animation) (0) | 2022.07.12 |
Visual Studio Code 자동 완성이 되지 않는 오류 (0) | 2022.07.12 |