我希望能够缩放我的精灵并将它们保持在与缩放之前相同的位置。我将sprite的中心用作origin参数,因为我也希望能够旋转sprite。
我确定解决方案将是微不足道的,但我找不到合适的/一般的解决方案来解决此问题。
如果不清楚,我做了一些图片来展示我的代码,该代码的结果以及我想要实现的目标。
1-这是我的代码,其结果是缩放小精灵时得到的结果,如您所见,小精灵已缩放但已“移动”:
如注释中所建议的那样,代码是:
Vector2 scale = Vector2.One;
float rotation = 0;
public void Update(GameTime gameTime)
{
if (Input.IsKeyPressed(Keys.P))
scale += new Vector2(0.05f, 0.0f);
if (Input.IsKeyPressed(Keys.M))
scale -= new Vector2(0.05f, 0.0f);
if (Input.IsKeyPressed(Keys.O))
scale += new Vector2(0.0f, 0.05f);
if (Input.IsKeyPressed(Keys.L))
scale -= new Vector2(0.0f, 0.05f);
if (Input.IsKeyPressed(Keys.D))
rotation += MathHelper.ToRadians(5);
if (Input.IsKeyPressed(Keys.Q))
rotation -= MathHelper.ToRadians(5);
Input.Update(gameTime);
}
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, null, Matrix.CreateScale(4));
spriteBatch.Draw(Sprites.BACKGROUND, Vector2.Zero, new Rectangle(0, 0, 128, 128), Color.White);
Vector2 marioPosition = new Vector2(64, 112 - 32);
Rectangle source = new Rectangle(0,0,16,32);
Vector2 origin = source.Size.ToVector2() / 2;
spriteBatch.Draw(Sprites.MARIO, marioPosition + origin, source, Color.White, rotation, origin, scale, SpriteEffects.None, 0f);
spriteBatch.End();
}
2-这是我想要实现的目标,我知道我可以通过移动原点来做到这一点,但我想将其保持在精灵的中心,这样我就可以围绕该点进行旋转:http : //pasteboard.co/ rzMfc0p.png
有人帮助我,找到了解决我的问题的解决方案(Pema99 @pemathedev),正如其他人所建议的那样,解决方案的确是移动精灵,这是移动精灵所需的费用:
public void Update(GameTime gameTime)
{
if (Input.IsKeyPressed(Keys.P))
scale.X += .05f;
if (Input.IsKeyPressed(Keys.M))
scale.X -= .05f;
//Solution ---------------------------------------------------
if (Input.IsKeyPressed(Keys.O))
{
float previousSize = source.Height * scale.Y;
float newSize = source.Height * (scale.Y + .05f);
scale.Y += .05f;
marioPosition.Y -= (Math.Abs(previousSize - newSize)/2)
}
if (Input.IsKeyPressed(Keys.L))
{
float previousSize = source.Height * scale.Y;
float newSize = source.Height * (scale.Y - .05f);
scale.Y -= .05f;
marioPosition.Y += (Math.Abs(previousSize - newSize)/2)
}
//--------------------------------------------------------------
if (Input.IsKeyPressed(Keys.D))
rotation += MathHelper.ToRadians(5);
if (Input.IsKeyPressed(Keys.Q))
rotation -= MathHelper.ToRadians(5);
Input.Update(gameTime);
}
谢谢大家 !
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句