0

这是我的第一篇文章,所以如果我在这里提问时做错了什么,我提前道歉。我在网上找了一个具体的答案,但找不到一个,所以这里......

我正在编写基于 Surfaceview 的游戏,到目前为止,一切进展顺利,但是,我想在 160DPI 屏幕上将我的主要精灵移动 1 个像素作为基线(所以基本上 1 DIP 作为 1 像素 = 1 DIP在 160DPI 屏幕上对吗?)

我正在使用以下论坛:

private static final float spritemovestep = 1f;
final float scale = getResources().getDisplayMetrics().density;
MoveX = (int) (spritemovestep * scale + 0.5f);

然后......像

SpriteX=SpriteX+MoveX

第一个问题 - 这是正确的吗?

如果是,有人可以解释 +.05f 的实际用途吗,我读过它是“四舍五入到最接近的数字”,但是......

如果 spritemovestep = 1,那么在 120DPI 屏幕上(我认为它返回 0.75 作为比例)它会计算为:1 x .75 + .5?哪个是 1.25?那么0.5有什么用?

当它被转换为 int 值时,结果是什么?

在某些情况下,最终结果在低密度屏幕上似乎是“0”,因此精灵根本没有移动。

此外,一些本应以不同速度移动的精灵在特定密度下以相同速度移动。

我确定我很傻并且在这里遗漏了一些东西,但我就是不明白这应该如何工作。如果我想在 MDPI 屏幕上将我的精灵移动 1 个 DIP/物理像素,它如何在 LDPI 屏幕上移动小于 1 个像素?

另外,我一直看到的这个公式是什么:

px = dp * (dpi / 160) - When is this used?

如果有人能回答我的问题,我将不胜感激。

谢谢大家

4

1 回答 1

1

The +0.5f is to round up to the nearest nukber, as you said. Ideally, when the number is scaled down for ldpi, a value of 1 becomes 0.75, which, when cast to an int is expressed as less than 1 or ~=0. By adding the rounding figure, this number is raised to 1.25 which, when cast as an int yields <2 or ~=1. This way, your sprite should be drawn with a minimum movement of 1. The only reason sprites that move at different speeds would move the same speeds is if they are so close that, when rounded, they wind up being the same size using the scale you gave. Altogether, your equation is very similar to others ive seen. Im making a game that uses surfaceview for the company i work for as well, and while i cant go into details on the code, your issue is one that i struggled with for sone time. Im not sure how your physics updates, but perhaps thats something you should check into, specifically, how it counts ticks for your game timer. It may be that your application is reading its ticks as being too close together to reach the point where it would hit the point of moving the 1.25 or 1 after casting to int, and therefore your sprite appears not to move. I briefly experienced that problem and at first was looking at my velocity until i found that the error was in the timer. One other thing i noticed is that your algorithm collects the density. On a mdpi device, does this return 1 or 160? That could make a big difference, but im not sure, as the equation i used was different. The other equation you found is a paraphrase of the equation listed in the development guide at android.developer.com to describe how the os converts pixels into dip. The reson people tend to quote that is to provide a reference to help others build their own algorithm for scaling appropriate for the jeeds of their app. Hopefully that helps, as its really the best answer i can give at this time. Sorry for any typing errors, im sending this from my phone

于 2012-02-04T17:55:59.240 回答