Add collision detection with octree

This commit is contained in:
2021-04-11 14:12:55 +02:00
parent 46b1ac233b
commit 1c2fc7b86b
21 changed files with 94 additions and 21 deletions
+41 -1
View File
@@ -7,6 +7,7 @@ using SynthySound;
using System.Linq;
using EvilSatellites.Objects;
using DavyKager;
using EvilSatellites.Quadtree;
namespace EvilSatellites.Screens
{
@@ -15,6 +16,7 @@ namespace EvilSatellites.Screens
public ScreenManager Manager { get; set; }
public ScreenState State { get; set; }
public List<IGameObject> Objects = new List<IGameObject>();
private Quadtree<IGameObject> objtree = new Quadtree<IGameObject>(new Vector3(10000, 10000, 10000), 10, 20);
private float Theta = 0;
private Player _player;
private ISoundEffect radarNoise;
@@ -40,8 +42,10 @@ namespace EvilSatellites.Screens
public void Update(GameTime gameTime)
{
objtree.Clear();
foreach (var obj in Objects)
{
objtree.Add(obj);
obj.Update(gameTime);
if (obj.Type == ObjectType.Player)
{
@@ -56,14 +60,28 @@ namespace EvilSatellites.Screens
Vector3 radarTarget = (Objects[1].Position - _player.Position);
radarTarget.Normalize();
radarNoise.Pitch = MathHelper.Clamp(0.1f / Vector3.Distance(_player.Rotation.Forward, radarTarget)*3f, 0, 1);
CheckCollisions();
return;
}
public void HandleInput(GameTime gameTime, KeyboardState inputs)
{
Vector3 move = new Vector3(0, 0, 0);
if (inputs.IsKeyDown(Keys.W))
{
_player.Accelerate();
move.Z = -0.035f;
}
if (inputs.IsKeyDown(Keys.S))
{
move.Z = 0.035f;
}
if (inputs.IsKeyDown(Keys.A))
{
move.X = -0.035f;
}
if (inputs.IsKeyDown(Keys.D))
{
move.X = 0.035f;
}
if (inputs.IsKeyDown(Keys.Left))
{
@@ -81,6 +99,7 @@ namespace EvilSatellites.Screens
{
_player.RotateX(-0.05f);
}
_player.Accelerate(move);
if (inputs.IsKeyDown(Keys.V))
{
Tolk.Speak(_player.Movement.Length().ToString(), true);
@@ -95,5 +114,26 @@ namespace EvilSatellites.Screens
}
}
private void CheckCollisions()
{
foreach (var obj in Objects)
{
var candidates = objtree.Find(obj.Position, obj.Dimensions);
foreach (var target in candidates)
{
if (obj == target) continue;
if (Intersects(obj, target))
{
obj.OnCollision(target);
target.OnCollision(obj);
}
}
}
}
public bool Intersects(IGameObject obj1, IGameObject obj2)
{
return (obj1.Position.X <= (obj2.Position.X + obj2.Dimensions.X) && (obj1.Position.X + obj1.Dimensions.X) >= obj2.Position.X) && (obj1.Position.Y <= (obj2.Position.Y + obj2.Dimensions.Y) && (obj1.Position.Y + obj1.Dimensions.Y) >= obj2.Position.Y) && (obj1.Position.Z <= (obj2.Position.Z + obj2.Dimensions.Z) && (obj1.Position.Z + obj1.Dimensions.Z) >= obj2.Position.Z);
}
}
}