【发布时间】:2019-04-03 13:27:39
【问题描述】:
我正在创建 2D 自上而下的射击游戏。我得到了我希望我的子弹从墙上反弹的点。我正在使用 OnCollisionEnter2D 和rigidbody2D。子弹在撞墙后会反弹,但它们会绕着自己的轴旋转。我尝试了很多方法,但无法让这个工作。
这就是它在实践中的样子:
这是我的子弹代码和弹跳孩子的代码。
public class GunBullet : MonoBehaviour
{
[HideInInspector] public PlayerAvatar ownerPlayerAvatar;
SpriteRenderer spriteRenderer;
public int damage = 15;
[SerializeField] float bulletSpeed;
Rigidbody2D rigidbody;
public void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
rigidbody.velocity = transform.right * BulletSpeed;
}
}
public class RicochetMode : MonoBehaviour
{
Rigidbody2D rigidbody2D;
GunBullet gunBullet;
private void Start()
{
rigidbody2D = transform.root.GetComponent<Rigidbody2D>();
gunBullet = transform.root.GetComponent<GunBullet>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Obstacle"))
{
Debug.Log("RICOCHET");
Vector2 reflectedPosition = Vector3.Reflect(transform.right, collision.contacts[0].normal);
rigidbody2D.velocity = (reflectedPosition).normalized * gunBullet.BulletSpeed;
Vector2 dir = rigidbody2D.velocity;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
rigidbody2D.MoveRotation(angle);
}
}
}
我希望子弹朝向正确的方向。而且我不想使用统一的 2D 物理材料。
编辑。
问题的解决方法是设置
正如@trollingchar 所说,rigidbody2D.angularVelocity 为零。
【问题讨论】:
-
他们建议仅将 MoveRotation 用于小角度 (docs.unity3d.com/ScriptReference/Rigidbody2D.MoveRotation.html),这不是子弹反射回来的情况。可以直接设置旋转。
-
我正在尝试rigidbody.rotate = angle,但这似乎不起作用。
-
rotation,而不是rotate。如果这不起作用,请尝试设置transform.localRotation或transform.rotation。 -
是的,当然我的意思是轮换。这些似乎也不起作用,也许我应该提到子弹的刚体是动态的。
-
也许他们正在旋转,因为统一的内部碰撞处理认为它必须改变
angularVelocity作为碰撞的结果。里面有什么价值? (如果不为零,则在碰撞处理中手动将其设置为零)
标签: c# unity3d collision-detection game-physics