当前位置: 首页 > news >正文

从零开发游戏需要学习的c#模块,第十八章(2D 碰撞检测与金币收集)

这节课我们将要学习在地图上随机生成金币黄色方块代替玩家碰到金币后金币消失分数增加屏幕左上角显示实时分数将game1替换为using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Input;using System;using System.Collections.Generic;namespace MY_FIRST_GAME{public class Game1 : Game{private GraphicsDeviceManager _graphics;private SpriteBatch _spriteBatch;// 玩家private Texture2D playerTexture;private Vector2 playerPosition;private float playerSpeed 200f;// ★ 金币private Texture2D coinTexture;private ListVector2 coins;private Random rng;private int score;// 字体显示分数用private SpriteFont font;public Game1(){_graphics new GraphicsDeviceManager(this);Content.RootDirectory Content;IsMouseVisible true;}protected override void Initialize(){_graphics.PreferredBackBufferWidth 800;_graphics.PreferredBackBufferHeight 600;_graphics.ApplyChanges();playerPosition new Vector2(400, 300);rng new Random();coins new ListVector2();score 0;// 生成 5 个金币SpawnCoins(5);base.Initialize();}protected override void LoadContent(){_spriteBatch new SpriteBatch(GraphicsDevice);// 加载玩家图片using var stream System.IO.File.OpenRead(Content/player.png);playerTexture Texture2D.FromStream(GraphicsDevice, stream);// ★ 创建金币纹理黄色 32x32 方块coinTexture new Texture2D(GraphicsDevice, 32, 32);Color[] data new Color[32 * 32];for (int i 0; i data.Length; i)data[i] Color.Gold;coinTexture.SetData(data);// ★ 加载字体需要先创建字体文件见下方说明// font Content.LoadSpriteFont(font);}// ★ 生成金币private void SpawnCoins(int count){for (int i 0; i count; i){float x rng.Next(50, 750);float y rng.Next(50, 550);coins.Add(new Vector2(x, y));}}protected override void Update(GameTime gameTime){KeyboardState keyboard Keyboard.GetState();float speed playerSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;float deltaTime (float)gameTime.ElapsedGameTime.TotalSeconds;// 移动if (keyboard.IsKeyDown(Keys.W) || keyboard.IsKeyDown(Keys.Up))playerPosition.Y - speed;if (keyboard.IsKeyDown(Keys.S) || keyboard.IsKeyDown(Keys.Down))playerPosition.Y speed;if (keyboard.IsKeyDown(Keys.A) || keyboard.IsKeyDown(Keys.Left))playerPosition.X - speed;if (keyboard.IsKeyDown(Keys.D) || keyboard.IsKeyDown(Keys.Right))playerPosition.X speed;// 限制玩家不超出窗口playerPosition.X Math.Clamp(playerPosition.X, 32, 768);playerPosition.Y Math.Clamp(playerPosition.Y, 32, 568);// ★ 检测金币碰撞CheckCoinCollision();// ★ 金币捡完了重新生成if (coins.Count 0)SpawnCoins(5);if (keyboard.IsKeyDown(Keys.Escape))Exit();base.Update(gameTime);}// ★ 碰撞检测private void CheckCoinCollision(){Rectangle playerRect new Rectangle((int)playerPosition.X - 32,(int)playerPosition.Y - 32,64, 64);for (int i coins.Count - 1; i 0; i--){Rectangle coinRect new Rectangle((int)coins[i].X, (int)coins[i].Y, 32, 32);if (playerRect.Intersects(coinRect)){coins.RemoveAt(i); // 移除金币score 10; // 加分}}}protected override void Draw(GameTime gameTime){GraphicsDevice.Clear(Color.CornflowerBlue);_spriteBatch.Begin();// 画所有金币foreach (Vector2 coinPos in coins){_spriteBatch.Draw(coinTexture, coinPos, Color.White);}// 画玩家以图片中心为锚点_spriteBatch.Draw(playerTexture,playerPosition,null,Color.White,0f,new Vector2(playerTexture.Width / 2, playerTexture.Height / 2),1f,SpriteEffects.None,0f);// ★ 画分数暂时用窗口标题栏显示Window.Title $分数{score} | 剩余金币{coins.Count};_spriteBatch.End();base.Draw(gameTime);}}}本节课学习的新内容1. 碰撞检测Rectangle.Intersects()Rectangle playerRect new Rectangle(玩家左上角X, 玩家左上角Y, 宽度, 高度); Rectangle coinRect new Rectangle(金币X, 金币Y, 32, 32); if (playerRect.Intersects(coinRect)) { // 碰撞了 }2. 以图片中心为锚点画图_spriteBatch.Draw( playerTexture, // 纹理 playerPosition, // 位置 null, // 不裁剪 Color.White, // 颜色 0f, // 不旋转 new Vector2(width/2, height/2), // ★ 锚点设为中心 1f, // 不缩放 SpriteEffects.None, // 不翻转 0f // 深度 );3.Math.Clamp限制范围playerPosition.X Math.Clamp(playerPosition.X, 最小值, 最大值);好了这节课就此结束关注我下期更精彩
http://www.zskr.cn/news/1341155.html

相关文章:

  • ElevenLabs声音库迁移避雷手册(从V2到V3),37家SaaS厂商踩过的5个兼容性深坑:API响应结构突变、SSML标签弃用、Webhook回调中断
  • NCM文件转换终极指南:3步快速解密网易云音乐加密音频
  • 企业AI开发包含哪些内容:从需求分析到交付落地的完整指南 - 华旭传媒
  • DiffSinger歌声合成技术:从架构设计到生产部署的工程实践
  • Sequin实战教程:构建企业级变更数据捕获管道
  • 如何快速获取精准歌词?LDDC 跨平台歌词下载工具完整指南
  • 如何利用VITON-HD实现高分辨率虚拟试衣的完整指南
  • article-extractor安全实践:防范XSS攻击与内容过滤的最佳策略
  • UVa 255 Correct Move
  • Spring AI 2.0 开发Java Agent智能体 - 多模态支持
  • Spark 安装与使用完全指南【保姆级教程】
  • CANN/asc-devkit算子动态库配置
  • LLPlayer:终极语言学习视频播放器 - 用AI技术革新你的外语学习方式
  • Soulmask《灵魂面具》 专用服务器搭建教程
  • 大模型微调是什么?企业为什么需要:2026年术语适配、知识注入与场景落地指南 - 观域传媒
  • Wurm Unlimited 专用服务器搭建教程
  • 2026哪家公司可以做GEO获客/AI搜索排名提升?九颐数科等三家服务商能力拆解与选择框架 - 广州矩阵架构科技公司
  • Flux1-dev完整教程:24GB以下显存用户的终极AI解决方案
  • GitHub社区徽章系统技术深度解析:基于GraphQL的事件管理架构实现原理
  • JetBrains IDE 试用重置终极指南:ide-eval-resetter 完整教程
  • YimMenu完全指南:5大核心功能让你安全畅玩GTA5在线模式
  • 读《AI时代成为行业精英的融合型学习法》
  • 企业落地 AI Agent,第一批最容易跑通的 10 个低风险场景
  • 如何在企业中构建真正有效的AI Agent?从理论到落地,基于300+企业Agent交付经验的实战指南
  • DicomObjects COM -Release Date: 2026-05-18
  • Web基础(六):Mybatis
  • ChatGPT-Web-Midjourney-Proxy的GPTs功能详解:打造专属AI助手的终极指南
  • 0602光刻机 第六篇:EUV超精密光学系统(S级 长期死磕突破)超精密反射镜技术壁垒
  • BetterCodable快速入门指南:5分钟学会属性包装器的强大功能
  • Squash架构深度剖析:从Plank到Debug Attachment的完整实现