Reputation: 1
I'm trying to make a touhou-style game where any sprite, that can shoot bullets, can shoot any type of bullet it is given, with the shot cooldown coming from the bullet. But, I can't figure out how.
I currently have my Character
class sending an event to the monogame GameEngine, which then creates a hardcoded Bullet
following the characters position and direction they are facing. When trying to make the Bullet
type dynamic, I've tried to add a list of Bullet
types to the Character
class, but that could only contain instances of Bullets
, not the class type.
Then, I wanted to send the Bullet
info as an event argument, but I can't figure out how to generate the bullet using it's class name and still pass in all its parameters needed for construction. What I want is a function that takes in the name of a subclass of a Bullet
and the parameters for said bullet.
An instance of the passed subclass should be initialized in a way that is well decoupled, as in the individual characters know nothing about the Bullet
being called other than the name, but still gets the cooldown length of the specific bullet.
I know that this will use a factory somehow, either factory method or abstract factory, but I really can't wrap my head around this, sorry if this is a repeat.
Here's my code:
GameEngine:
var player = playerFactory.CreateEntity(playertexture, new Vector2(Globals.WindowSize.X/2,
Globals.WindowSize.Y / 2), 0,200f) as Player;
player.SpriteEvent += PlayerEventHandler;
private void PlayerEventHandler(object sender, SpriteEventArgs args)
{
//This is where the things like bullets and any
//other sprite events are currently set to go to.
//We can subscribe different types of sprites to different event
//handlers, this was just
//to test if my sprite event was working.
//Right now, it's only subscribed to the player
//and reacts when the F key is pressed.
var player = sender as Player;
var characterArgs = args as CharacterEventArgs;
BulletManager.AddByType("A");
}
Player:
//on keypress, check if cooldown has ended, and if it has, shoot.
if(kstate.IsKeyDown(Keys.F))
{
shotCoolDown -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if (shotCoolDown < 0)
{
this.Shoot(bulletTypes[0]);
}
}
public override void Shoot(Attack bullet)
{
//Call Shoot event, send to PlayerEventHandler, And set shotCooldown
//based on bullet created
this.OnSpriteEvent(new CharacterEventArgs(){ Bullet = bullet});
shotCoolDown = BulletA.GetCoolDown;
}
Bullet:
public class BulletA(Texture2D texture, Vector2 position, float rotation, float speed) : Attack(texture, position, rotation, speed)
{
protected const float Cooldown = 500f;
public static float GetCoolDown => Cooldown;
public override void Update(GameTime gameTime)
{
// moving logic after its created
}
}
Upvotes: 0
Views: 61