123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- #include "Game.h"
- #include "rendering/Renderer.h"
- #include "utils/StringBuffer.h"
- #include "utils/Utils.h"
- Game::Game(Controller& c, const Clock& fps, const Clock& tps, const Size& size)
- : controller(c), fps(fps), tps(tps), size(size), physicsToggle(true),
- player(Vector2(50.0f, 50.0f), 5.0f) {
- }
- void Game::tick() {
- if(controller.start.wasReleased()) {
- physicsToggle = !physicsToggle;
- }
- player.preTick();
- if(physicsToggle) {
- // forces from the player
- if(controller.a.isDown() && player.onGround) {
- player.jumpTicks = 10;
- player.onGround = false;
- }
- if(controller.right.isDown()) {
- player.addForce(Vector2(2.5f, 0.0f));
- }
- if(controller.left.isDown()) {
- player.addForce(Vector2(-2.5f, 0.0f));
- }
- if(player.jumpTicks > 0) {
- player.jumpTicks--;
- player.addForce(Vector2(0.0f, 10.0f));
- }
- player.jumpTicks *= controller.a.isDown();
- // pseudo drag
- player.addForce(Vector2(-player.velocity[0] * 0.5f, 0.0f));
- } else {
- player.velocity[0] = 0.0f;
- if(controller.a.isDown() && player.onGround) {
- player.velocity[1] = 15.0f;
- player.onGround = false;
- }
- if(controller.right.isDown()) {
- player.velocity[0] = 5.0f;
- }
- if(controller.left.isDown()) {
- player.velocity[0] = -5.0f;
- }
- }
- player.tick();
- // collision detection
- // floor crush
- if(player.position[1] < 0.0f) {
- player.position[1] = 0.0f;
- player.velocity[1] = 0.0f;
- player.onGround = true;
- }
- // right wall
- if(player.position[0] + player.size[0] > size.width) {
- player.position[0] = size.width - player.size[0];
- // player.velocity[0] = 0.0f;
- }
- // left wall
- if(player.position[0] < 0.0f) {
- player.position[0] = 0.0f;
- // player.velocity[0] = 0.0f;
- }
- }
- void Game::render(float lag, Renderer& r) const {
- r.translateTo(0.0f, 0.0f)
- .scale(1.0f, -1.0f)
- .translateY(size.height)
- .update();
- Vector2 pos = Utils::interpolate(player.lastPosition, player.position, lag);
- r.drawRectangle(pos, player.size, Color4(0xFF, 0x00, 0x00, 0xFF));
- r.translateTo(0.0f, 0.0f).update();
- r.setStringSize(2);
- StringBuffer<100> s("FPS: ");
- s.append(fps.getUpdatesPerSecond()).append(" ");
- s.append("%6.2f", tps.getUpdatesPerSecond()).append(" ");
- s.append(physicsToggle ? "Force Physics" : "Velocity Physics");
- float y = 10.0f;
- y = r.drawString(10.0f, y, s);
- s.clear().append("a = ").append(player.acceleration);
- y = r.drawString(10.0f, y, s);
- s.clear().append("v = ").append(player.velocity);
- y = r.drawString(10.0f, y, s);
- }
- bool Game::isRunning() const {
- return !controller.select.isDown();
- }
|