점프 기능을 넣어보자
시작하기에 앞서 Player Script 를 살짝 수정하겠다.
Update 함수를 사용하여 키 입력을 받고 Player 를 이동시켰으나
Player 는 Rigidbody 가 적용된 물리적으로 움직이는 오브젝트이므로
FixedUpdate 함수에 넣겠다.
Update 함수는 매 프레임마다 호출된다. (일정하지 않다.)
보통 물리효과가 적용되지 않은 오브젝트, 단순 타이머, 키입력에 사용된다.
FixedUpdate 는 일정한 간격으로 호출된다.
따라서 물리효과가 적용된 오브젝트를 조정할 때 사용된다.
Update : 불규칙한 호출 → 물리검사가 제대로 이루어지지 않을 수 있다.
FixedUpdate : 규칙적인 호출 → 물리검사에 적합하다.
private void Update()
{
horizontal = Input.GetAxis("Horizontal");
}
void FixedUpdate()
{
animator.SetFloat("DirX", Mathf.Abs(horizontal));
if (horizontal < 0)
myRenderer.flipX = true;
else
myRenderer.flipX = false;
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
다음과 같이 수정하고 시작하겠다.
Player 의 점프기능을 만들어보자
Space 키를 누르면 점프하도록 만들자!
public float jumpPower = 10.0f;
private void Update()
{
horizontal = Input.GetAxis("Horizontal");
if(Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * jumpPower;
}
}
이렇게 바꾸고
Player Rigidbody 의 Gravity 를 2로 바꾸자
Gravity 는 밑으로 떨어지는 힘이므로 1 로 하면 물 속처럼 천천히 떨어진다.
잘 움직이는 것을 볼 수 있다.
이제 적을 만들어보자
Player 만들 때와 같은 방식으로
Sprite 추가 → Scene 에 기본 Sprite 추가 → Rigidbody & Box Collider 추가
이렇게 진행되며 Gravity 2, Box Size 설정을 해주면 된다.
다음으로 적의 애니메이션을 만들어보자
모두 잘 추가되어 있는 것을 볼 수 있다.
잘 작동한다.
이제 적을 움직여 볼텐데 방식은 여러가지가 크게 두 가지가 있다.
맵의 양 끝에 Box Collider 를 생성해 부딪히면 방향을 바꿔주거나
맵의 양 끝에 빈 Object 를 두고 해당 포지션에 닿으면 반대로 돌아오거나
첫 번째 예시는 구글에 많길래 두 번째를 택하겠다.
만약 왔다갔다 움직이는 간단한 방식이 아니라면 두 번째가 훨씬 편하다.
Scripts 폴더에 Enemy Script 를 만들어주자
첫 번째로
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Transform[] moveArr;
public float speed;
private int randSpot;
// Start is called before the first frame update
void Start()
{
randSpot = 0;
}
void FixedUpdate()
{
transform.position = Vector2.MoveTowards(
transform.position,
moveArr[randSpot].position,
speed * Time.deltaTime
);
if(Vector2.Distance(transform.position,
moveArr[randSpot].position) < 0.2f)
{
if (transform.position.x > moveArr[randSpot].position.x)
transform.localScale = new Vector2(-0.6f, 0.6f);
else
transform.localScale = new Vector2(0.0834f, 0.0834f);
randSpot = Random.Range(0, moveArr.Length);
}
}
}
다음처럼 Rigidbody 없이
모든 Object 에 붙어있는 transform 을 이용하여 움직이게 하고
Scale 을 이용해 캐릭터를 좌우 반전 시켜도 되고
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Rigidbody2D rb;
public Transform[] moveArr;
public float speed = 1.0f;
private int randSpot;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
randSpot = 0;
}
void FixedUpdate()
{
rb.position = Vector2.MoveTowards(
rb.position,
moveArr[randSpot].position,
speed * Time.deltaTime
);
if(Vector2.Distance(rb.position,
moveArr[randSpot].position) < 0.2f)
{
if (rb.position.x > moveArr[randSpot].position.x)
myRen.flipX = true;
else
myRen.flipX = false;
randSpot = Random.Range(0, moveArr.Length);
}
}
}
위처럼
Rigidbody 를 쓰고
Inspector 창의 Renderer 를 사용하여 좌우 반전을 시켜도 된다.
다음으로 여기서 중요한 점은
위 사진의 Renderer 에서 보이는 Sprite Sort Point 라는 목록이다.
우리가 Sprite 를 생성하게 되면 해당 이미지의 좌표는 자동적으로
Center 에 맞춰진다.
우리는 4장의 Sprite 를 이용하여 애니메이션과 캐릭터를 작동시키는데
다음과 같이 바닥에 WayPoint 라는 좌표를 생성하게 되면
Enemy 와 Point 의 차가 0.2 보다 크게 되어 계속 나아가려고 한다.
이를 Sprite Sort Point 를 수정함으로써 Enemy 의 중심좌표를
Sprite 목록에서
Pivot 항목을 Custom 으로 맞춘 후 오른쪽 하단에서 Apply 시키고
오른쪽의 Sprite Editor 를 누르고 사진에서 본인이 선택하던
하단에서 본인이 입력하던 편한대로 하면 된다.
우리는 이미지 4장을 모두 작업해야하기에 적당한 좌표를 이미지에서 찾아
기입하는 것이 편리하다.
작업을 마치면 이제 Enemy 에 Point 를 넣어주면 된다.
정한 Point 를 다음과 같이 Drag & Drop 하면 된다.
하나씩 해도 되고 Enemy Inspector 상단에 있는 자물쇠를 클릭 후
한번에 선택하여 (Shift 이용) MoveArr 로 넣으면 된다.
Rigidbody 도 빼먹지 말고 넣어주면 다음과 같이 움직이게 된다.
오늘은 여기까지 :)