Move_Flip
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move_Flip : MonoBehaviour
{
// 좌우반전
// 전역변수 선언
Rigidbody2D rb;
public float speed = 5; // 좌우이동시 이동 속도
public float power = 5; // 점프력
float vx = 0; // 좌우방향키 누르고있는지 여부(오른쪽 +1, 왼쪽 -1)
bool isJumping = false; // 점프여부
bool groundFlag = false; // 발이 무언가에 닿아있는지 여부
void Start() // 유니티 실행하자마자 처음 한번만 실행. 초기화
{
// 리지드바디 컴포넌트 가져오기
rb = GetComponent<Rigidbody2D>();
// 충돌후 회전시키지 않기
rb.constraints = RigidbodyConstraints2D.FreezeRotation;
}
void Update() // 판정
{
vx = 0; // 초기화 (방향키 안눌렸을때는 정지하기)
// 좌우방향키 눌림 여부
if (Input.GetKey("right"))
{
vx = 1;
}
else if (Input.GetKey("left"))
{
vx = -1;
}
// 스페이스키 눌려지면서 오브젝트가 지면에 있을때만 점프가능
if (Input.GetKey("space") && groundFlag==true)
{
isJumping = true;
}
else
{
isJumping = false;
}
}
void FixedUpdate() // 실제 행동(물리력이용)
{
// 좌우방향 이동
rb.velocity = new Vector2(vx * speed, rb.velocity.y);
Debug.Log(rb.velocity.y);
// 반전하기
if(vx != 0)
{
transform.localScale = new Vector2(vx, 1);
}
// 점프하기
if (isJumping)
{
rb.AddForce(transform.up*power, ForceMode2D.Impulse);
isJumping = false;
}
}
void OnTriggerStay2D(Collider2D collision)
{
groundFlag = true;
}
void OnTriggerExit2D(Collider2D collision)
{
groundFlag = false;
}
}
'----------고1---------- > 게임엔진' 카테고리의 다른 글
[고1 게임엔진] 09 - (3) (0) | 2023.09.13 |
---|---|
[고1 게임엔진] 09 - (2) (3) | 2023.09.11 |
[고1 게임엔진] 08 - (1) (0) | 2023.08.30 |
[고1 게임엔진] 08 - (3) (0) | 2023.08.30 |
[고1 게임엔진] 08 - (2) (0) | 2023.08.28 |