2016-07-07 11 views
1

캐릭터 컨트롤러 스크립트를 만들고 있는데 모든 것이 잘 작동하고 있지만 일단 플레이어가 떨어지기 시작하면 갑작스러운 동작이 멈추는 문제가 있습니다.Unity에서 부드럽게 빠져 나옴 - C#

using UnityEngine; 
using System.Collections; 

public class CharacterController : MonoBehaviour { 

    public float inputDelay = 0.1f; 
    public float forwardVel = 12; 
    public float rotateCel = 12; 
    public float JumpHeight = 20; 
    public Vector3 Gravity = new Vector3 (0, -180, 0); 
    public bool CanPress; 
    private float jumpTime; 
    public float _initialJumpTime = 0.4f; 
    //[HideInInspector] 
    public bool isGrounded; 
    Quaternion targetRotation; 
    Rigidbody rBody; 
    Vector3 forwardInput, turnInput; 
    public bool HasJumped; 

    public Quaternion TargetRotation 
    { 
     get {return targetRotation;} 
    } 
    // Use this for initialization 
    void Start() { 
     Physics.gravity = Gravity; 
     targetRotation = transform.rotation; 
     if (GetComponent<Rigidbody>()) 
      rBody = GetComponent<Rigidbody>(); 
     else { 
      Debug.LogError("Character Needs Rigidbody"); 
     } 

    // forwardInput = turnInput = 0; 
     forwardInput = turnInput = Vector3.zero; 
    } 

    // Update is called once per frame 
    void Update() { 

     GetInput(); 
     //Turn(); 

     if (CanPress == true) { 
      if (Input.GetKeyDown (KeyCode.Space)) { 
       HasJumped = true; 
       jumpTime = _initialJumpTime; 
      } 
     } 

     if (HasJumped == true) { 
      rBody.useGravity = false; 
      jumpTime -= 1 * Time.deltaTime; 
      if (jumpTime > 0) { 
      Jump(); 
      } 
      else { 
       HasJumped = false; 
       rBody.useGravity = true; 
      } 
     } 
    } 


    void GetInput() { 
     //forwardInput = Input.GetAxis ("Vertical"); 
     //turnInput = Input.GetAxis ("Horizontal"); 
     forwardInput = new Vector3 (Input.GetAxis ("Horizontal") * rotateCel, 0, Input.GetAxis ("Vertical") * forwardVel); 
     forwardInput = transform.TransformDirection (forwardInput); 
     if (Input.GetKeyUp (KeyCode.Space)) { 
      //HasJumped = false; 
     } 


    } 

    void Jump() { 

      Vector3 up = transform.TransformDirection (Vector3.up); 
     GetComponent<Rigidbody>().AddForce (up * 5, ForceMode.Impulse); 

    } 
    void FixedUpdate() { 

     Run(); 
    } 
    void Run() { 
     if (Mathf.Abs (10) > inputDelay) { 
      //Move 
      //rBody.velocity = transform.forward * forwardInput * forwardVel; 
      rBody.velocity = forwardInput; 
     } else { 
      //zero velocity 
      rBody.velocity = Vector3.zero; 

     } 

    } 
    void Turn() { 
    // targetRotation *= Quaternion.AngleAxis (rotateCel * turnInput * Time.deltaTime, Vector3.up); 
    // transform.rotation = targetRotation; 
    } 

    void OnTriggerEnter(Collider col) { 
     isGrounded = true; 
     CanPress = true; 
    } 

    void OnTriggerExit(Collider col) { 
     isGrounded = false; 
     CanPress = false; 
    } 

} 

내 캐릭터가 중력을 사용하여 X, Y, 회전에 대한 Z 제약이있는 강체 attactches있다 - 나는 점차 아래로 떨어 플레이어를 원하는이 내 캐릭터 제어기 스크립트입니다.

  • 플레이어는 부드럽게 올라가고 부드럽게 떨어지지 만 두 사람 사이의 전환은 매우 갑작스럽고 갑작 스럽습니다.

도움 주셔서 감사합니다. :)

+0

자신 만의 캐릭터 컨트롤러를 구축하고 있습니까? 왜 당신이 유니티 스탠다드 에셋의 일부로 내장 된 캐릭터 컨트롤러를 사용하지 않는지 궁금하다면 :-) – Tom

+0

안녕하세요, @Tom, 저는이 모든 것을 학습 경험은 단결의 inbuilt 스크립트를 항상 사용하고 싶지 않고, 내 자신의 스크립트를 만들어 내 게임 요구에 맞게 스크립트를 변경할 수있는 옵션을 제공합니다. –

답변

1

좋아, 그래서 나는 당신의 코드를 가져 와서 연극을했다.

나는이 문제가 귀하의 Run() 기능에서 점프에 영향을 미치는 rigidbody의 속도를 변경하고 있다고 생각합니다.

나는 그 물건을 꺼내 스크립트를 약간 개선하고 테스트했습니다. 이것을 rigidbody으로 캡슐에 붙이고 바닥에 바닥에 box collider을 꽂아 둡니다. 그러면 부드럽게 점프해야합니다.

새 (틱) 스크립트를 점

using UnityEngine; 
using System.Collections; 

