Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / item / weapon / bullet / Bullet.cs
@lijincheng lijincheng on 9 Mar 2023 2 KB 小修改
  1. using Godot;
  2.  
  3. /// <summary>
  4. /// 子弹类
  5. /// </summary>
  6. [RegisterActivity(ActivityIdPrefix.Bullet + "0001", ResourcePath.prefab_weapon_bullet_Bullet_tscn)]
  7. public partial class Bullet : ActivityObject
  8. {
  9. /// <summary>
  10. /// 碰撞区域
  11. /// </summary>
  12. public Area2D CollisionArea { get; private set; }
  13.  
  14. // 最大飞行距离
  15. private float MaxDistance;
  16.  
  17. // 子弹飞行速度
  18. private float FlySpeed;
  19.  
  20. //当前子弹已经飞行的距离
  21. private float CurrFlyDistance = 0;
  22.  
  23. public void Init(float speed, float maxDistance, Vector2 position, float rotation, uint targetLayer)
  24. {
  25. CollisionArea = GetNode<Area2D>("CollisionArea");
  26. CollisionArea.CollisionMask = targetLayer;
  27. CollisionArea.AreaEntered += OnArea2dEntered;
  28.  
  29. FlySpeed = speed;
  30. MaxDistance = maxDistance;
  31. Position = position;
  32. Rotation = rotation;
  33. ShadowOffset = new Vector2(0, 5);
  34.  
  35. BasisVelocity = new Vector2(FlySpeed, 0).Rotated(Rotation);
  36. }
  37.  
  38. protected override void PhysicsProcessOver(float delta)
  39. {
  40. //移动
  41. var lastSlideCollision = GetLastSlideCollision();
  42. //撞到墙
  43. if (lastSlideCollision != null)
  44. {
  45. //创建粒子特效
  46. var packedScene = ResourceManager.Load<PackedScene>(ResourcePath.prefab_effect_BulletSmoke_tscn);
  47. var smoke = packedScene.Instantiate<GpuParticles2D>();
  48. smoke.GlobalPosition = lastSlideCollision.GetPosition();
  49. smoke.GlobalRotation = lastSlideCollision.GetNormal().Angle();
  50. smoke.AddToActivityRoot(RoomLayerEnum.YSortLayer);
  51.  
  52. Destroy();
  53. return;
  54. }
  55. //距离太大, 自动销毁
  56. CurrFlyDistance += FlySpeed * delta;
  57. if (CurrFlyDistance >= MaxDistance)
  58. {
  59. var packedScene = ResourceManager.Load<PackedScene>(ResourcePath.prefab_effect_BulletDisappear_tscn);
  60. var node = packedScene.Instantiate<Node2D>();
  61. node.GlobalPosition = GlobalPosition;
  62. node.AddToActivityRoot(RoomLayerEnum.YSortLayer);
  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. }