我在Unity的立方体上使用了rigibody2D。我有一个恒定的力量来缓慢增加速度:
rigidbody2D.AddForce (Vector2.right * speed * Time.deltaTime)
这样可以正常工作,但是,现在和它们(看似完全随机),速度重置为0或进入负值。以下是该类的代码:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed;
public float jumpForce;
private bool isGrounded;
// Use this for initialization
private void Start()
{
}
// Update is called once per frame
private void Update()
{
rigidbody2D.AddForce (Vector2.right * speed * Time.deltaTime);
if (Input.GetMouseButton(0)) {
Jump();
}
Debug.Log(rigidbody2D.velocity);
}
public void reverseSpeed(){
speed = -speed;
}
private void OnCollisionEnter2D(Collision2D c)
{
if (c.gameObject.tag == "Floor")
{
isGrounded = true;
}
if (c.gameObject.tag == "Inverting") {
reverseSpeed ();
//TODO: Needs to match old speed better
rigidbody2D.AddForce ((-c.relativeVelocity * rigidbody2D.mass) * Time.deltaTime);
//Try just reversing velocity directly
}
}
private void OnCollisionExit2D(Collision2D c)
{
if (c.gameObject.tag == "Floor")
{
isGrounded = false;
}
}
private void Jump()
{
//Need changing
rigidbody2D.AddForce(transform.up * (jumpForce/ Time.deltaTime));
}
}
我检查对象上是否有任何组件导致这种情况,但据我所知,没有任何内容。
编辑:我做了更多测试,但这绝不是因为与另一个物体碰撞造成的。