Merge pull request #51 from progtime-net/Collision

Collision
This commit is contained in:
SergoDobro 2024-08-17 23:19:33 +03:00 committed by GitHub
commit a6544a20f2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 130 additions and 76 deletions

View file

@ -13,11 +13,17 @@ using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient;
using System.Drawing; using System.Drawing;
using System.Reflection; using System.Reflection;
using ZoFo.GameCore.GameObjects.Entities; using ZoFo.GameCore.GameObjects.Entities;
using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player;
using System.Linq;
using System.Web;
using ZoFo.GameCore.GUI;
namespace ZoFo.GameCore namespace ZoFo.GameCore
{ {
public class Client public class Client
{ {
#region Network part
ClientNetworkManager networkManager; ClientNetworkManager networkManager;
public bool IsConnected { get { return networkManager.IsConnected; } } public bool IsConnected { get { return networkManager.IsConnected; } }
@ -39,12 +45,13 @@ namespace ZoFo.GameCore
} }
public void GameEndedUnexpectedly() { } public void GameEndedUnexpectedly() { }
public void JoinRoom(string ip,int port) public void JoinRoom(string ip, int port)
{ {
networkManager.JoinRoom(ip,port); networkManager.JoinRoom(ip, port);
} }
public void JoinYourself(int port) { networkManager.JoinYourself(port); } public void JoinYourself(int port) { networkManager.JoinYourself(port); }
#endregion
List<MapObject> mapObjects = new List<MapObject>(); List<MapObject> mapObjects = new List<MapObject>();
List<GameObject> gameObjects = new List<GameObject>(); List<GameObject> gameObjects = new List<GameObject>();
@ -85,20 +92,43 @@ namespace ZoFo.GameCore
} }
else if (update is UpdateGameObjectCreated) else if (update is UpdateGameObjectCreated)
{ {
var a = Assembly.GetAssembly(typeof(GameObject));
if ((update as UpdateGameObjectCreated).GameObjectType == "EntittyForAnimationTests") if ((update as UpdateGameObjectCreated).GameObjectType == "EntittyForAnimationTests")
{ gameObjects.Add(new EntittyForAnimationTests(new Vector2(100, 100)));
if ((update as UpdateGameObjectCreated).GameObjectType == "Player")
gameObjects.Add(new Player(new Vector2(100, 100)));
gameObjects.Add( (gameObjects.Last() as Entity).SetIdByClient((update as UpdateGameObjectCreated).IdEntity);
new EntittyForAnimationTests(new Vector2(100,100)) //var a = Assembly.GetAssembly(typeof(GameObject));
);
}
//gameObjects.Add( TODO reflection //gameObjects.Add( TODO reflection
//Activator.CreateInstance(Type.GetType("ZoFo.GameCore.GameObjects.Entities.EntittyForAnimationTests") //Activator.CreateInstance(Type.GetType("ZoFo.GameCore.GameObjects.Entities.EntittyForAnimationTests")
///*(update as UpdateGameObjectCreated).GameObjectType*/, new []{ new Vector2(100, 100) }) ///*(update as UpdateGameObjectCreated).GameObjectType*/, new []{ new Vector2(100, 100) })
//as GameObject //as GameObject
//); //);
} }
else if (update is UpdatePosition)
{
var ent = FindEntityById(update.IdEntity);
ent.position = (update as UpdatePosition).NewPosition;
DebugHUD.Instance.Log("newPosition " + ent.position);
} }
} }
public Entity FindEntityById(int id)
{
for (int i = 0; i < gameObjects.Count; i++)
{
if (gameObjects[i] is Entity)
{
if ((gameObjects[i] as Entity).Id == id)
{
return gameObjects[i] as Entity;
}
}
}
return null;
}
}
} }

View file

@ -13,9 +13,11 @@ public class DebugHUD
private SpriteFont _spriteFont; private SpriteFont _spriteFont;
private Dictionary<string, string> _text = new(); private Dictionary<string, string> _text = new();
private List<string> _log = new(); private List<string> _log = new();
public static DebugHUD Instance { get; private set; }
public void Initialize() public void Initialize()
{ {
Instance = this;
} }
public void LoadContent() public void LoadContent()

View file

