[英]How to make a Rigidbody2D bullet move in Unity2D
几天来我一直在尝试各种修复程序,但我无法弄清楚。 我需要一颗子弹来生成并移动直到碰撞,但我什至无法让它移动(它生成得很好)。 注意:这是一个 2D 游戏。 这是我的代码:
public class Enemy : MonoBehaviour
{
public float timeBetweenFire = 2;
public Rigidbody2D bullet;
public Transform gunSpawn;
private float timer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update() {
timer+=Time.deltaTime;
if (timer >= timeBetweenFire) {
Shoot();
timer = 0;
}
}
private void Shoot() {
Rigidbody2D bulletInstance;
bulletInstance = Instantiate(bullet, gunSpawn.position, gunSpawn.rotation) as Rigidbody2D;
//bulletInstance.AddForce(gunSpawn.forward * 1000f);
//bulletInstance.AddForce(Vector3.up * 10 * Time.deltaTime);
//bulletInstance.AddForce(transform.forward * 100);
bulletInstance.AddForce(Vector3.up * 1000);
}
}
注释过的 bulletInstance 方法是我最近尝试过的,我对子弹进行了一系列大规模的代码更改(iirc 在刚体、游戏对象和变换之间进行了更改),但没有任何帮助。 子弹的生成距离除了 gunSpawn 之外的任何东西都有很大的距离,它只是一个空的游戏对象,所以我认为碰撞不是问题。 我是一名新的 Unity 程序员,所以请原谅我的任何愚蠢错误。
更新:这是我为使其(主要)工作所做的。 当子弹相撞时它可以旋转出来,但至少我取得了一些进展。
public class Deflect : MonoBehaviour
{
private Rigidbody2D bullet;
public float bulletSpeed = 0.1f;
Vector2 direction = new Vector3(0.7f,0.7f);
ContactPoint2D[] myContact = new ContactPoint2D[1];
Vector2 _velocity;
public void Update ()
{
}
// Start is called before the first frame update
void Start()
{
bullet = this.GetComponent<Rigidbody2D>();
_velocity = bullet.velocity;
}
void OnCollisionEnter2D(Collision2D collision)
{
foreach (ContactPoint2D contact in collision.contacts)
{
print(contact.collider.name + " hit " + contact.otherCollider.name);
// Visualize the contact point
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
Vector2 inNormal = collision.contacts[0].normal;
_velocity = Vector3.Reflect(_velocity, inNormal);
bullet.velocity = _velocity;
}
}
确保子弹具有刚体组件并且未设置为运动学。
1 - 将您的子弹预制件创建为GameObject
2 - 添加一个RigidBody2D
到它
3 - 确保在 Rigibody2d 上未选中Rigibody2d
4 - 然后GameObject bulletInstance = Instantiate(bullet, gunSpawn.position,gunSpawn.rotation); bulletInstance.GetComponent<Rigidbody2D>().AddForce(Vector3.up * 1000);
IsKinematic 防止Rigidbody2D
受到力的影响。
https://docs.unity3d.com/ScriptReference/Rigidbody-isKinematic.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.