[text] aa

Viewer

  1. #include "Bike.h"
  2. #include "ResourceManager.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include "AudioManager.h"
  6. #include "Trail.h"
  7. #include "DynamicTrail.h"
  8.  
  9. #include "math.h"
  10.  
  11. Bike::Bike(b2World* world, float x, float y, float width, float height) :
  12.     GameplayState(width, height),
  13.     m_motorSpeed(0.0f),
  14.     m_maxMotorSpeed(500.0f),
  15.     m_maxSpeed(0.05), 
  16.     m_acceleration(5.0f),
  17.     m_braking(200.0f),
  18.     m_isAccelerating(false),
  19.     m_isBraking(false) {
  20.  
  21.     b2BodyDef carBodyDef;
  22.     carBodyDef.type = b2_dynamicBody;
  23.     carBodyDef.position.Set(x, y + 50);
  24.    
  25.     m_carBody = world->CreateBody(&carBodyDef);
  26.  
  27.  
  28.     // Define the car shape and fixture
  29.     b2PolygonShape carBox;
  30.     carBox.SetAsBox(2.0f, 1.0f);
  31.     b2FixtureDef carFixtureDef;
  32.     carFixtureDef.shape = &carBox;
  33.     carFixtureDef.density = 10.0f;
  34.     carFixtureDef.friction = 0.3f;
  35.     m_carBody->CreateFixture(&carFixtureDef);
  36.  
  37.     // Define the wheel bodies and fixtures
  38.     b2BodyDef wheelBodyDef;
  39.     wheelBodyDef.type = b2_dynamicBody; 
  40.     b2CircleShape wheelShape;
  41.     wheelShape.m_radius = 0.5f;
  42.     b2FixtureDef wheelFixtureDef;
  43.     wheelFixtureDef.shape = &wheelShape;
  44.     wheelFixtureDef.density = 1.5f;
  45.     wheelFixtureDef.friction = 0.3f;
  46.  
  47.     // Create the left wheel
  48.     wheelBodyDef.position.Set(x - 1.5f, y - 2.0f);
  49.     m_leftWheel = world->CreateBody(&wheelBodyDef);
  50.     m_leftWheel->CreateFixture(&wheelFixtureDef);
  51.  
  52.     // Create the right wheel
  53.     wheelBodyDef.position.Set(x + 1.5f, y - 2.0f);
  54.     m_rightWheel = world->CreateBody(&wheelBodyDef);
  55.     m_rightWheel->CreateFixture(&wheelFixtureDef);
  56.  
  57.     // Define the joints for the wheels
  58.     b2RevoluteJointDef leftJointDef;
  59.     leftJointDef.bodyA = m_carBody;
  60.     leftJointDef.bodyB = m_leftWheel;
  61.     leftJointDef.localAnchorA.Set(-1.5f, -1.0f);
  62.     leftJointDef.localAnchorB.Set(0.0f, 0.0f);
  63.     leftJointDef.enableMotor = true;
  64.     leftJointDef.maxMotorTorque = 10.0f;
  65.     leftJointDef.motorSpeed = 0.01f;
  66.     m_leftJoint = static_cast<b2RevoluteJoint*>(world->CreateJoint(&leftJointDef));
  67.  
  68.     b2RevoluteJointDef rightJointDef;
  69.     rightJointDef.bodyA = m_carBody;
  70.     rightJointDef.bodyB = m_rightWheel;
  71.     rightJointDef.localAnchorA.Set(1.5f, -1.0f);
  72.     rightJointDef.localAnchorB.Set(0.0f, 0.0f);
  73.     rightJointDef.enableMotor = true;
  74.     rightJointDef.maxMotorTorque = 10.0f;
  75.     rightJointDef.motorSpeed = 0.01f;
  76.     m_rightJoint = static_cast<b2RevoluteJoint*>(world->CreateJoint(&rightJointDef));
  77.  
  78.     std::cout<<"Body: " << m_carBody->GetPosition().x << " " << m_carBody->GetPosition().y << std::endl;
  79.     std::cout<<"LWheel: " << m_leftWheel->GetPosition().x << " " << m_leftWheel->GetPosition().y << std::endl;
  80.     std::cout<<"Rwheel: " << m_rightWheel->GetPosition().x << " " << m_rightWheel->GetPosition().y << std::endl;
  81.  
  82. }
  83.  
  84. void Bike::update(float deltaTime, sf::RenderWindow &window) {
  85.  
  86.     b2Vec2 velocity = m_carBody->GetLinearVelocity();
  87.     float speed = velocity.Length();
  88.  
  89.     // Apply motor forces only if wheels are touching the ground
  90.     if (m_leftWheel->GetContactList() || m_rightWheel->GetContactList()) {
  91.         if (m_isAccelerating && speed < m_maxSpeed) {
  92.             m_motorSpeed = std::min(m_motorSpeed + m_acceleration * deltaTime, m_maxMotorSpeed);
  93.         }
  94.         else if (m_isBraking) {
  95.             m_motorSpeed = std::max(m_motorSpeed - m_braking * deltaTime, -m_maxMotorSpeed);
  96.         }
  97.         else {
  98.             // Apply friction when no input
  99.             m_motorSpeed *= 0.99f;
  100.         }
  101.  
  102.         if (speed >= m_maxSpeed) {
  103.             m_motorSpeed = std::min(m_motorSpeed, m_maxSpeed / (m_leftWheel->GetFixtureList()->GetShape()->m_radius * m_leftJoint->GetJointSpeed()));
  104.         }
  105.  
  106.         m_leftJoint->SetMotorSpeed(m_motorSpeed);
  107.         m_rightJoint->SetMotorSpeed(m_motorSpeed);
  108.     }
  109.     else {
  110.         // In air, wheels shouldn't affect movement
  111.         m_leftJoint->SetMotorSpeed(0);
  112.         m_rightJoint->SetMotorSpeed(0);
  113.     }
  114.       m_world->Step(deltaTime, 8, 3);
  115. }
  116.  
  117.  
  118. Bike::Bike(float& width, float& height, b2World& world, std::unique_ptr<Trail>& trail)
  119.     : GameplayStateMode(width, height, world, trail), 
  120.     m_playerX(0.0f), m_speedFactor(4.0f),
  121.     m_velocity(0.0f, 0.0f), m_maxSpeed(5.0f),
  122.     m_acceleration(0.55f), m_deceleration(0.13f) {
  123.  
  124.     // Create dynamic body (bike)
  125.     b2BodyDef dynamicBodyDef;
  126.     dynamicBodyDef.type = b2_dynamicBody;
  127.     dynamicBodyDef.position.Set(m_trail->getSFVertices()[0].x / SCALE, m_trail->getSFVertices()[0].y / SCALE);
  128.     m_dynamicBody = m_world.CreateBody(&dynamicBodyDef);
  129.  
  130.     b2CircleShape dynamicCircle;
  131.     dynamicCircle.m_radius = 1.0f;
  132.  
  133.     b2FixtureDef fixtureDef;
  134.     fixtureDef.shape = &dynamicCircle;
  135.     fixtureDef.density = 1.0f;
  136.     fixtureDef.friction = 0.3f;
  137.     m_dynamicBody->CreateFixture(&fixtureDef);
  138.  
  139.     m_motorSprite.setTexture(ResourceManager::getInstance().getTexture("motor"));
  140.     m_motorSprite.setScale(0.5f, 0.5f);
  141.     sf::FloatRect spriteBounds = m_motorSprite.getLocalBounds();
  142.     m_motorSprite.setOrigin(spriteBounds.width / 2, spriteBounds.height);
  143.  
  144.     sf::Vector2f initialPos = B2ToSF(m_dynamicBody->GetPosition(), SCALE);
  145.     m_motorSprite.setPosition(initialPos);
  146.     m_trail->updateTrailView(initialPos);
  147. }
  148.  
  149.  
  150. // void Bike::handleInput(const sf::Event& event) {
  151. //     if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased) {
  152. //         bool rightPressed = sf::Keyboard::isKeyPressed(sf::Keyboard::Right);
  153. //         bool leftPressed = sf::Keyboard::isKeyPressed(sf::Keyboard::Left);
  154.  
  155. //         if (event.type == sf::Event::KeyPressed) {
  156. //             if (rightPressed && !leftPressed) {
  157. //                 accelerate();
  158. //             }
  159. //             else if (leftPressed && !rightPressed) {
  160. //                 brake();
  161. //             }
  162. //         }
  163.  
  164. //         if (event.type == sf::Event::KeyReleased) {
  165. //             if (event.key.code == sf::Keyboard::Right) {
  166. //                 AudioManager::getInstance().stopSound("motorChangeGear");
  167. //             }
  168. //             if (!rightPressed && !leftPressed) {
  169. //                 // Decelerate when no key is pressed or both keys are pressed
  170. //                 if (m_velocity.x > 0) {
  171. //                     m_velocity.x = std::max(0.0f, m_velocity.x - m_deceleration);
  172. //                 }
  173. //                 else if (m_velocity.x < 0) {
  174. //                     m_velocity.x = std::min(0.0f, m_velocity.x + m_deceleration);
  175. //                 }
  176. //             }
  177. //         }
  178.  
  179. //         // Clamp velocity to max speed
  180. //         //m_velocity.x = std::clamp(m_velocity.x, -m_maxSpeed, m_maxSpeed);
  181. //         if (m_velocity.x > m_maxSpeed)
  182. //         {
  183. //             m_velocity.x = m_maxSpeed;
  184. //         }
  185. //     }
  186. //     std::cout << m_motorSprite.getPosition().x << " " << m_motorSprite.getPosition().y << std::endl;
  187. //     std::cout << "dynamic body: " << m_dynamicBody->GetPosition().x << " " << m_dynamicBody->GetPosition().y << std::endl;
  188. // }
  189. // >>>>>>> master
  190.  
  191.  
  192.  
  193. void Bike::render(sf::RenderWindow& window) {
  194.     
  195.     window.draw(m_trailShape);
  196.  
  197.     sf::RectangleShape carShape = createRectangleShape(m_carBody, 4.0f, 2.0f);
  198.     carShape.setFillColor(sf::Color::Blue);
  199.     window.draw(carShape);
  200.  
  201.     sf::CircleShape leftWheelShape = createCircleShape(m_leftWheel, 0.5f);
  202.     leftWheelShape.setFillColor(sf::Color::Red);
  203.     window.draw(leftWheelShape);
  204.  
  205.  
  206.     sf::CircleShape rightWheelShape = createCircleShape(m_rightWheel, 0.5f);
  207.     rightWheelShape.setFillColor(sf::Color::Red);
  208.     window.draw(rightWheelShape);
  209.  
  210. }
  211.  
  212. void Bike::handleInput(sf::Event event) {
  213.  
  214.     if (event.type == sf::Event::KeyPressed) {
  215.         if (event.key.code == sf::Keyboard::Right) {
  216.             m_carBody->ApplyLinearImpulseToCenter({ 10,0 }, true);
  217.             m_isAccelerating = true;
  218.             m_isBraking = false;
  219.         }
  220.         else if (event.key.code == sf::Keyboard::Left) {
  221.             m_carBody->ApplyLinearImpulseToCenter({-10,0}, true);
  222.             m_isAccelerating = false;
  223.             m_isBraking = true;
  224.         }
  225.         //else if (event.key.code == sf::Keyboard::Left && event.key.code == sf::Keyboard::Up) {
  226.         //    m_carBody->ApplyLinearImpulseToCenter({ -50,0 }, true);
  227.         //    m_isAccelerating = false;
  228.         //    m_isBraking = true;
  229.         //}
  230.         //else if (event.key.code == sf::Keyboard::Left && event.key.code == sf::Keyboard::Down) {
  231.         //    m_carBody->ApplyLinearImpulseToCenter({ -50,0 }, true);
  232.         //    m_isAccelerating = false;
  233.         //    m_isBraking = true;
  234.         //}
  235.         //else if (event.key.code == sf::Keyboard::Right && event.key.code == sf::Keyboard::Up) {
  236.         //    m_carBody->ApplyLinearImpulseToCenter({ 50,0 }, true);
  237.         //    m_carBody->ApplyAngularImpulse(50, true);
  238.         //    m_isAccelerating = false;
  239.         //    m_isBraking = true;
  240.         //}
  241.         //else if (event.key.code == sf::Keyboard::Right && event.key.code == sf::Keyboard::Down) {
  242.         //    m_carBody->ApplyLinearImpulseToCenter({ 50,0 }, true);
  243.         //    m_isAccelerating = false;
  244.         //    m_isBraking = true;
  245.         //}
  246. =======
  247. //     DynamicTrail* dynamicTrail = dynamic_cast<DynamicTrail*>(m_trail.get());
  248.  
  249. //     if (dynamicTrail) {
  250. //         // Access DynamicTrail specific methods
  251. //         sf::Vector2f sfPosition = B2ToSF(position, SCALE);
  252. //         sf::Vector2f closestPoint = dynamicTrail->findClosestPointOnTrail(sfPosition);
  253.  
  254. //         // Set the bike's position to the closest point on the trail
  255. //         m_dynamicBody->SetTransform(SFToB2(closestPoint, SCALE), m_dynamicBody->GetAngle());
  256.  
  257. //         // Update sprite position
  258. //         m_motorSprite.setPosition(closestPoint);
  259.  
  260. //         // Calculate angle based on trail slope
  261. //         float angle = dynamicTrail->calculateTrailAngle(closestPoint);
  262. //         m_motorSprite.setRotation(angle);
  263.  
  264. //         dynamicTrail->updateTrailView(closestPoint);
  265.  
  266. //         // Check if the player has reached the last vertex
  267. //         auto playerPosition = getPosition();
  268. //         if (playerPosition.x >= dynamicTrail->getSFVertices().back().x) {
  269. //             sf::Vector2f startPoint = dynamicTrail->getSFVertices()[0];
  270. //             m_motorSprite.setPosition(startPoint.x, startPoint.y);
  271. //             m_dynamicBody->SetTransform(SFToB2(startPoint, SCALE), m_dynamicBody->GetAngle());
  272. //             dynamicTrail->updateTrailView(startPoint);
  273. //         }
  274. //     }
  275.     
  276. //     // Step the Box2D world
  277. //     m_world.Step(deltaTime, 8, 3);
  278. // }
  279.  
  280.  
  281. // void Bike::render(sf::RenderWindow& window) {
  282. //     window.setView(m_trail->getTrailView());
  283.  
  284. //     // Fill enclosed areas
  285. //     //m_trail->fillEnclosedAreas(window);
  286.  
  287. //     // Draw the trail line
  288. //     window.draw(m_trail->getTrailShape());
  289. // >>>>>>> master
  290.  
  291. //     }
  292.     else if (event.type == sf::Event::KeyReleased) {
  293.         if (event.key.code == sf::Keyboard::Right || event.key.code == sf::Keyboard::Left) {
  294.             m_isAccelerating = false;
  295.             m_isBraking = false;
  296.         }
  297.     }
  298. }
  299.  
  300. sf::RectangleShape Bike::createRectangleShape(b2Body* body, float width, float height) {
  301.     sf::RectangleShape shape(sf::Vector2f(width * SCALE, height * SCALE));
  302.     shape.setOrigin(width * SCALE / 2.0f, height * SCALE + 22.5f);
  303.     shape.setPosition(body->GetPosition().x * SCALE, (body->GetPosition().y * SCALE));
  304.     shape.setRotation(body->GetAngle() * 180.0f / b2_pi);
  305.     sf::Texture texture;
  306.     texture.loadFromFile("Bike.png");
  307.     shape.setTexture(&texture);
  308.  
  309.     return shape;
  310. }
  311.  
  312. sf::CircleShape Bike::createCircleShape(b2Body* body, float radius) {
  313.     sf::CircleShape shape(radius * SCALE);
  314.     shape.setOrigin(radius * SCALE, radius * SCALE);
  315.  
  316.     // Adjust the position to place the wheels below the car body
  317.     // Assuming SCALE is a factor to convert Box2D world units to SFML pixels
  318.     float xPos = body->GetPosition().x * SCALE;
  319.     float yPos = body->GetPosition().y * SCALE;// Adjust for the wheel's radius
  320.     shape.setPosition(xPos, yPos);
  321.     return shape;
  322. }
  323.   
  324. void Bike::accelerate() {
  325.     // Apply torque to accelerate in the right direction
  326.     //m_dynamicBody->ApplyTorque(-20.0f, true);  // Use negative torque for clockwise rotation
  327.     m_velocity.x += m_acceleration;
  328.     m_velocity.x = std::min(m_velocity.x, m_maxSpeed);
  329.     AudioManager::getInstance().playSound("motorChangeGear");
  330. }
  331.  
  332. void Bike::brake() {
  333.     m_velocity.x -= m_deceleration;
  334. }
  335.  
  336. sf::Vector2f Bike::getPosition() const { return m_motorSprite.getPosition(); }
  337. void Bike::setPosition(const sf::Vector2f& position) { m_motorSprite.setPosition(position); }
  338. float Bike::getSpeed() const { return std::abs(m_velocity.x); }

Editor

You can edit this paste and save as new:


File Description
  • aa
  • Paste Code
  • 02 Jul-2024
  • 12.65 Kb
You can Share it: