且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Unity 2D 中,我如何实现“物理上"不发生的非触发碰撞?移动刚体?

更新时间:2021-07-28 21:27:57

对于命中的位置,这很容易.你必须有 2 个碰撞器和 2 个刚体,然后你可以简单地添加一个Void OnTriggerEnter2D(Collision Coll) 并在其中检查标签:if(coll.compareTag(surface")) 并在内部您可以使用collision.transform.position 获取位置.物理菜单上的碰撞矩阵只允许去除某些层之间的碰撞,如果你不希望敌人互相推挤,这很有用!

For the position of the hit it's very easy. You must have 2 colliders and 2 Rigidbody and then you can simply add a Void OnTriggerEnter2D(Collision Coll) and inside it check for the tag : if(coll.compareTag("surface")) and inside you can get the position with collision.transform.position. The collision matrix on the Physics menu only allows to remove Collision between certain layers, it's useful if you want the enemies not to push eachother!

如果你不想让玩家被推动,你可以改变碰撞器来触发,并在碰撞后使用与之前相同的方法使用 void OnTriggerEnter2D 和 compareTag 销毁子弹.这样它看起来就像是碰到了敌人并爆炸了,但实际上并没有碰到任何东西.如果你想给玩家添加击退,那么你可以根据子弹的方向做一个简单的 AddForce 就完成了!

If you don't want the player pushed you can change the collider to trigger, and destroy the bullet just after the collision with the same method as before with a void OnTriggerEnter2D and the compareTag. In this way it will look like it touches the enemy and explode, but it won't actually touch anything. If you want to add knockback to the player then you could do a simple AddForce based on the direction of the bullet and the work is done!

如果你想避免子弹移动墙壁,你可以将墙壁设置为静态,它应该可以正常工作

If you want to avoid the bullet to move walls you can set walls to static and it should work fine