好的,假设我有一张地板或其他东西的瓷砖纹理。我希望我的玩家可以在上面行走。 我该如何设置这个瓷砖,使其成为地板呢? 我需要这个瓷砖纹理覆盖整个屏幕宽度对吗? 我应该怎么做呢? 谢谢。
好的,假设我有一张地板或其他东西的瓷砖纹理。我希望我的玩家可以在上面行走。 我该如何设置这个瓷砖,使其成为地板呢? 我需要这个瓷砖纹理覆盖整个屏幕宽度对吗? 我应该怎么做呢? 谢谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework; // Don't forget those, they will let you
using Microsoft.Xna.Framework.Content; // access some class like:
using Microsoft.Xna.Framework.Graphics; // Texture2D or Vector2
namespace Your_Project _Name
{
class Tile
{
}
{
namespace Your_Project _Name
{
class Tile
{
Texture2D texture;
Vector2 position;
public void Initialize()
{
}
public void Draw()
{
}
}
{
您可以看到,我还创建了两个方法,Initialize和Draw,现在我们将在public void Initialize()中初始化瓷砖纹理和位置, 我不知道您如何使用ContentManager,但这是一种简单的方法:
public void Initialize(ContentManager Content)
{
texture = Content.Load<Texture2D>("YourfloorTexture"); //it will load your texture.
position = new Vector2(); //the position will be (0,0)
}
现在我们需要多次绘制纹理,怎样实现呢?Thasc提供的方法可能更加复杂,但以下是一种易于理解的方法。我将添加一个SpriteBatch以便进行绘制,在public void Draw()函数中实现如下:
public void Draw(SpriteBatch spriteBatch)
{
for (int i=0; i<30;i++) //will do a loop 30 times. Each Time i will =
//a valor from 0 to 30.
{
spriteBatch.Draw(texture, position, Color.White);
//Will draw the texture once, at the position Vector2
//right now position = (0,0)
spriteBatch.Draw(texture, new Vector2((int)i,(int)i), Color.White);
//Will Draw the texture 30 times, the first time on the position (0,0)
//Second Time on (1,1) .. third (2,2) etc...
spriteBatch.Draw(texture, new Vector2((int)position.X + (i * texture.Width), (int)position.Y + (i * texture.Height), Color.White));
//Will Draw the Texture 30 times Spaced by the Width and height
//of the texture (this is the code you need)
}
}
我没有尝试过,但应该能够正常工作。现在它只是一个样例,你可以自己解决其余问题。有很多其他方法可以做到这一点,但这个方法真的很容易。好了,现在最后一步是实现这个类,所以进入你所有代码都在的主类之前:
public Game1()
Tile tile;
并在protected override void Initialize()中进行初始化:
tile = new Tile();
tile.Initialize(Content);
spriteBatch.Begin();
tile.Draw(spriteBatch);
spriteBatch.End();
以下是完成简单平铺系统的所有步骤。正如我所说,还有许多其他方法,您只需要阅读有关它们的教程或自己创建它们。
SamplerState.LinearWrap
传递给 SpriteBatch.Begin
,然后在背景矩形上调用 Draw
。Rectangle backgroundRect = new Rectangle(0, 0, backWidth, backHeight);
spriteBatch.Begin(..., ..., SamplerState.LinearWrap, ..., ...);
spriteBatch.Draw(backgroundTexture, backgroundRect, Color.White);
spriteBatch.End();
如果您感到好奇,这个操作会创建一个单一的多边形,覆盖背景区域,它将从0.0f到backWidth
的纹理中获取坐标。纹理通常映射在(0.0f,0.0f)和(1.0f,1.0f)之间,代表给定纹理的角落。如果超出这些边界,TextureAddressMode
定义如何处理这些坐标:
Clamp
会削减坐标到0-1范围。Wrap
将坐标环绕回0,所以0.0 = 2.0 = 4.0等,而1.0 = 3.0 = 5.0等。Mirror
也会环绕,但在每次渲染多边形时交替镜像纹理,基本上是从左到右再到左-等等。