【问题标题】:Make ball Jumping让球跳跃
【发布时间】:2015-06-23 05:18:42
【问题描述】:

我正在尝试制作一个可以水平和垂直移动球的脚本。我设法让它发挥作用。

但现在我想让我的球“跳”起来。我以下面的脚本结束,但现在我的球就像火箭一样发射了 xD

谁能帮帮我

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour 
{
    public float speed;
    public float jumpSpeed;
    public GUIText countText;
    public GUIText winText;
    private int count;

    void Start()
    {
        count = 0;
        SetCountText();
        winText.text = " "; 
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);
        Vector3 jump = new Vector3 (0, jumpSpeed, 0);

        GetComponent<Rigidbody>().AddForce (movement * speed * Time.deltaTime);

        if (Input.GetButtonDown ("Jump"));
        GetComponent<Rigidbody>().AddForce (jump * jumpSpeed * Time.deltaTime);

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "PickUp") {
            other.gameObject.SetActive(false);
            count = count +1;
            SetCountText();
        }
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
        if (count >= 10) 
        {
            winText.text = "YOU WIN!";
        }
    }
}

【问题讨论】:

  • 我似乎记得读过,对于跳跃,你最好设置速度而不是试图给角色施加冲动

标签: c# unity3d


【解决方案1】:

跳跃不适用于在物体上添加连续力。当第一次按下跳跃按钮时,您必须对对象施加一次脉冲。这个脉冲也不包括时间因素,因为它只应用一次。所以你会得到这样的东西:

bool jumping;

if (Input.GetButtonDown ("Jump") && !this.jumping);
{
    GetComponent<Rigidbody>().AddForce (jumpForce * new Vector3(0,1,0));
    this.jumping = true;
}

还请注意,在您的示例中,您将向上的单位向量乘以 jumpspeed 两次。一次在jump 向量初始化中,然后一次在AddForce 方法中。

当然,您还必须确保施加重力以将物体拉回原处(如果物体撞到地面,请重置跳跃布尔值。

一般来说,根据您制作的游戏类型,自己设置对象的速度会更容易,不要使用 Unity 物理引擎进行一些简单的移动。

【讨论】:

  • 谢谢,这非常有用。我决定使用速度部分。
【解决方案2】:

函数FixedUpdate中你的代码有错误:

if (Input.GetButtonDown ("Jump"));

这样,您将在每一帧对您的对象施加一个力,因为分号从条件中排除了下面的行。只要在 RigidBody 组件上启用了 UseGravity,通过删除分号,您将在跳转的情况下获得正确的 if 实现。

if (Input.GetButtonDown ("Jump"))
    GetComponent<Rigidbody>().AddForce (jump * jumpSpeed * Time.deltaTime);

希望对你有帮助。

【讨论】:

    【解决方案3】:

    谢谢大家,帮了大忙。我现在有一个跳跃的角色。只有在接地时才能跳跃的人。

    public bool IsGrounded;
    
        void OnCollisionStay (Collision collisionInfo)
    {
        IsGrounded = true;  
    }
    
    void OnCollisionExit (Collision collisionInfo)
    {
        IsGrounded = false;
    }
    
    
    if (Input.GetButtonDown ("Jump") && IsGrounded)
        {
            GetComponent<Rigidbody>().velocity = new Vector3(0, 10, 0);
        }
    

    【讨论】:

      猜你喜欢
      • 2021-07-05
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多