점프구현은 간단하다.
코드를 다음과 같이 추가해주면 된다!
그리고 떨어지는 속도가 느리니 중력을 바꿔줄수있는데
1. Project Setting -> Gravity Y값을 바꿔주는 방법과
2. Rigidbody Scale -> 오브젝트에 적용되는 중력 비율을 바꿔줄수있다.
점프했을때는 걷는 애니메이션을 없애주는것이 좋다!!!
그러니 새 애니메이션을 만들어주고
이렇게 연결시키고 코드도 추가해주자.
그런데 문제가 생겼다.
점프가 끝나도 점프에서 ->idle로 넘어오지 않는다는것이다.
그렇기에 코드를 추가적으로 수정해서
"레이 케스트"라는것을 배워보자
(오브젝트 검색을 위해 Ray를 쏜다.
)
그렇게 레이저를 아래로 내려올때마다 쏴서 플랫폼이라고 Layer를 준 곳에 닿이면
함수가 실행되게 하여 다음 애니메이션으로 넘어가게,
그리고 점프도 무한점프를 방지하게 짠 코드가 다음과 같다.
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;
void Awake()
{
rigid = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
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.5f, rigid.velocity.y);//float곱할때는 f붙여줘야한다.
}
// change Direction
if(Input.GetButtonDown("Horizontal"))
spriteRenderer.flipX = Input.GetAxisRaw("Horizontal") == -1;
// work animation
if (Mathf.Abs( rigid.velocity.x)< 0.3) //절댓값 설정
anim.SetBool("isWorking", false);
else
anim.SetBool("isWorking", true);
}
void FixedUpdate()
{
// Move by Control
float h = Input.GetAxisRaw("Horizontal"); // 횡으로 키를 누르면
rigid.AddForce(Vector2.right*h,ForceMode2D.Impulse); // 이르케 이동한다 !
// MaxSpeed Limit
if (rigid.velocity.x > maxSpeed)// right
rigid.velocity = new Vector2(maxSpeed, rigid.velocity.y);
else if (rigid.velocity.x < maxSpeed * (-1)) // Left Maxspeed
rigid.velocity = new Vector2(maxSpeed * (-1), rigid.velocity.y);
// Lending 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);
}
}
}
}
}
점프까지 구현완료!!