@ -12,6 +12,7 @@ using ZoFo.GameCore.GameManagers.ItemManager;
using ZoFo.GameCore.GUI; using ZoFo.GameCore.GUI;
using static System.Collections.Specialized.BitVector32; using static System.Collections.Specialized.BitVector32;
using MonogameLibrary.UI.Base; using MonogameLibrary.UI.Base;
using ZoFo.GameCore.GameObjects;
namespace ZoFo.GameCore.GameManagers namespace ZoFo.GameCore.GameManagers
{ {
@ -83,6 +84,8 @@ namespace ZoFo.GameCore.GameManagers
currentGUI.LoadContent(); currentGUI.LoadContent();
animationBuilder = new AnimationBuilder(); animationBuilder = new AnimationBuilder();
animationBuilder.LoadAnimations(); animationBuilder.LoadAnimations();
GameObject.debugTexture = new Texture2D(GraphicsDevice, 1, 1);
GameObject.debugTexture.SetData(new Color[] { Color.White });
} }
protected override void Update(GameTime gameTime) protected override void Update(GameTime gameTime)

View file

@ -1,6 +0,0 @@
namespace ZoFo.GameCore.GameManagers.CollisionManager
{
public class CollectionComponent
{
}
}

View file

@ -14,12 +14,29 @@ namespace ZoFo.GameCore.GameManagers.CollisionManager
public class CollisionComponent public class CollisionComponent
{ {
//==КОНСТРУКТОР== //==КОНСТРУКТОР==
// public CollisionComponent(GameObject gameObject) public CollisionComponent(GameObject gameObject)
// { {
// this.gameObject = gameObject;
// AppManager.Instance.server.collisionManager.Register(this);
// }
this.gameObject = gameObject;
hasCollision = false;
this.isTrigger = false;
}
public CollisionComponent(GameObject gameObject, bool hasCollision = false, Rectangle? collisionRectangle = null, bool isTrigger = false, Rectangle? triggerRectangle = null)
{
this.gameObject = gameObject;
hasCollision = hasCollision;
this.isTrigger = isTrigger;
if (hasCollision)
this.stopRectangle = collisionRectangle.Value;
if (isTrigger)
this.triggerRectangle = triggerRectangle.Value;
}
//==ПОЛЯ== //==ПОЛЯ==
@ -48,29 +65,6 @@ namespace ZoFo.GameCore.GameManagers.CollisionManager
public event EventHandler<CollisionComponent> OnCollision; public event EventHandler<CollisionComponent> OnCollision;
// methods-event
public CollisionComponent(GameObject gameObject)
{
this.gameObject = gameObject;
doesStop = false;
this.isTrigger = false;
AppManager.Instance.server.collisionManager.Register(this);
}
public CollisionComponent(GameObject gameObject, bool hasCollision = false, Rectangle? collisionRectangle = null, bool isTrigger = false, Rectangle? triggerRectangle = null)
{
this.gameObject = gameObject;
doesStop = hasCollision;
this.isTrigger = isTrigger;
if (hasCollision)
this.stopRectangle = collisionRectangle.Value;
if (isTrigger)
this.triggerRectangle = triggerRectangle.Value;
AppManager.Instance.server.collisionManager.Register(this);
}
} }
} }

View file

