简体   繁体   中英

rb.addforce not responding even though collision works

how are you doing? I am working on a simple mechanic of knockback where if my character collides with the name "enemy", the players rigidbody which is paraphrsased as (rb), has force added 'back'.

Here is my code, Please refer to where I outline with asterisk.

public class Move : MonoBehaviour {

public float speed;

private Rigidbody rb;

public int health;
private float knockback;


// Use this for initialization
void Start()
{
    rb = GetComponent<Rigidbody>();
    knockback = 2f;

}

void OnCollisionEnter(Collision col)
{
    if (col.gameObject.name == "enemy")
    {
        health = health - 20;  //**this works**
        rb.AddRelativeForce(Vector3.forward * knockback); //**but this doesnt :c **
    }
}

void death()
{
    if (health <= 0)
    {
        print("i died");
    }
}

void playerWalk()
{
    var x = Input.GetAxis("Horizontal") * Time.deltaTime * 75f;
    var z = Input.GetAxis("Vertical") * Time.deltaTime * 5f;

    transform.Rotate(0, x, 0);
    transform.Translate(0, 0, z);

}
void Update()
{
    death();
    playerWalk();

}

}

The problem is as you may have guessed, My triggers do not work. My health = health - 20; line works but my rb.addforce doesn't.

What could be the problem here? Thank you :)

edit 2#

Just want to edit this and say That I have figured out the problem. The problem was that my float value just was not high enough xD

As you wrote the snippet, ´rb´ is not a field, but a local variable inside the ´Start´ method. If you are getting an exception in the menctioned line, maybe it is because of this. If you want ´rb´ to be a field, accesible all arround the class methods, you'll need to declare it in the class body, like this:

public int health;
private float knockback;
private RigidBody rb;

// (...) the rest of your code

If this is not the case, just tell me and give us more info on your problem.

Try removing the deltaTime:

     rb.AddRelativeForce(Vector3.forward * knockback);

The default ForceMode for AddRelativeForce is AddForce and does not require time scaling.

我不是专家,但这是我的答案。...您将刚体附加到变换上。...因此将刚体位置更改为等于变换位置...您在更新中调用了两种方法...因此它们将被连续调用....因此,您可以使用向上箭头键向前移动变换方向。.但是,仅在碰撞进入处添加力...碰撞进入仅被调用一次,而playwalk方法则被连续调用...这就是为什么无法识别添加力的原因。 ...检查此链接http://unityweltech.blogspot.com/2018/09/rbforce-is-not-responding.html?m=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM