728x90
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroController : MonoBehaviour
{
private Animator anim;
public Rigidbody2D rBody2D;
public float jumpForce;
public float moveSpeed;
private float moveForce = 1f;
private bool isJump = false;
// 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()
{
//방향 전환
//키보드 좌우 인풋을 받아 -1,0,1 출력
float h = Input.GetAxisRaw("Horizontal"); //-1,0,1
//h: 방향 의미하는 값
//Debug.LogFormat("===>{0}", (int)h);
//좌우반전 스케일의 X값을 -1로 한다. 이때 y,z의 값은 1이어야 함
//즉, 좌: (-1,1,1)
//우: (1,1,1)
if (h != 0)
{
//누른상태 좌(-1) 우(1) : 이동상태
this.transform.localScale = new Vector3(h, 1, 1);
//리지드바디가 없을 경우 이동?
//h : x축 방향
Vector3 dir = new Vector3(h, 0, 0);
//속도 : moveSpeed
//this.transform.Translate(방향 * 속도 * 시간);
this.transform.Translate(dir * moveSpeed * Time.deltaTime);
//애니메이션 전환
//멈춤 : 기본동작 h값이 0 즉, dir 값이 (0,0,0)벡터 = Vector3.zero
//이동 : 뛰는동작 h값이 0이 아니다. -1 또는 1일 경우
//Animator의 매개변수에 값을 할당하면
//Animator Controller의 transition에 설정된 condition에 의해 전환됨
this.anim.SetInteger("h", (int)h);
}
else
{
this.anim.SetBool("Idel", true);
}
//점프
if (Input.GetKeyUp(KeyCode.Space))
{
if (this.isJump == false)
{
Debug.Log("jump");
this.rBody2D.AddForce(Vector2.up * this.jumpForce, ForceMode2D.Impulse);
this.isJump = true;
}
}
if (this.isJump)
{
if (this.rBody2D.velocity.y > 0)
{
//점프하기
this.anim.SetBool("Jump", true);
}
else if (this.rBody2D.velocity.y < 0)
{
//내려오기
this.anim.SetBool("Fall", true);
}
else
{
this.anim.SetBool("Jump", false);
this.anim.SetBool("Fall", false);
this.anim.SetBool("Idle", true);
}
}
}
}
'KDT > 유니티 기초' 카테고리의 다른 글
23/08/04 유니티짱 대각선으로 이동 (0) | 2023.08.04 |
---|---|
23/08/04 유니티짱 직선으로 움직이기 (0) | 2023.08.04 |
23/08/02 키보드로 인풋 받아 이동하기 (0) | 2023.08.03 |
23/08/01 [수업과제] 표창 던지기 (0) | 2023.08.01 |
23/08/01 SwipeCar (0) | 2023.08.01 |