我正在尝试制作一个脚本,我可以在其中水平和垂直移动球。我设法让它发挥作用。
但现在我想让我的球“跳起来”。我以下面的脚本结束,但现在我的球像火箭一样发射 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!";
}
}
}
最佳答案
跳跃不适用于对物体施加持续的力。第一次按下跳跃按钮时,您必须对物体施加一次脉冲。该脉冲也不包括时间因素,因为它仅应用一次。所以你会得到这样的东西:
bool jumping;
if (Input.GetButtonDown ("Jump") && !this.jumping);
{
GetComponent<Rigidbody>().AddForce (jumpForce * new Vector3(0,1,0));
this.jumping = true;
}
另请注意,在您的示例中,您将向上单位向量乘以跳跃速度两次。一次进入 jump
向量初始化,然后一次进入 AddForce
方法。
当然,您还必须确保重力适用于将物体拉回原处(如果物体撞到地面,请重置跳跃 bool 值。
一般来说,根据您制作的游戏类型,您自己设置对象的速度会更容易,而不需要使用 Unity 物理引擎来做一些简单的四处移动。
关于c# - 让球跳跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088208/