我目前正在做一个学校项目,我需要开发一个等距游戏。不幸的是,由于我的老师对游戏开发一无所知(已经专注于切换到新学校),我被困住了。
现在我可以轻松绘制游戏地图,但它停止了。当我添加角色时,我看到它正在渲染,但我无法移动它。很可能我搞砸了 IsoToScreen 和 ScreenToIso 数学问题。
当我尝试将我的角色移动 1 像素时,由于某种原因,它会立即离开屏幕。
这是我用来将简单 2D 转换为 2.5D Isometric 的 IsoMath 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Beowulf
{
class IsoMath
{
private double tw, th, tx, ty, sx, sy;
public IsoMath(double width, double height)
{
tw = width;
th = height;
}
public Vector2 ScreenToIsoTile(Vector2 start, Vector2 offset, Vector2 screenOriginPoint)
{
Vector2 ret = new Vector2(0, 0);
sx = start.X - (screenOriginPoint.X + offset.X);
sy = start.Y - (screenOriginPoint.Y + offset.Y);
tx = System.Math.Round((sx / (tw * 2)) + (sy / (th * 2))) - 1;
ty = System.Math.Round((-sx / (tw * 2)) + (sy / (th * 2)));
ret.X = (float)tx;
ret.Y = (float)ty;
return ret;
}
public Vector2 ScreenToIsoPoint(float x, float y)
{
Vector2 ret = new Vector2(0, 0);
tx = (x - y) * tw;
ty = (x + y) * th;
ret.X = (float)tx * .5f;
ret.Y = (float)ty * .5f;
return ret;
}
public Vector2 IsoToScreenPoint(float x, float y)
{
Vector2 ret = new Vector2(0, 0);
tx = (x + y) / tw;
ty = (x - y) / th;
ret.X = (float)tx / .5f;
ret.Y = (float)ty * -1;
return ret;
}
public Vector2 ScreenToIso(float x, float y)
{
Vector2 ret = new Vector2(0, 0);
tx = (x - y);
ty = (x + y);
ret.X = (float)tx;
ret.Y = (float)ty;
return ret;
}
public Vector2 IsoToScreen(float x, float y)
{
Vector2 ret = new Vector2(0, 0);
tx = (x + y);
ty = (x - y);
ret.X = (float)tx * .5f;
ret.Y = -(float)ty / 2;
return ret;
}
}
}
我的 Player 类只是一个带有 Draw(SpriteBatch sp, vector2 playerPostition); 的占位符。顾名思义,在给定位置绘制角色的方法(该位置在主 Draw 方法中预先计算)
这就是我将角色绘制到屏幕上的方式。它适用于固定的 x14,y14 位置(浮点数),但是当我将 1f 添加到这两个值中的任何一个时,找不到该字符。
Vector2 plPos = isoMath.ScreenToIsoPoint(pl.X, pl.Y);
plPos.X += x;
plPos.Y += y;
pl.Draw(spriteBatch, plPos);
我使用以下代码(在绘制字符之前)来渲染我的地图。大量的 if 语句用于剔除屏幕图块。
for (int i = 0; i < scene.width; i++)
{
for (int j = 0; j < scene.height; j++)
{
Vector2 p = isoMath.ScreenToIsoPoint(i, j);
Rectangle r = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
if (r.Contains(new Point((int)(((p.X) + x)), (int)((p.Y) + y))) || r.Contains(new Point((int)((p.X) + x) + tile.Width, (int)((p.Y) + y + tile.Height))) || r.Contains(new Point((int)((p.X) + x) + tile.Width, (int)((p.Y) + y))) || r.Contains(new Point((int)((p.X) + x), (int)((p.Y) + y + tile.Height))))
{
spriteBatch.Draw(tile, new Rectangle((int)((p.X) + x), (int)((p.Y) + y), (int)(tile.Width * 1.02), (int)(tile.Height * 1.02)), Color.White);
}
}
}
如果您认为我没有提供足够的信息,您可以单击此处 (1.13Mb)下载整个项目的 zip 存档。