Newer
Older
DungeonShooting / DungeonShooting_Godot / src / weapon / bullet / OrdinaryBullets.cs
  1. using System;
  2. using Godot;
  3.  
  4. /// <summary>
  5. /// 普通的子弹
  6. /// </summary>
  7. public class OrdinaryBullets : Node2D, IBullet
  8. {
  9. public CampEnum TargetCamp { get; private set; }
  10.  
  11. public Gun Gun { get; private set; }
  12.  
  13. public Node2D Master { get; private set; }
  14.  
  15. /// <summary>
  16. /// 碰撞物体后产生的火花
  17. /// </summary>
  18. [Export] public PackedScene Hit;
  19.  
  20. // 起始点坐标
  21. private Vector2 StartPosition;
  22. // 最大飞行距离
  23. private float MaxDistance;
  24. // 子弹飞行速度
  25. private float FlySpeed = 1500;
  26. //当前子弹已经飞行的距离
  27. private float CurrFlyDistance = 0;
  28. //射线碰撞节点
  29. private RayCast2D RayCast;
  30. //子弹的精灵
  31. private Sprite BulletSprite;
  32. //绘制阴影的精灵
  33. private Sprite ShadowSprite;
  34.  
  35. private int frame = 0;
  36.  
  37. public void Init(CampEnum target, Gun gun, Node2D master)
  38. {
  39. TargetCamp = target;
  40. Gun = gun;
  41. Master = master;
  42.  
  43. MaxDistance = MathUtils.RandRange(gun.Attribute.MinDistance, gun.Attribute.MaxDistance);
  44. StartPosition = GlobalPosition;
  45. BulletSprite = GetNode<Sprite>("Bullet");
  46. BulletSprite.Visible = false;
  47. RayCast = GetNode<RayCast2D>("RayCast2D");
  48.  
  49. //创建阴影
  50. ShadowSprite = new Sprite();
  51. ShadowSprite.Visible = false;
  52. ShadowSprite.ZIndex = -1;
  53. ShadowSprite.Texture = BulletSprite.Texture;
  54. ShadowSprite.Offset = BulletSprite.Offset;
  55. ShadowSprite.Material = ResourceManager.ShadowMaterial;
  56. AddChild(ShadowSprite);
  57. }
  58.  
  59. public override void _Ready()
  60. {
  61. //生成时播放音效
  62. SoundManager.PlaySoundEffect("ordinaryBullet.ogg", this, 6f);
  63. }
  64.  
  65. public override void _PhysicsProcess(float delta)
  66. {
  67. if (frame++ == 0)
  68. {
  69. BulletSprite.Visible = true;
  70. ShadowSprite.Visible = true;
  71. }
  72. //碰到墙壁
  73. if (RayCast.IsColliding())
  74. {
  75. //var target = RayCast.GetCollider();
  76. var pos = RayCast.GetCollisionPoint();
  77. //播放受击动画
  78. Node2D hit = Hit.Instance<Node2D>();
  79. hit.RotationDegrees = MathUtils.RandRangeInt(0, 360);
  80. hit.GlobalPosition = pos;
  81. GetTree().CurrentScene.AddChild(hit);
  82. QueueFree();
  83. }
  84. else //没有碰到, 继续移动
  85. {
  86. ShadowSprite.GlobalPosition = GlobalPosition + new Vector2(0, 5);
  87. Position += new Vector2(FlySpeed * delta, 0).Rotated(Rotation);
  88.  
  89. CurrFlyDistance += FlySpeed * delta;
  90. if (CurrFlyDistance >= MaxDistance)
  91. {
  92. QueueFree();
  93. }
  94. }
  95. }
  96.  
  97. }