@ -31,8 +31,10 @@ namespace ZoFo.GameCore.GameManagers.CollisionManager
//for (int i = 0; i < ObjectsWithCollisions.Count; i++) //for (int i = 0; i < ObjectsWithCollisions.Count; i++)
//{ //{
var currentRect = entity.collisionComponent.stopRectangle;//задаём РЕК var currentRect = entity.collisionComponent.stopRectangle;//задаём РЕК
currentRect.X+=(int)entity.position.X;
currentRect.Y+=(int)entity.position.Y;
var newRect = currentRect; // задаём значение старого РЕК новому РЕК var newRect = currentRect; // задаём значение старого РЕК новому РЕК
bool flagRemovedObject = false; //флаг удаления
var collidedX = false; // соприкосновение var collidedX = false; // соприкосновение
@ -95,16 +97,14 @@ namespace ZoFo.GameCore.GameManagers.CollisionManager
newRect.Y = tryingRectY.Y;//значение по X для нового РЕК приравниваем к значению испытуемого РЕК newRect.Y = tryingRectY.Y;//значение по X для нового РЕК приравниваем к значению испытуемого РЕК
} }
entity.collisionComponent.stopRectangle = newRect; entity.graphicsComponent.ObjectDrawRectangle.X = (int)entity.position.X;
entity.graphicsComponent.ObjectDrawRectangle = newRect; entity.graphicsComponent.ObjectDrawRectangle.Y = (int)entity.position.Y;
AppManager.Instance.server.AddData(new UpdatePosition() { NewPosition = entity.position, IdEntity = entity.Id });
AppManager.Instance.debugHud.Set("testPos", entity.position.ToString()); //TODO remove
entity.velocity = Vector2.Zero; entity.velocity = Vector2.Zero;
} }
//обновление позиции объекта //обновление позиции объекта
public void UpdateObjectsPositions()
{
}
public void UpdatePositions() public void UpdatePositions()
{ {

View file

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace ZoFo.GameCore.GameManagers.ItemManager namespace ZoFo.GameCore.GameManagers.ItemManager
{ {
class ItemInfo public class ItemInfo
{ {
//поля //поля
string tag; string tag;

View file

@ -1,4 +1,5 @@
using System; using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -13,5 +14,7 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient
public class UpdatePosition : UpdateData public class UpdatePosition : UpdateData
{ {
public UpdatePosition() { UpdateType = "UpdatePosition"; } public UpdatePosition() { UpdateType = "UpdatePosition"; }
public Vector2 NewPosition { get; set; }
} }
} }

View file

@ -12,10 +12,22 @@ namespace ZoFo.GameCore.GameObjects.Entities
//public override GraphicsComponent graphicsComponent => null; //public override GraphicsComponent graphicsComponent => null;
public CollisionComponent collisionComponent { get; protected set; } public CollisionComponent collisionComponent { get; protected set; }
public int Id { get; set; } public int Id { get; set; }
static int totalEntitiesCreated = 0;
protected Entity(Vector2 position) : base(position) protected Entity(Vector2 position) : base(position)
{ {
Id = totalEntitiesCreated;
totalEntitiesCreated++;
collisionComponent = new CollisionComponent(this);
} }
/// <summary>
/// For initialisation on Client
/// </summary>
/// <param name="newId"></param>
public void SetIdByClient(int newId)
{
Id = newId;
}
public virtual void Update() public virtual void Update()
{ {
} }

View file

@ -15,7 +15,7 @@ public class Interactable : Entity
{ {
collisionComponent.OnTriggerEnter += (sender, e) => ChangeInteraction(sender, e, true); collisionComponent.OnTriggerEnter += (sender, e) => ChangeInteraction(sender, e, true);
collisionComponent.OnTriggerExit += (sender, e) => ChangeInteraction(sender, e, false); collisionComponent.OnTriggerExit += (sender, e) => ChangeInteraction(sender, e, false);
collisionComponent.OnTriggerInteract += OnInteraction; collisionComponent.OnTriggerZone += OnInteraction;
} }
private void ChangeInteraction(object sender, CollisionComponent e, bool isReady) private void ChangeInteraction(object sender, CollisionComponent e, bool isReady)

View file

@ -35,6 +35,7 @@ public class LivingEntity : Entity
} }
} }

View file

@ -26,20 +26,23 @@ public class Player : LivingEntity
//InputWeaponRotation = new Vector2(0, 0); //InputWeaponRotation = new Vector2(0, 0);
//InputPlayerRotation = new Vector2(0, 0); //InputPlayerRotation = new Vector2(0, 0);
collisionComponent = new CollisionComponent(this, true, new Rectangle(0, 0, 10, 10)); collisionComponent.stopRectangle = new Rectangle(0, 0, 10, 10);
graphicsComponent.ObjectDrawRectangle = new Rectangle(0,0,100,100);
} }
public void Update(GameTime gameTime) public override void Update()
{ {
MovementLogic(); MovementLogic();
} }
float t;
public void MovementLogic() public void MovementLogic()
{ {
velocity.X = (float)Math.Sin(t);
t++;
if (InputPlayerRotation.X > 0.9) if (InputPlayerRotation.X > 0.9)
{ {
velocity.X = 5;
} }
} }
public void HandleNewInput(UpdateInput updateInput) public void HandleNewInput(UpdateInput updateInput)

