移动敌人精灵,根据它生成的一侧. C# 单游戏



所以我有一个代码,精灵在窗口外生成,我希望它根据它生成的位置在特定的直线上移动,如果精灵在顶部生成,它会在底部生成,反之亦然,如果精灵然后向左生成,它将向右,反之亦然。

游戏1.cs代码:

public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
List<Enemy> enemies = new List<Enemy>();

public Vector2 ecords
{
get { return ecords; }
set { ecords = value; }
}

public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}

protected override void Initialize()
{

base.Initialize();
}

protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
//player
Texture2D playertexture = Content.Load<Texture2D>("Player");
player = new Player(new Vector2(350, 175), playertexture);
//enemy
Texture2D enemytexture = Content.Load<Texture2D>("Enemy");
Random random = new Random();
var width = GraphicsDevice.Viewport.Width;
var height = GraphicsDevice.Viewport.Height;
for (int i = 0; i < 20; i++)
{
enemies.Add(new Enemy(new Vector2(random.Next(width, width + 100), random.Next(0, height)), enemytexture));
enemies.Add(new Enemy(new Vector2(random.Next(0 - 100, 0), random.Next(0, height)), enemytexture));
enemies.Add(new Enemy(new Vector2(random.Next(0, width), random.Next(-100, 0)), enemytexture));
enemies.Add(new Enemy(new Vector2(random.Next(0, width), random.Next(height, height + 100)), enemytexture));
}


}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
foreach (Enemy enemy in enemies)
{
enemy.Update(gameTime);
}
player.Update(gameTime);

base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
foreach (Enemy enemy in enemies)
{
enemy.Draw(spriteBatch);
}
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}

敌人.cs

class Enemy
{
Texture2D enemytexture;
Vector2 enemyposition;

public Enemy(Vector2 enemyposition, Texture2D enemytexture)
{
this.enemyposition = enemyposition;
this.enemytexture = enemytexture;
}
public void Update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(enemytexture, enemyposition, Color.White);
}
}

一种选择是添加一个velocity(或者您可以将其命名为movement/direction(到Enemy,就像您现有的enemyposition一样,在参数中传递给构造函数。然后通过在Update方法中添加速度来更新当前位置Enemy

public void Update(GameTime gameTime)
{
this.enemyposition += this.velocity;
}

您可以使用单位矢量(可选乘以速度(作为速度值:

var (left, right) = (-Vector2.UnitX, Vector2.UnitX);
var (up, down) = (-Vector2.UnitY, Vector2.UnitY);
float enemySpeed = 5.0f;
enemies.Add(new Enemy(
new Vector2(random.Next(width, width + 100), random.Next(0, height)), 
enemytexture, velocity: left * enemySpeed));
// etc.

最新更新