Ошибка обнаружения изометрических столкновений в MonogameC#

Место общения программистов C#
Ответить
Anonymous
 Ошибка обнаружения изометрических столкновений в Monogame

Сообщение Anonymous »

Итак, у меня возникла проблема: столкновение не работает должным образом. Я попробовал много техник. Красные плитки должны были показать столкновение с зеленой плиткой. Проблема в том, что когда я пытаюсь преобразовать изометрические координаты в нормальные, что-то идет не так. Публичная Vector2 Rematrixlogic преобразует изометрическую логику в нормальную ось. void checkCollision проверяет, сталкивается ли плитка с игроком. Чтобы добиться этого, я использую для проверки прямоугольник; Однако он использовал метод алмазной проверки, но он не удался. Я не знаю, использовал ли я неправильную формулу или неправильный метод. Когда плитка сталкивается с игроком (зеленая плитка), плитка должна стать красной. Однако большинство плиток становятся красными, даже если они не сталкиваются. Щелкните эту ссылку, чтобы увидеть результаты запуска программы.
Это мой код:

Код: Выделить всё

public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;

List tiles = new List();

Texture2D TestImage;
SpriteFont Defaultext;
Texture2D Image1;
Texture2D Image2;
Texture2D Image3;
string message = "None";
int MoveX = 0;
int Movey = 0;
float Scale = 0;
Player player;
Tile testtile;

public Game1()
{
_graphics = new GraphicsDeviceManager(this);
_graphics.PreferredBackBufferWidth = 1200;
_graphics.PreferredBackBufferHeight = 700;
Content.RootDirectory = "Content";

IsMouseVisible = true;
}

protected override void Initialize()
{
base.Initialize();
}

protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
TestImage = Content.Load("spritesheet");
Image1 = Content.Load("tile_000");
Defaultext = Content.Load("File");
Image2 = Content.Load("tile_101");
Image3 = Content.Load("tile_022");
ReadMap("..\\..\\..\\TestNotcsv.txt", 1);

testtile = new Tile(Image1, MatrixLofic(1, 1, 50, -50), 1);
player = new Player(Image1, new Vector2(20, 20), new Vector2(0, 0), 1);

ReadMap("..\\..\\..\\1.txt", 2);
tiles.Add(testtile);
testtile.tilecole = Color.Blue;
}

protected override void Update(GameTime gameTime)
{
ArrowFunction();
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();

for (int i = 0; i < tiles.Count; i++)
{
tiles[i].update(MoveX, Movey);
Checkcollsion(tiles[i]._pos, tiles[i]);
}

player.Update();
base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();

drawoder();
_spriteBatch.DrawString(Defaultext, message, new Vector2(0, 0), Color.Red);
_spriteBatch.End();

base.Draw(gameTime);
}

public Vector2 MatrixLofic(float w, float h, float _x, float _y)
{
float x = ((float)_x * (0.5f * (float)w)) + ((float)_y * (-0.5f * (float)w));
float y = ((float)_x * (0.25f * (float)h)) + ((float)_y * (0.25f * (float)h));
x += 128f * 1.5f;

Vector2 final = new Vector2(x, y);
return final;
}

public Vector2 Rematrixlogic(float tileWidth, float tileHeight, float cartX, float cartY)
{
cartX = (cartX - cartY) * 0.5f * tileWidth;
cartY = (cartX + cartY) * 0.25f * tileHeight;
cartX = 128f * 1.5f;
return new Vector2(cartX, cartY);
}

public Vector2 MatricLogic2(int x, int y)
{
var _x = (x * 32 / 2) - (x * 32 / 2);
var _y = (y * 16 / 2) + (y * 16 / 2);
Vector2 n = new Vector2(_x, _y);
return n;
}

public void MoveTiles()
{
KeyboardState key = Keyboard.GetState();
if (Keyboard.GetState().IsKeyDown(Keys.W))
{
Movey = 1;
}
else if (Keyboard.GetState().IsKeyDown(Keys.S))
{
Movey = -1;
}
else
{
Movey = 0;
}

if (Keyboard.GetState().IsKeyDown(Keys.D))
{
MoveX = -1;
}
else if (Keyboard.GetState().IsKeyDown(Keys.A))
{
MoveX = 1;
}
else
{
MoveX = 0;
}

if (Keyboard.GetState().IsKeyDown(Keys.R))
{
MoveX = 0;
Movey = 0;
DeletaAlltile();
ReadMap("..\\..\\..\\TestNotcsv.txt", 1);
ReadMap("..\\..\\..\\1.txt", 2);
}
}
public void DeletaAlltile()
{
for (int i = 0; i < tiles.Count;  i++)
{
tiles.Remove(tiles[i]);
}
}

void drawoder()
{
bool once = true;
for (int i = 0; i < tiles.Count; i++)
{
if (tiles[i].depth  player.depth && once == true)
{
player.draw(_spriteBatch);
once = false;
}

else if (tiles[i].depth > player.depth && once == false)
{
tiles[i].draw(_spriteBatch);
}
}
}

bool IsPointInDiamond(Vector2 point, Vector2 center, float halfWidth, float halfHeight)
{
// Calculate the diamond's boundaries based on its center and size
return (Math.Abs(point.X - center.X) / halfWidth + Math.Abs(point.Y - center.Y) / halfHeight) 

Подробнее здесь: [url]https://stackoverflow.com/questions/79218223/isometric-collision-detection-error-in-monogame[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»