- private bool CollisionVertical(float xpos, float ypos, out int tilecoordx)
- {
- tilecoordx = (int)Math.Floor(xpos / tileSize);
- int tiletop = (int)Math.Floor(ypos / tileSize);
- int tilebottom = (int)Math.Floor((ypos + h - 1) / tileSize);
- for (int i = tiletop; i <= tilebottom; i++)
- {
- if (map.IsSolid(tilecoordx, i))
- return true;
- }
- return false;
- }
- private bool CollisionHorizontal(float xpos, float ypos, out int tilecoordy)
- {
- tilecoordy = (int)Math.Floor(ypos / tileSize);
- int tileleft = (int)Math.Floor(xpos / tileSize);
- int tileright = (int)Math.Floor((xpos + w - 1) / tileSize);
- for (int i = tileleft; i <= tileright; i++)
- {
- if (map.IsSolid(i, tilecoordy))
- return true;
- }
- return false;
- }
- public void Update(float frametime, ControlState ctrlstate)
- {
- const float Gravity = 1.0f;
- const float VelJump = 100.0f;
- velx = 0;
- if (ctrlstate.HasFlag(ControlState.Left))
- {
- velx = -MoveSpeedX;
- }
- else if (ctrlstate.HasFlag(ControlState.Right))
- {
- velx = MoveSpeedX;
- }
- if (ctrlstate.HasFlag(ControlState.Jump) && !lockJumping)
- {
- lockJumping = true;
- vely = -VelJump;
- }
- int tilecoord;
- float mapSizeX = tileSize * map.TileCountX;
- float mapSizeY = tileSize * map.TileCountY;
- if (velx < 0.0f)
- {
- // Move left
- float lefttest = x + (velx * frametime);
- if (lefttest <= 0.0f)
- {
- x = 0;
- velx = 0;
- }
- else
- {
- if (CollisionVertical(lefttest, y, out tilecoord))
- {
- x = (tilecoord + 1) * tileSize;
- velx = 0;
- }
- else
- {
- x += velx * frametime;
- }
- }
- }
- else if (velx > 0.0f)
- {
- float righttest = x + (velx * frametime) + w;
- if (righttest >= mapSizeX)
- {
- x = mapSizeX - w;
- velx = 0;
- }
- else
- {
- // Move right
- if (CollisionVertical(righttest, y, out tilecoord))
- {
- x = (tilecoord * tileSize) - w;
- velx = 0;
- }
- else
- {
- x += velx * frametime;
- }
- }
- }
- if (vely < 0.0f)
- {
- float toptest = y + (vely * frametime);
- if (toptest <= 0.0f)
- {
- // Hit on ceiling
- y = 0.0f;
- vely = 0;
- }
- else
- {
- // Jumping
- if (CollisionHorizontal(x, toptest, out tilecoord))
- {
- y = (tilecoord + 1) * tileSize;
- vely = 0;
- }
- else
- {
- y += vely * frametime;
- vely += Gravity;
- }
- }
- }
- else
- {
- // Falling or in air
- float maxBottom = map.TileCountY * tileSize;
- float bottomtest = y + (vely * frametime) + h;
- if (bottomtest >= maxBottom)
- {
- // Bodenloses loch
- y = maxBottom - h;
- vely = 0;
- if (!ctrlstate.HasFlag(ControlState.Jump))
- lockJumping = false;
- }
- else
- {
- if (CollisionHorizontal(x, bottomtest, out tilecoord))
- {
- Console.WriteLine("Collision floor - " + bottomtest);
- y = (tilecoord * tileSize) - h;
- vely = 1;
- if (!ctrlstate.HasFlag(ControlState.Jump))
- lockJumping = false;
- }
- else
- {
- vely += Gravity;
- y += vely * frametime;
- lockJumping = true;
- }
- }
- }
- }