View file

@ -46,6 +46,7 @@ public abstract class GameObject
#region Client Side #region Client Side
public static Texture2D debugTexture;
/// <summary> /// <summary>
/// Для клиента /// Для клиента
/// Это вызывается в клиентской части игры /// Это вызывается в клиентской части игры
@ -82,6 +83,8 @@ public abstract class GameObject
{ {
graphicsComponent.DrawAnimation(graphicsComponent.ObjectDrawRectangle, spriteBatch); graphicsComponent.DrawAnimation(graphicsComponent.ObjectDrawRectangle, spriteBatch);
//debug //debug
DrawDebugRectangle(spriteBatch, graphicsComponent.ObjectDrawRectangle);
if (AppManager.Instance.InputManager.CollisionsCheat) if (AppManager.Instance.InputManager.CollisionsCheat)
DrawDebugRectangle(spriteBatch, graphicsComponent.ObjectDrawRectangle); DrawDebugRectangle(spriteBatch, graphicsComponent.ObjectDrawRectangle);
@ -90,11 +93,11 @@ public abstract class GameObject
{ {
if (color is null) color = new Color(1, 0, 0, 0.25f); if (color is null) color = new Color(1, 0, 0, 0.25f);
if (color.Value.A == 255) color = new Color(color.Value, 0.25f); if (color.Value.A == 255) color = new Color(color.Value, 0.25f);
//spriteBatch.Draw(debugTexture, spriteBatch.Draw(debugTexture,
// new Rectangle((_rectangle.X - graphicsComponent.CameraPosition.X) * graphicsComponent.scaling, new Rectangle((_rectangle.X - GraphicsComponent.CameraPosition.X) * GraphicsComponent.scaling,
// (_rectangle.Y - graphicsComponent.CameraPosition.Y) * graphicsComponent.scaling, (_rectangle.Y - GraphicsComponent.CameraPosition.Y) * GraphicsComponent.scaling,
// _rectangle.Width * graphicsComponent.scaling, _rectangle.Width * GraphicsComponent.scaling,
// _rectangle.Height * graphicsComponent.scaling), color.Value); _rectangle.Height * GraphicsComponent.scaling), color.Value);
//TODO: debugTexture //TODO: debugTexture
} }

View file

@ -15,6 +15,7 @@ using ZoFo.GameCore.GameManagers.NetworkManager.Updates;
using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient;
using ZoFo.GameCore.GameObjects; using ZoFo.GameCore.GameObjects;
using ZoFo.GameCore.GameObjects.Entities; using ZoFo.GameCore.GameObjects.Entities;
using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Enemies;
using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player; using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player;
using ZoFo.GameCore.GameObjects.MapObjects; using ZoFo.GameCore.GameObjects.MapObjects;
@ -26,8 +27,6 @@ namespace ZoFo.GameCore
private int ticks = 0; private int ticks = 0;
public IPEndPoint MyIp { get { return networkManager.InfoConnect; } } public IPEndPoint MyIp { get { return networkManager.InfoConnect; } }
public CollisionManager collisionManager;
public Server() public Server()
{ {
networkManager = new ServerNetworkManager(); networkManager = new ServerNetworkManager();
@ -150,10 +149,20 @@ namespace ZoFo.GameCore
});//TODO });//TODO
return; return;
} }
if (gameObject is Entity)
{
AddData(new UpdateGameObjectCreated() { GameObjectType = gameObject.GetType().Name, IdEntity = (gameObject as Entity).Id });
collisionManager.Register((gameObject as Entity).collisionComponent);
}
else
AddData(new UpdateGameObjectCreated() { GameObjectType = gameObject.GetType().Name });
AddData(new UpdateGameObjectCreated()
{ GameObjectType = gameObject.GetType().Name } ////var elems = gameObject.GetType().GetProperties(System.Reflection.BindingFlags.Public);
); ////if (elems.Count()>0) TODO
////{
//// AppManager.Instance.server.collisionManager.Register((elems.First().GetValue(gameObject) as CollisionComponent));
////}
} }