• 카테고리

    질문 & 답변
  • 세부 분야

    게임 프로그래밍

  • 해결 여부

    미해결

크로스헤어 문제

21.03.22 14:21 작성 조회수 404

1

크로스헤어를 하고 있는데 못 해결하고 있는 문제가

있습니다. 걷고 있으면 애니메이터에서 crosshair_idle 이랑

crosshair_walk를 계속해서 왔다갔다해요.

제가 한 부분까지 다 돌려서 봤는데 문제는 없는 것 같았어

요.

전체코드:(Playercontroller)

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

public class PlayerController : MonoBehaviour 
{
    //스피드 조정 변수
    [SerializeField]
    private float walkSpeed;

    [SerializeField]
    private float runSpeed;
    [SerializeField]
    private float crouchSpeed;
    private float applySpeed;

    [SerializeField]
    private float jumpForce;

    //상태 변수
    private bool isWalk = false;
    private bool isRun = false;
    private bool isCrouch = false;
    private bool isGround = true;

    //움직임 체크 변수
    private Vector3 lastPos;

    //앉았을 때 얼마나 앉을지 결정하는 변수
    [SerializeField]
    private float crouchPosY;
    private float originPosY;
    private float applyCrouchPosY;

    //땅 착지 여부
    private CapsuleCollider capsuleCollider;

    // 민감도
    [SerializeField]
    private float lookSensitivity;

    // 카메라 한계
    [SerializeField]
    private float cameraRotationLimit;
    private float crrentCameraRotationX = 0;

    //필요한 컴포넌트
    [SerializeField]
    private Camera theCamera;
    private Rigidbody myRigid;
    private GunController theGunController;
    private crosshair thecrosshair;

    // Start is called before the first frame update
    void Start()
    {
        capsuleCollider = GetComponent<CapsuleCollider>();
        myRigid = GetComponent<Rigidbody>();
        theGunController = FindObjectOfType<GunController>();
        thecrosshair = FindObjectOfType<crosshair>();

        applySpeed = walkSpeed;
        originPosY = theCamera.transform.localPosition.y;
        applyCrouchPosY = originPosY;
    }

    // Update is called once per frame
    void Update()
    {
        IsGround();
        TryJump();
        TryRun();
        TryCrouch();
        Move();
        Movecheck();
        cameraRotation();
        CharacterRotation();
    }

    private void TryCrouch()
    {
        if(Input.GetKeyDown(KeyCode.LeftControl))
        {
            Crouch();
        }
    }

    private void Crouch()
    {
        isCrouch = !isCrouch;
        thecrosshair.crouchingAnimation(isCrouch);

        if(isCrouch)
        {
            applySpeed = crouchSpeed;
            applyCrouchPosY = crouchPosY;
        }
        else
        { 
            applySpeed = walkSpeed;
            applyCrouchPosY = originPosY;
        }

        StartCoroutine(CrouchCoroutine());
    }

    IEnumerator CrouchCoroutine()
    {
        float _posY = theCamera.transform.localPosition.y;
        int count = 0;

        while(_posY != applyCrouchPosY)
        {
            count++; 
            _posY = Mathf.Lerp(_posYapplyCrouchPosY0.3f);
            theCamera.transform.localPosition = new Vector3(0_posY0);
            if(count > 15)
                break;
            yield return null;

        }
        theCamera.transform.localPosition = new Vector3(0applyCrouchPosY0f);
    }

    private void IsGround()
    {
        isGround = Physics.Raycast(transform.positionVector3.downcapsuleCollider.bounds.extents.y + 0.1f);
    }

    private void TryJump()
    {
        if(Input.GetKeyDown(KeyCode.Space) && isGround)
        {
            jump();
        }
    }

    private void jump()
    {
        if(isCrouch)
            Crouch();
        myRigid.velocity = transform.up * jumpForce;
    }

    private void TryRun()
    {
        if(Input.GetKey(KeyCode.LeftShift))
        {
            Running();
        }
        if(Input.GetKeyUp(KeyCode.LeftShift))
        {
            RunningCancel();
        }
    }

    private void Running()
    {
        if(isCrouch)
            Crouch();

        theGunController.CancelFineSight();

        isRun = true;
        thecrosshair.runningAnimation(isRun);
        applySpeed = runSpeed;
    }

    private void RunningCancel()
    {
        isRun = false;
        thecrosshair.runningAnimation(isRun);
        applySpeed = walkSpeed;
    }
    private void Move()
    {

        float _MoveDirX = Input.GetAxisRaw("Horizontal");
        float _MoveDirZ = Input.GetAxisRaw("Vertical");

        Vector3 _moveHorizontal = transform.right * _MoveDirX;
        Vector3 _moveVertical = transform.forward * _MoveDirZ;
        Vector3 _velocity = (_moveHorizontal + _moveVertical).normalized * applySpeed;

        myRigid.MovePosition(transform.position + _velocity * Time.deltaTime);
    }

