You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Monogame中缩放SourceRectangle时宽高归零问题求助

解决MonoGame中缩放导致SourceRectangle宽高为0的问题

嘿,我来帮你搞定这个问题!你遇到的核心问题是整数除法和强制类型转换的顺序错误,导致缩放后的数值被直接截断成0了。

问题根源分析

你当前的代码是这样的:

sourceRectangle.Width = (texture.Width / cols) * (int)this.scale.X
sourceRectangle.Height = (texture.Height / rows) * (int)this.scale.Y

这里有两个关键问题:

  1. texture.Width / cols 是整数除法——因为两个操作数都是整数,结果会直接舍去小数部分,比如如果texture.Width=3、cols=2,结果就是1而不是1.5。
  2. 你先把scale.X转成了int类型,当scale.X=0.5时,强制转int会直接变成0,再乘前面的整数结果,自然就得到0了。

修正方案

我们需要调整计算顺序,先保留浮点精度完成所有运算,再根据需求转换成整数(比如四舍五入或向上取整)。这里提供两种常用的写法:

写法1:四舍五入到最近整数(推荐用于碰撞盒和视觉表现对齐)

// 先将整数转为浮点型,避免提前截断小数
sourceRectangle.Width = (int)Math.Round((texture.Width / (float)cols) * this.scale.X);
sourceRectangle.Height = (int)Math.Round((texture.Height / (float)rows) * this.scale.Y);

写法2:向上取整(确保碰撞盒不会比渲染区域小)

如果担心四舍五入导致碰撞盒过小,可以用向上取整:

sourceRectangle.Width = (int)Math.Ceiling((texture.Width / (float)cols) * this.scale.X);
sourceRectangle.Height = (int)Math.Ceiling((texture.Height / (float)rows) * this.scale.Y);

额外小贴士

  • 确保this.scale的X/Y值是浮点类型(比如Vector2),不要提前转成int。
  • 碰撞盒的缩放逻辑最好和你渲染精灵时的缩放逻辑完全一致,避免出现“看起来在范围内但碰撞检测没触发”的情况。

内容的提问来源于stack exchange,提问作者user9202590

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:37:04