C#基于Monogame实现弹跳方块游戏:移除屏幕中心100px范围内方块
MonoGame弹跳方块消失功能实现方案
实现思路
- 首先确定屏幕中心点坐标,结合现有代码的边界判断逻辑,窗口默认尺寸为800x480,中心点坐标为
(400, 240) - 判定逻辑采用距离平方对比替代开根号计算,避免性能损耗,半径100px对应的平方值为
100 * 100 = 10000 - 判定时取30x30方块的中心点坐标
(X+15, Y+15)做对比,判定精度更高 - 遍历方块列表时采用倒序for循环,避免foreach遍历过程中删除元素抛出异常
- 原初始化逻辑仅生成1000个方块,需修改为2000个匹配需求
修改后完整代码
Game1.cs
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace Inlämning2 { public class Game1 : Game { private GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; Texture2D pixelTexture; List<Block> blocks = new List<Block>(); // 定义屏幕中心、判定半径平方常量 private const int ScreenCenterX = 400; private const int ScreenCenterY = 240; private const int RadiusSquared = 100 * 100; public Game1() { _graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; IsMouseVisible = true; } protected override void Initialize() { Random rnd = new Random(); // 循环次数修改为2000,生成对应数量的方块 for (int i = 0; i < 2000; i++) { var block = new Block(); block.X = rnd.Next(0, 600); block.Y = rnd.Next(0, 400); block.Color = new Color(rnd.Next(256), rnd.Next(256), rnd.Next(256)); blocks.Add(block); } base.Initialize(); } protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); pixelTexture = Content.Load<Texture2D>("pixel"); } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); foreach (Block block in blocks) { block.Update(); } // 倒序遍历方块列表,移除符合消失条件的方块 for (int i = blocks.Count - 1; i >= 0; i--) { var block = blocks[i]; // 计算方块中心点坐标 int blockCenterX = block.X + 15; int blockCenterY = block.Y + 15; // 计算到屏幕中心的距离平方 int distanceSquared = (blockCenterX - ScreenCenterX) * (blockCenterX - ScreenCenterX) + (blockCenterY - ScreenCenterY) * (blockCenterY - ScreenCenterY); if (distanceSquared <= RadiusSquared) { blocks.RemoveAt(i); } } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); _spriteBatch.Begin(); foreach (Block block in blocks) { block.Draw(_spriteBatch, pixelTexture); } _spriteBatch.End(); base.Draw(gameTime); } } }
Block.cs 无需修改,原有逻辑可正常运行
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Inlämning2 { class Block { public int X { get; set; } = 100; public int Y { get; set; } = 100; public Color Color { get; set; } = Color.Red; public int speed1 = 1; public int speed2 = -1; public void Draw(SpriteBatch spriteBatch, Texture2D texture) { spriteBatch.Draw(texture, new Rectangle(X, Y, 30, 30), Color); } public void Update() { if (X < 0) speed2 += 1; if (X > 770) speed2 += -1; if (Y > 450) speed1 += -1; if (Y < 0) speed1 += 1; X += speed2; Y += speed1; if (speed1 > 1) speed1 = 1; if (speed2 > 1) speed2 = 1; } } }
内容的提问来源于stack exchange,提问作者Blackout
相关产品推荐
相关产品推荐

