1. 첫번째 방법 (가장 간단)
float h = Input.GetAxisRaw("Horizontal"); //-1, 0, 1
Debug.LogFormat("=> {0}", (int)h);
//좌우 반전 , 왼쪽 h값이 -1
if (h != 0)
{
this.transform.localScale = new Vector3(h, 1, 1);
}
this.anim.SetInteger("Direction", (int)h);
direction 이 notEquls =0 이면 idle-> run
direction이 equls=0 이면 run-> idle 로 잘 실행됨
2. 두번째 방법 (moveposition)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HeroController : MonoBehaviour
{
private Animator anim;
private Rigidbody2D rBody2D;
public float moveSpeed = 1f; // 속도를 인스펙터에서 수정하기 위해서 따로 위로 뺌
// Start is called before the first frame update
void Start()
{
this.anim = this.GetComponent<Animator>();
this.rBody2D = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxisRaw("Horizontal"); //-1, 0, 1
Debug.LogFormat("=> {0}", (int)h);
//좌우 반전 , 왼쪽 h값이 -1
if (h != 0)
{
this.transform.localScale = new Vector3(h, 1, 1);
}
//this.anim.SetInteger("Direction", (int)h);
//2번째 방법
var dir = new Vector2(h, 0); //방향
//this.rBody2D.MovePosition(방향*속도*시간)
var movement = dir * this.moveSpeed * Time.deltaTime;
Debug.Log(movement);
this.rBody2D.MovePosition(this.rBody2D.position+ movement);
anim.SetFloat("Speed", Mathf.Abs(movement.x));
}
}
animator 의 parameter에 speed 추가
오류남-> hero에 rigid바디를 추가 안해서 그런것이었음 추가 후 해결
idle에서 run으로 바뀌지 않음 -> log에 찍히는 값을 보고 conditions의 값을 바꾸니 해결
캐릭터가 뛰는 도중 튀는 현상( 값이 0이 되지도 않고 animation만든거에 문제가 없는데도 run에서 idle로 전환되는 문제)
-> anim.SetFloat("Speed", Mathf.Abs(movement.x)); 여기서 문제가 있음 --> 캐릭터의 movespeed를 높히니까 튀는 현상이 사라짐
3. 3번째 방법 (velocity)
//3번째 방법
var velocityX = moveSpeed * Input.GetAxisRaw("Horizontal");
this.rBody2D.velocity = new Vector2(velocityX, 0);
Debug.Log(velocityX);
anim.SetFloat("Speed", Mathf.Abs(this.rBody2D.velocity.x));
-> 문제 없이 잘 실행됨
4. 4번째 방법(moveforce)
'유니티 기초' 카테고리의 다른 글
unity 2d 복습 (0) | 2023.08.03 |
---|---|
hero 달리고 점프 (0) | 2023.08.03 |
고양이 구름 (0) | 2023.08.02 |
고양이 구름 올라가기 게임 (0) | 2023.08.02 |
고양의 체력을 적용하고 체력이 0이 되었을경우에 GameOver를 화면에 출력해라! (0) | 2023.08.02 |