简体   繁体   English

如何在Unity中向移动对象(向后)施加力

[英]How to add force in (backward direction) to an moving object in Unity

I have a player that is moving forward with constant speed and I have attached a rigidbody to that object. 我有一个以恒定速度向前移动的播放器,并且已在该对象上附加了刚体。 So I want that when player hit with other collider then a force should be apply on player to move it in backward direction. 因此,我希望玩家在与其他对撞机撞击时向其施加力使其向后移动。 here below is my script that is attached with my player. 下面是我的播放器附带的脚本。 The print statement is executing so it mean that the Trigger function is working and rigidbody is attached to the player, but the addforce() function is not working. print语句正在执行,因此意味着Trigger函数可以正常工作,并且刚体连接到播放器,但是addforce()函数无法正常工作。 Please help me. 请帮我。

void OnTriggerEnter(Collider obj)
{
    if (obj.gameObject.name == "enemy")
    {
        if(gameObject.GetComponent<Rigidbody>())
        {
            print("force add");
            gameobject.getcomponent<RigidBody>().AddForce (-transform.forward * 10f * Time.deltaTime); 
        }
    } 
}

Ok, first try apply higher value, it's possible that force is too low, bacause it's multiply by Time.deltaTime which is low value: 好的,首先尝试应用更高的值,可能是力太低,因为它乘以Time.deltaTime这是低值:

.AddForce (-transform.forward * 10000f * Time.deltaTime);

Second check, if you change position of the player with transform.position anywhere in your code. 第二次检查,是否在代码中的任何位置使用transform.position更改播放器的位置。 (If yes paste this parts of code) (如果是,请粘贴这部分代码)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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