首页 > 解决方案 > 物体不动,如何让子弹动起来

问题描述

我制造了一个会向玩家射击的敌人。我在水池出现时转动它并尝试启动它,但由于某种原因它没有移动

我有两个用于子弹脚本的脚本,一个用于射击子弹的敌人的脚本

起初,我试图在AddForce(transform.up * Speed); 图片

对于子弹

public class BulletScript : MonoBehaviour
{

    public GameObject bullet;

    void Start()
    {
        bullet.transform.Translate(bullet.transform.forward * Time.deltaTime);
    }

}

为敌人

public class TurelScript : MonoBehaviour
{

    public Transform Player;
    public Transform Turell;
    public GameObject PrefabOfbullet;
    public Transform BUlletPosition;

    public float Rotation;

    void Start()
    {
        var turnOfBullet = Quaternion.Lerp(BUlletPosition.rotation, Quaternion.LookRotation(Vector3.forward, Player.position - BUlletPosition.position), Time.deltaTime * 40f);
        var rigidbodyBullet = GetComponent<Rigidbody2D>();


        StartCoroutine(BulletSpawn());
    }

    // Update is called once per frame
    void Update()
    {
        var turn = Quaternion.Lerp(Turell.rotation, Quaternion.LookRotation(Vector3.forward, Player.position - Turell.position), Time.deltaTime * 4f);
        var rigidbody = GetComponent<Rigidbody2D>();


        rigidbody.MoveRotation(turn.eulerAngles.z);
    }


    IEnumerator BulletSpawn()
    {
        while (true)
        {
            Instantiate(PrefabOfbullet, BUlletPosition.position, Turell.rotation);
            yield return new WaitForSeconds(0.3f);
        }
    }
}

标签: c#unity3d

解决方案


由于子弹似乎是Rigidbody2D您根本不应该使用Transform.Translate 的,而只能通过Rigidbody2D组件更改它并且FixedUpdate不破坏物理。(见Rigidbody2D.MovePosition

然后对于你几乎不想使用AddForce的子弹,它需要知道子弹的质量并相应地计算所需的力。

你会立即改变它velocity,所以宁愿做类似的事情

// Having the correct type allows you only to reference
// Object that actually have this type
// And second you don't need `GetComponent` on runtime
public Rigidbody2D PrefabOfBullet;

// Set the speed you want in Unity Units / second
public float BulletSpeed = 1f;

...

var bullet = Instantiate (PrefabOfBullet, Bullet position.position, Turell.rotation);
bullet.velocity = bullet.transform.up * BulletSpeed;

...

推荐阅读