    private void Movecheck()
    {
        if(!isRun && !isCrouch)
        {
            if(Vector3.Distance(lastPostransform.position) >= 0.01f)
                isWalk = true;
            else
                isWalk = false;

            thecrosshair.walkingAnimation(isWalk);
            Vector3 position = transform.position;
            lastPos = position;
        }
    }
    private void CharacterRotation()
    {
        float _yRotation = Input.GetAxisRaw("Mouse X");
        Vector3 _characterRotationY = new Vector3(0f_yRotation0f) * lookSensitivity;
        myRigid.MoveRotation(myRigid.rotation * Quaternion.Euler(_characterRotationY));

    }
    private void cameraRotation()
    {
        float _xRotation = Input.GetAxisRaw("Mouse Y");
        float _cameraRotationX = _xRotation * lookSensitivity;
        crrentCameraRotationX -= _cameraRotationX;
        crrentCameraRotationX = Mathf.Clamp(crrentCameraRotationX, -cameraRotationLimitcameraRotationLimit);

        theCamera.transform.localEulerAngles = new Vector3(crrentCameraRotationX0f0f);
    }
}

답변 7

·

답변을 작성해보세요.

2

dydybest님의 프로필

dydybest

질문자

2021.10.01

저... 해결했습니다!

Move()함수에 있는 _velocity를 함수안에다 놓지말고 젤 위에 작성해서 스크립트 내에서는 얼마든지 사용할 수 있게 한다음

MoveCheck() 함수를

void MoveCheck()

    {

        if (!isRun && !isCrouch && isGround)

        {

            if (velocity.magnitude >= 0.01f)

                isWalk = true;

            else

                isWalk = false;

 

            theCrosshair.WalkingAnimation(isWalk);

            lastPos = transform.position;

        }

    }

 

이렇게 위에 보이는 것처럼 적으시면 됩니다.

전 위치와 지금 위치의 거리를 이용하는 것이 아닌 속도를 이용하는 방식이죠.

그럼 도움이 됬으면 좋겠군요!

0

tlgh0903님의 프로필

tlgh0903

2023.02.27

private void MoveCheck()

{

if (!isRun && !isCrouch)

{

if (Input.GetAxisRaw("Horizontal") !=0 || Input.GetAxisRaw("Vertical") != 0)

isWalk = true;

else

isWalk = false;

theCrosshair.WalkingAnimation(isWalk);

lastPos = transform.position;

}

}

 

이렇게 하셔도됩니다

0

dydybest님의 프로필

dydybest

질문자

2021.09.28

안녕하세요.

저와 같은 문제를 격고 있는 사람이 많은 것 같군요.ㅠㅠ

저 같은 경우에는 아예 큰 결심을 하고 처음부터 다시하고 있어요.

하.... 예전에 했던 데까지 가는데 시간이 좀 걸릴 것 같아요.ㅠㅠ

0

JR피기님의 프로필

JR피기

2021.09.22

저도 같은 문제를 겪고 있는데 답변은 없는건가요? ㅠㅠ

0

dydybest님의 프로필

dydybest

질문자

2021.04.02

안녕하세요.

저와 똑같은 상황을 격고 계시군요ㅠㅠ

저 오류때문에 애니메이션도 실행이 재대로 안돼는 것 같습니다.

그리고 또 엄청 많은 오류를 겪고 있는데 해결이 안돼요ㅠㅠ

0

dydybest님의 프로필

dydybest

질문자

2021.03.22

전체코드:(HUD)

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

public class HUD : MonoBehaviour
{
    [SerializeField]
    private GunController theGunController;
    private Gun currentGun;

    [SerializeField]
    private GameObject go_BulletHUD;

    [SerializeField]
    private Text[] text_Bullet;

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

    private void CheckBullet()
    {
        currentGun = theGunController.GetGun();
        text_Bullet[0].text = currentGun.carryBulletCount.ToString();
        text_Bullet[1].text = currentGun.reloadBulletCount.ToString();
        text_Bullet[2].text = currentGun.currentBulletCount.ToString();
    }
}
끼얏호우님의 프로필

끼얏호우

2021.03.28

저도 동일한 이슈를 겪고있네요. 원인찾기가 너무 난해해서 일단 뒷전으로 하고 있는중입니다..

0

dydybest님의 프로필

dydybest

질문자

2021.03.22

전체코드:(crosshair)

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

public class crosshair : MonoBehaviour
{

    [SerializeField]
    private Animator animator;

    private float gunAccuracy;

    [SerializeField]
    private GameObject go_CrosshairHUD;

    public void walkingAnimation(bool _flag)
    {
        animator.SetBool("walking"_flag);
    }
    public void runningAnimation(bool _flag)
    {
        animator.SetBool("running"_flag);
    }

    public void crouchingAnimation(bool _flag)
    {
        animator.SetBool("crouching"_flag);
    }

    public void FireAnimation()
    {
        if(animator.GetBool("walking"))
            animator.SetTrigger("walk_fire");
        else if(animator.GetBool("crouching"))
            animator.SetTrigger("crouch_fire");
        else
            animator.SetTrigger("idle_fire");
    }

}