XNA-2D 打磚塊遊戲(二)
上一篇已經將磚塊寫出來了,現在讓他會消失吧!
我們在磚塊的Collided函式內將Life扣一,當Life小於等於零時,在Udate那裡就會將active設定為false,
接著就可以移出drawList和collideList。稍微改寫一下Game1的Update如下:
protected override void Update(GameTime gameTime) {
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
List<Visual2DObject> dList = new List<Visual2DObject>(drawList);
foreach (Visual2DObject o in dList) {
if (o.Active == false) {
drawList.Remove(o);
} else
o.Update(gameTime);
}
List<PixelCollideObject> cList = new List<PixelCollideObject>(collideList);
for (int i = 0; i < cList.Count; i++) {
if (cList[i].Active == false) {
collideList.Remove(cList[i]);
} else {
for (int j = i + 1; j < cList.Count; j++) {
Vector2? p = cList[i].CollideCheck(cList[j]);
if (p != null) {
cList[i].Collided(cList[j], p.Value);
p = null;
}
}
}
}
base.Update(gameTime);
}
接著我們產生一個板子,因為板子不會受到球的碰撞而產生任何影響,所以和磚塊類似。程式碼如下:
public class Paddle : PixelCollideObject{
private float speed = 0.5f;
public float Speed {
get { return speed * 1000; }
set {
if (value < 100) speed = 0.1f;
else speed = value / 1000f;
}
}
public Paddle(Texture2D image)
: base(image) {
}
public override void Update(GameTime gameTime) {
if (!enabled) return;
KeyboardState state = Keyboard.GetState();
if (state.IsKeyDown(Keys.Left)) {
position.X -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
} else if (state.IsKeyDown(Keys.Right)) {
position.X += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
}
if (curb != null) {
if (position.X < curb.Value.Left) position.X = curb.Value.Left;
else if (position.X + image.Width > curb.Value.Right) position.X = curb.Value.Right - image.Width;
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) {
if (visibled == false) return;
spriteBatch.Draw(image, position, Color.White);
}
public override void Collided(ICollidable obj, Vector2 collidePoint) {
}
}
Speed對外的單位是像素每秒,內部的話就用像素每毫秒。Update處理移動和限制範圍。
目前碰到球並不用做啥事。
所以遊戲畫面暫時如下: