Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / item / weapon / bullet / Bullet.cs
  1. using Godot;
  2.  
  3. /// <summary>
  4. /// 子弹类
  5. /// </summary>
  6. public class Bullet : ActivityObject
  7. {
  8. /// <summary>
  9. /// 碰撞区域
  10. /// </summary>
  11. public Area2D CollisionArea { get; }
  12.  
  13. // 最大飞行距离
  14. private float MaxDistance;
  15.  
  16. // 子弹飞行速度
  17. private float FlySpeed;
  18.  
  19. //当前子弹已经飞行的距离
  20. private float CurrFlyDistance = 0;
  21.  
  22. public Bullet(string scenePath, float speed, float maxDistance, Vector2 position, float rotation, uint targetLayer) :
  23. base(scenePath)
  24. {
  25. CollisionArea = GetNode<Area2D>("CollisionArea");
  26. CollisionArea.CollisionMask = targetLayer;
  27. CollisionArea.Connect("area_entered", this, nameof(OnArea2dEntered));
  28.  
  29. FlySpeed = speed;
  30. MaxDistance = maxDistance;
  31. Position = position;
  32. Rotation = rotation;
  33. ShadowOffset = new Vector2(0, 5);
  34. }
  35.  
  36. public override void _Ready()
  37. {
  38. base._Ready();
  39. //绘制阴影
  40. ShowShadowSprite();
  41. }
  42.  
  43. protected override void PhysicsProcess(float delta)
  44. {
  45. //移动
  46. var kinematicCollision = MoveAndCollide(new Vector2(FlySpeed * delta, 0).Rotated(Rotation));
  47. if (kinematicCollision != null)
  48. {
  49. //创建粒子特效
  50. var packedScene = ResourceManager.Load<PackedScene>(ResourcePath.prefab_effect_BulletSmoke_tscn);
  51. var smoke = packedScene.Instance<Particles2D>();
  52. smoke.GlobalPosition = kinematicCollision.Position;
  53. smoke.GlobalRotation = kinematicCollision.Normal.Angle();
  54. GameApplication.Instance.Room.GetRoot(true).AddChild(smoke);
  55.  
  56. Destroy();
  57. return;
  58. }
  59. //距离太大, 自动销毁
  60. CurrFlyDistance += FlySpeed * delta;
  61. if (CurrFlyDistance >= MaxDistance)
  62. {
  63. Destroy();
  64. }
  65. }
  66.  
  67. private void OnArea2dEntered(Area2D other)
  68. {
  69. var role = other.AsActivityObject<Role>();
  70. if (role != null)
  71. {
  72. role.CallDeferred(nameof(Role.Hurt), 4, Rotation);
  73. Destroy();
  74. }
  75. }
  76. }