public class CharacterController : MonoBehaviour 
{ 
    public float inputDelay = 0.1f; 
    public float forwardVel = 12; 
    public float rotateCel = 12; 
    public float jumpHeight = 10; 
    private float jumpTime; 
    public float _initialJumpTime = 0.4f; 
    //[HideInInspector] 
    public bool isGrounded; 
    Quaternion targetRotation; 
    Rigidbody rBody; 
    Vector3 forwardInput, turnInput; 
    public bool canJump; 

    public Quaternion TargetRotation 
    { 
     get { return targetRotation; } 
    } 

    void Start() 
    { 
     targetRotation = transform.rotation; 
     if (GetComponent<Rigidbody>()) 
      rBody = GetComponent<Rigidbody>(); 
     else 
     { 
      Debug.LogError("Character Needs Rigidbody"); 
     } 

     // forwardInput = turnInput = 0; 
     forwardInput = turnInput = Vector3.zero; 
    } 

    void Update() 
    { 
     GetInput(); 
     //Turn(); 

     if (Input.GetKeyDown(KeyCode.Space) && canJump) 
     { 
      rBody.AddForce(Vector3.up * jumpHeight, ForceMode.Impulse); 
     } 
    } 


    void GetInput() 
    { 
     //forwardInput = Input.GetAxis ("Vertical"); 
     //turnInput = Input.GetAxis ("Horizontal"); 
     forwardInput = new Vector3(Input.GetAxis("Horizontal") * rotateCel, 0, Input.GetAxis("Vertical") * forwardVel); 
     forwardInput = transform.TransformDirection(forwardInput); 
    } 

    void FixedUpdate() 
    { 
     //Run(); 
    } 

    void Run() 
    { 
     //HERE YOU SET THE RIGIDBODYS VELOCITY, WHICH IS CAUSING YOUR JUMP TO NOT WORK PROPERLY. DO NOT MODIFY THE VELOCITY 
     //OF A RIGIDBODY 
     if (Mathf.Abs(10) > inputDelay) 
     { 
      //Move 
      //rBody.velocity = transform.forward * forwardInput * forwardVel; 
      rBody.velocity = forwardInput; 
     } 
     else 
     { 
      //zero velocity 
      rBody.velocity = Vector3.zero; 
     } 
    } 

    void Turn() 
    { 
     // targetRotation *= Quaternion.AngleAxis (rotateCel * turnInput * Time.deltaTime, Vector3.up); 
     // transform.rotation = targetRotation; 
    } 

    void OnCollisionEnter(Collision col) 
    { 
     isGrounded = true; 
     canJump = true; 
    } 

    void OnCollisionExit(Collision col) 
    { 
     isGrounded = false; 
     canJump = false; 
    } 
} 

커플 :

  • 이름 당신의 변수 inThisKindOfFashion (jumpHeight, isOnGround, camelCaseExample), 대문자로 시작하는 변수를 가진 GravityJumpHeight과 같이 혼동을 줄 수 있습니다.

  • 누군가 내 질문에 대해 한 번 대답 했으므로, 무엇을하고 있는지 알지 못하면 강체의 속도를 수정하지 마십시오! 이상하게 보입니다.하지만 그 조언을 따른 후에 나는 결코 문제가 없었습니다!

  • 스크립트에서 나는 OnTrigger 대신 OnCollision을 사용했습니다. , rigidbody으로 capsule 밑에 box collider 바닥을 놓고이 스크립트를 켜면 캐릭터가 땅에 멈추게됩니다. 방아쇠를 사용하면 쓰러 질 것입니다. (적어도 내 경험으로는)

해피 코딩!:-)


편집 는 귀하의 의견에 응답하려면 :

을 "어떻게 내가 플레이어를 이동 되죠"

운동은 다양한 방법으로 수행 할 수 있습니다 하지만 조금씩 다르게해야하는 경우가 아니면 일반적으로 항상이 옵션을 사용합니다.

void Update() 
{ 
    if (Input.GetKeyDown(KeyCode.LeftArrow)) 
    { 
     transform.position += Vector3.left * speed * Time.deltaTime; //speed could be 5f, for example (f means float); 
    } 

    // then do the same for other directions, RightArrow -.right, UpArrow - .forward, DownArrow - .back 
} 

당신은 더 높거나 더 작은 점프의 jumpHeight 변수를 변경할 수 있습니다 "나는 조정 어떻게 플레이어는 점프 얼마나 빨리". 더 빠르게 빠져 나가는 것이 더 빠르다면 편집> 프로젝트 설정> 물리학>으로 이동하여 Y 중력을 -20과 같이 더 작은 것으로 변경하십시오.

자습서

here 그들은 자습서의 다양한 있고, 당신은 단지 비디오 다음과 함께 넣을 수 있도록 예제 프로젝트와 함께 사람이 있어도 찾을 수 있습니다.

+0

와우, 고마워요 @ 톰, 그 충고를 마음에 받아 들일 것입니다 :) 코드를 테스트하고 작동하는지 알려 드리겠습니다. :) –

+0

괜찮습니다! :-) – Tom

+0

어이 @ 톰 점프 지금 큰 작품. 몇 가지 질문 - Rigidbody를 사용하거나 Vector3.Lerp를 사용하여 플레이어를 어떻게 움직일 것을 제안합니까? 어떻게 플레이어가 점프하는 속도를 조절할 수 있습니까? 그리고 나는 단지 13 살이 기 때문에 코딩에 많은 경험이 없으므로 C# 코딩을 자세히 가르치는 웹 사이트 또는 자습서가 있습니까? 시간을내어 도와 주셔서 대단히 감사합니다. 해피 코딩! : D –