Como criar um mundo de embrulho em Box2D
-
22-08-2019 - |
Pergunta
Eu preciso para criar um mundo de embrulho infinitas com Box2D (onde a coordenada X de todos os objetos é 0 A câmara pode ver apenas uma pequena parte do mundo a um tempo (cerca de 5% a largura, a altura de 100% - o mundo é de cerca de 30 altura por 1000 de largura). Felicidades.
Solução
Eu tenho implementado o seguinte, que não é de forma ideal, mas apto para o meu propósito. Há muitas limitações envolvidas e não é um mundo de embrulho verdade, mas é bom o suficiente.
public void Wrap()
{
float tp = 0;
float sx = ship.GetPosition().X; // the player controls this ship object with the joypad
if (sx >= Landscape.LandscapeWidth()) // Landscape has overhang so camera can go beyond the end of the world a bit
{
tp = -Landscape.LandscapeWidth();
}
else if (sx < 0)
{
tp = Landscape.LandscapeWidth();
}
if (tp != 0)
{
ship.Teleport(tp, 0); // telport the ship
foreach (Enemy e in enemies) // Teleport everything else which is onscreen
{
if (!IsOffScreen(e.bodyAABB)) // using old AABB
{
e.Teleport(tp, 0);
}
}
}
foreach(Enemy e in enemies)
{
e.UpdateAABB(); // calc new AABB for this body
if (IsOffScreen(g.bodyAABB)) // camera has not been teleported yet, it's still looking at where the ship was
{
float x = e.GetPosition().X;
// everything which will come onto the screen next frame gets teleported closer to where the camera will be when it catches up with the ship
if (e.bodyAABB.UpperBound.X < 0 || e.bodyAABB.LowerBound.X + Landscape.LandscapeWidth() <= cameraPos.X + screenWidth)
{
e.Teleport(Landscape.LandscapeWidth(), 0);
}
else if (e.bodyAABB.LowerBound.X > Landscape.LandscapeWidth() || e.bodyAABB.UpperBound.X - Landscape.LandscapeWidth() >= cameraPos.X - screenWidth)
{
e.Teleport(-Landscape.LandscapeWidth(), 0);
}
}
}
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow