2016-12-23 42 views
1

我试图添加跳到我们的控制脚本的控制,但它只是不工作,我有点沮丧,因为我试了很多,使其工作。我不使用刚体,而是想使用基于脚本的物理和 - 但后来 - 射线广播(检测地面)。它是3D的,但具有固定的角度,因为角色是精灵(我们正在考虑尝试类似于不饿,纸马里奥等)的风格。而我现在要放入的东西是当角色静止不动,然后跳跃时跳跃向上,当角色移动时角色也会移动一段距离。那么,你得到的照片。为此,我首先需要跳跃式的工作 - 也有重力让角色倒退,同时也考虑到角色可能会落在与起始场地高度不同的地面上。 现在发生的情况是,角色跳跃只是一点点,就像跳跃一样,然后无休止地跌倒 - 或者在再次按下跳跃时无限上升。那么,我该如何解决这个问题?跳跃没有刚体统一

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

public class Controls3D : MonoBehaviour 
{ 

    public float player3DSpeed = 5f; 
    private bool IsGrounded = true; 
    private const float groundY = (float) 0.4; 
    private Vector3 Velocity = Vector3.zero; 
    public Vector3 gravity = new Vector3(0, -10, 0); 

    void Start() 
    { 
    } 

    void Update() 
    { 
     if (IsGrounded) 
     { 
      if (Input.GetButtonDown("Jump")) 
      { 
       IsGrounded = false; 
       Velocity = new Vector3(Input.GetAxis("Horizontal"), 20, Input.GetAxis("Vertical")); 
      } 
      Velocity.x = Input.GetAxis("Horizontal"); 
      Velocity.z = Input.GetAxis("Vertical"); 
      if (Velocity.sqrMagnitude > 1) 
       Velocity.Normalize(); 
      transform.position += Velocity * player3DSpeed * Time.deltaTime; 
     } 
     else 
     { 
      Velocity += gravity * Time.deltaTime; 
      Vector3 position = transform.position + Velocity * Time.deltaTime; 
      if (position.y < groundY) 
      { 
       position.y = groundY; 
       IsGrounded = true; 
      } 
      transform.position = position; 
     } 
    } 
} 
+0

无尽的倒下问题解决了。只需要设置Velocity.y = 0;在transform.position = position之后;在IsGrounded = true下; – Gota

+1

如果你经过我打赌,你会看到初始速度比你想象的要小,因为'Velocity.Normalize();',所以你的Velocity.y是-1和1之间的某个数。我认为你的向上速度应该与其他两个方向无关,或者,您应该每次修改速度时都要将速度标准化,而不是仅在接地时进行。也就是说,为什么在停滞的情况下正常化,而不是在这里:'Velocity + = gravity * Time.deltaTime;'? – Quantic

+0

我想我现在得到了一些东西,谢谢。 – Gota

回答

0

如果我是你,我想我wouldve改变了整个事情变成角色管理,因为这样简化的过程中,一个####吨:P

如果你找出你想使用CC。这是解决我通常使用:

CharacterController controller = GetComponent<CharacterController>(); 
    // is the controller on the ground? 
    if (controller.isGrounded) 
    { 
     //Feed moveDirection with input. 
     moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); 
     moveDirection = transform.TransformDirection(moveDirection); 



     //Multiply it by speed. 
     moveDirection *= speed; 
     //Jumping 
     if (Input.GetButton("Jump")) 
      moveDirection.y = jumpSpeed; 

    } 
    //Applying gravity to the controller 
    moveDirection.y -= gravity * Time.deltaTime; 
    //Making the character move 
    controller.Move(moveDirection * Time.deltaTime); 

moveDirection是一个的Vector3类型可变的,并且速度和jumpSpeed是用于修改速度公共浮点值。

请注意:字符控制器,让你编程自己的物理。