본문 바로가기
컴퓨터&빅데이터&AI/프로그래밍및컴퓨터공학교재추천

유니티 점프할때 떠있는 도중에도 방향키가 먹히는 문제

by 먀로쟝 2022. 1. 4.
728x90

이미지 출처 https://www.pixiv.net/artworks/95096409

그 문제를 없애기 위해 h, v를 전역변수로 뺀다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody rigid;

    public int JumpPower = 10;
    public int MoveSpeed = 10;

    public float h = 0.0f;
    public float v = 0.0f;

    private bool IsJumping;
    // Start is called before the first frame update
    void Start()
    {
        rigid = GetComponent<Rigidbody>();
        IsJumping = false;
    }

    // Update is called once per frame
    void Update()
    {
        Move();
        Jump();
    }

    private void Move()
    {
        
        if (!IsJumping)
        {
            h = Input.GetAxis("Horizontal");
            v = Input.GetAxis("Vertical");
        }
        transform.Translate(new Vector3(h, 0, v) * MoveSpeed * Time.deltaTime);
        
    }

    void Jump()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            if(!IsJumping)
            {
                IsJumping = true;
                rigid.AddForce(Vector3.up * JumpPower, ForceMode.Impulse);
            }
            else
            {
                return;
            }
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag("Ground")) {
            IsJumping = false;
        }
    }
}

댓글