From 1dc140d31d96e9e84954e5f4ca1f1536a2e5f11a Mon Sep 17 00:00:00 2001 From: copygirl Date: Thu, 13 May 2021 19:33:52 +0200 Subject: [PATCH] Bullets collide with blocks and players --- project.godot | 9 +++++++++ scene/Block.tscn | 2 ++ scene/Player.tscn | 2 +- src/Objects/Bullet.cs | 26 ++++++++++++++++++++------ 4 files changed, 32 insertions(+), 7 deletions(-) diff --git a/project.godot b/project.godot index ba9cf39..37512d5 100644 --- a/project.godot +++ b/project.godot @@ -28,6 +28,10 @@ window/size/width=1280 window/size/height=720 window/stretch/mode="viewport" +[global] + +layer=false + [importer_defaults] texture={ @@ -104,6 +108,11 @@ ui_menu={ ] } +[layer_names] + +2d_physics/layer_1="players" +2d_physics/layer_2="blocks" + [rendering] 2d/snapping/use_gpu_pixel_snap=true diff --git a/scene/Block.tscn b/scene/Block.tscn index 0be6d5c..40b681f 100644 --- a/scene/Block.tscn +++ b/scene/Block.tscn @@ -7,6 +7,8 @@ extents = Vector2( 8, 8 ) [node name="Block" type="StaticBody2D"] +collision_layer = 2 +collision_mask = 0 script = ExtResource( 2 ) [node name="RectangleShape" type="CollisionShape2D" parent="."] diff --git a/scene/Player.tscn b/scene/Player.tscn index cd98cb9..2099345 100644 --- a/scene/Player.tscn +++ b/scene/Player.tscn @@ -22,7 +22,7 @@ radius = 8.0 [node name="Player" type="KinematicBody2D"] z_index = 10 -collision_layer = 0 +collision_mask = 2 script = ExtResource( 3 ) DisplayNamePath = NodePath("DisplayName") SpritePath = NodePath("Sprite") diff --git a/src/Objects/Bullet.cs b/src/Objects/Bullet.cs index 48ef056..20a30c1 100644 --- a/src/Objects/Bullet.cs +++ b/src/Objects/Bullet.cs @@ -33,18 +33,32 @@ public class Bullet : Node2D { _age += TimeSpan.FromSeconds(delta); - if (_distance < MaximumRange) { - _distance = Mathf.Min(MaximumRange, Speed * (float)_age.TotalSeconds); - Position = _startPosition + Direction * _distance; - Update(); - } - if (_age > TRAIL_DURATION) { Modulate = new Color(Modulate, Modulate.a - delta * 2); if (Modulate.a <= 0) this.RemoveFromParent(); } } + public override void _PhysicsProcess(float delta) + { + var previousPosition = Position; + _distance = Mathf.Min(MaximumRange, Speed * (float)_age.TotalSeconds); + Position = _startPosition + Direction * _distance; + + var collision = GetWorld2d().DirectSpaceState.IntersectRay( + previousPosition, Position, collisionLayer: 0b11); + if (collision.Count != 0) { + Position = (Vector2)collision["position"]; + _distance = _startPosition.DistanceTo(Position); + SetPhysicsProcess(false); + } + + if (_distance > MaximumRange) + SetPhysicsProcess(false); + + Update(); + } + public override void _Draw() { var numPoints = 2