void Initialize() { std::cout<<" Vector3 size = "<< sizeof(Vector3)<<std::endl; std::cout<<" Property<Vector3> size = "<< sizeof(Property<Vector3>)<<std::endl; std::cout<<" Event<> size = "<< sizeof(std::function<void(int&)>)<<std::endl; world.Initialize(); auto& renderSystem = world.GetSystem<RenderSystem<GameWorldSettings>>(); renderSystem.DefaultShader = &renderSystem.Shaders.LitColored; world.GetSystem<TouchSystem<GameWorldSettings>>().Input = &Input; camera = world.CreateObject(); camera->AddComponent<Camera>()->Viewport = Manager().Viewport(); camera->AddComponent<Transform>()->Position = { 0, 0, 170 }; camera->GetComponent<Camera>()->FieldOfView = 40; GameObject* prev = 0; for(int i=0; i< 30; i++) { GameObject* cube = CreateObject({-4,0,0}); cube->Parent = prev; prev = cube; } }
pair<int, int> getRandomPosition(GameWorld& gameWorld, GameObject gameObject, int minRadius, int maxRadius, bool free, bool needGold){ int startX, startY; startX = gameObject.x; startY = gameObject.y; vector<pair<int, int> > positions; for(int x = startX - maxRadius; x <= startX + maxRadius; x++){ for(int y = startY - maxRadius; y <= startY + maxRadius; y++){ if(x < 0 || y < 0 || x >= gameWorld.width || y >= gameWorld.height){ continue; } if(max(abs(startX - x), abs(startY - y)) < minRadius){ continue; } if(gameWorld.getWorldMap(x, y).present != free && (free || gameWorld.getWorldMap(x, y).player != gameWorld.myId) && (!needGold || gameWorld.isGold(x, y))){ positions.push_back(make_pair(x, y)); } } } if(positions.empty()){ return make_pair(-1, -1); } return positions[rand() % positions.size()]; }
void PowerShieldPhysicsComponent::init() { b2BodyDef bodyDef; bodyDef.type = b2_staticBody; // Adjust offsets here yo bodyDef.position.Set(gameObjectRef->posX + 40, gameObjectRef->posY); bodyDef.angle = 0;// ... which direction it's facing GameWorld* gameWorld = GameWorld::getInstance(); mBody = gameWorld->getPhysicsWorld()->CreateBody(&bodyDef); /// Hitbox instantiation b2PolygonShape box; /// Set Box Shape box.SetAsBox(1, 1); // look up other functions for polygons // boxFixtureDef.shape = &box; boxFixtureDef.density = 1; // Create Fixture mFixture = mBody->CreateFixture(&boxFixtureDef); mBody->SetUserData(gameObjectRef); mBody->SetTransform(b2Vec2(gameObjectRef->posX/worldScale, gameObjectRef->posY/worldScale), 0); setCollisionFilter(COLLISION_POWERSHIELD, COLLISION_FEATHER); }
void PlayerController::activateAdrenalineEffect() { GameWorld* world = character->engine; GameState* state = character->engine->state; adrenalineEffect = true; adrenalineEffectTime = world->getGameTime() + 20.f; state->basic.timeScale = 0.3f; }
void Project::CreateSettings(const std::string &path, const std::string& name) { GameWorld world; GameObject* root = world.CreateRoot(); root->AddComponent<ProjectSettings>()->name = name; std::ofstream file; file.open(path); root->ToJson(file); file.close(); }
// FUNCTIONS ////////////////////////////////////////////// LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { // this is the main message handler of the system PAINTSTRUCT ps; // used in WM_PAINT HDC hdc; // handle to a device context // what is the message switch(msg) { case WM_CREATE: { // do initialization stuff here // return success return(0); } break; case WM_LBUTTONDOWN: gameWorld.SetMessageFromInput(WM_LBUTTONDOWN, LOWORD(lparam), HIWORD(lparam)); break; case WM_PAINT: { // simply validate the window hdc = BeginPaint(hwnd,&ps); // you would do all your painting here EndPaint(hwnd,&ps); // return success return(0); } break; case WM_TIMER: gameWorld.Main(); break; case WM_DESTROY: { // kill the application, this sends a WM_QUIT message PostQuitMessage(0); // return success return(0); } break; default:break; } // end switch // process any messages that we didn't take care of return (DefWindowProc(hwnd, msg, wparam, lparam)); } // end WinProc
void MinionPhysicsComponent::init(){ if (!mBody){ b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(gameObjectRef->posX, gameObjectRef->posY); bodyDef.angle = 0;// ... which direction it's facing GameWorld* gameWorld = GameWorld::getInstance(); mBody = gameWorld->getPhysicsWorld()->CreateBody(&bodyDef); b2PolygonShape box; box.SetAsBox(.8f, .8f); // look up other functions for polygons boxFixtureDef.shape = &box; boxFixtureDef.density = 1; mFixture = mBody->CreateFixture(&boxFixtureDef); mBody->SetUserData(gameObjectRef); } mBody->SetTransform(b2Vec2(gameObjectRef->posX/worldScale, gameObjectRef->posY/worldScale), 0); float rando[10] = { -285, 285, -100, 50, -25, 160, -240, 60, -130, 250 }; float yForce = rando[(gameObjectRef->ID%10)]; if (gameObjectRef->team == TEAM_YELLOW){ mBody->SetLinearVelocity(b2Vec2(7, 0)); mBody->ApplyForce(b2Vec2(50, yForce), mBody->GetWorldCenter(), true); } else if (gameObjectRef->team == TEAM_PURPLE){ mBody->SetLinearVelocity(b2Vec2(-7, 0)); mBody->ApplyForce(b2Vec2(-50, yForce), mBody->GetWorldCenter(), true); } setCollisionFilter(COLLISION_MINION, COLLISION_FEATHER | COLLISION_MINION | COLLISION_BASE | COLLISION_MINE | COLLISION_FAN | COLLISION_PLATFORM | COLLISION_BOOMERANG); blownForce = b2Vec2(0.0f, 0.0f); savedYForce = 0.0f; }
void PlayerController::update(float dt) { restartLogic(); GameWorld* world = character->engine; GameState* state = character->engine->state; if (adrenalineEffect) { if (world->getGameTime() > adrenalineEffectTime) { state->basic.timeScale = 1.f; adrenalineEffect = false; } } CharacterController::update(dt); }
void Project::CreateNewWorld(const std::string &worldPath) { GameWorld world; GameObject* root = world.CreateRoot(); GameObject* cube = root->CreateObject(); cube->AddComponent<Transform>(); cube->AddComponent<Mesh>()->GetMesh<Vertex>().AddCube(0, 1); cube->AddComponent<Renderable>(); std::ofstream file; file.open(worldPath); root->ToJson(file); file.close(); }
KILLENUM Runtime::execSet() { accept( Token::SET ); world->addGameFlag( tokenizer.string() ); accept(); return PROCEED; }
KILLENUM Runtime::execClear() { accept( Token::CLEAR ); world->removeGameFlag( tokenizer.string() ); accept(); return PROCEED; }
void Update(float dt) { world.Update(dt); if (follow) { Vector3 pos = cube->GetComponent<Transform>()->Position; pos.y = 0; cameraObject->GetComponent<Transform>()->Position = pos; } }
void Render() { if (wireframe) { glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); } else { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } world.Render(); }
void Update(float dt) { if (timer<0) { std::stringstream s; s<<counter++; //label->GetComponent<DynamicLabel>()->Text = s.str(); timer = 2.0f; } else { timer -= dt; } label->GetComponent<Label>()->FontSize = Input.GetTouchPosition(0).x * 0.2f; //label->GetComponent<Sizeable>()->Size = { Input.GetTouchPosition(0).x * 0.1f, 100}; Context().InputDevice().UpdateInputManager(&world.Input()); world.Update(dt); }
BlockSequence::BlockSequence(const BlockSequenceDescriptor & descriptor, GameWorld & world, int id) : GameObject(id) , zIndex(0) , step(0) , timer(0.0f) , descriptor(descriptor) , world(world) , blockEntities() , outlineShape() , blockRects() { const auto & bounds = getBounds(); outlineShape.setSize({ static_cast<float>(bounds.getWidth()), static_cast<float>(bounds.getHeight()) }); outlineShape.setPosition({ static_cast<float>(bounds.getX()), static_cast<float>(bounds.getY()) }); outlineShape.setFillColor({ 255, 192, 10, 128 }); const auto & blockPositions = descriptor.getBlockPositions(); std::for_each( std::begin(blockPositions), std::end(blockPositions), [&](const Point2D<int> & topLeft){ sf::RectangleShape shape; shape.setPosition({ static_cast<float>(topLeft.getX()), static_cast<float>(topLeft.getY()) }); shape.setSize({ 16.0f, 16.0f }); shape.setFillColor({ 255, 32, 32, 128 }); blockRects.push_back(shape); std::unique_ptr<Enemy> entityUnique = world.spawnEnemy(descriptor.getEntityName()); std::shared_ptr<Enemy> entityShared(std::move(entityUnique)); entityShared->setPosition(topLeft.getX(), topLeft.getY()); blockEntities.push_back(entityShared); }); }
void SerializedGameData::ReadSnapshot(GameWorld& gw) { Prepare(true); em = &gw.GetEvMgr(); expectedObjectsCount = PopUnsignedInt(); GameObject::SetObjCount(0); gw.Deserialize(*this); em->Deserialize(*this); for (unsigned i = 0; i < gw.GetPlayerCount(); ++i) gw.GetPlayer(i).Deserialize(*this); // If this check fails, we did not serialize all objects or there was an async RTTR_Assert(expectedObjectsCount == GameObject::GetObjCount()); RTTR_Assert(expectedObjectsCount == objectsCount + 1); // "Nothing" nodeObj does not get serialized em = NULL; readObjects.clear(); }
GameObject::GameObject(GameWorld& gw, const ObjectPrototype& proto, double x, double y, double z, int id) : m_meshName(proto.m_meshName), m_sceneEntity(nullptr), m_sceneNode(nullptr), m_lockRotation(proto.m_lockRotation), m_isKinematic(proto.m_isKinematic), m_maxTurn(proto.m_maxTurnAngle), m_maxForward(proto.m_maxForward), m_maxBackward(proto.m_maxBackward), m_hitPoints(proto.m_maxHitPoints), m_collisionAccum(0), m_totalDamage(0), m_hasAgent(proto.m_hasAgent), m_gw(gw), m_id(id), m_oldGS(nullptr), m_newGS(nullptr) { m_sceneEntity = gw.GetScene()->createEntity(gw.GetMesh(m_meshName)); m_sceneNode = gw.GetScene()->getRootSceneNode()->createChildSceneNode(); m_sceneNode->attachObject(m_sceneEntity); Ogre::Vector3 size = m_sceneEntity->getBoundingBox().getSize(); m_body = dBodyCreate(gw.GetPhysicsWorld()); m_geom = dCreateBox(gw.GetPhysicsSpace(), size.x, size.y, size.z); dMassSetBox(&m_mass, proto.m_density, size.x, size.y, size.z); dBodySetMass(m_body, &m_mass); dGeomSetBody(m_geom, m_body); dBodySetPosition(m_body, x, y, z); // automagically disable things when the body is still for long enough dBodySetAutoDisableFlag(m_body, 1); dBodySetAutoDisableLinearThreshold(m_body, 0.1f); dBodySetAutoDisableAngularThreshold(m_body, 0.25f); dBodySetAutoDisableSteps(m_body, 1); // improve simulation accuracy dBodySetDamping(m_body, 0.0f, 0.1f); if (proto.m_registerCollisions) { gw.RegisterForCollisions(this); } if (proto.m_isKinematic) { dBodySetKinematic(m_body); } }
void CHUD::update(float dt) { GameWorld* gameScene = (GameWorld*)(this->getParent()->getChildByName("GameScene")); //Update text char text[256]; sprintf(text, "Gold: %d", player->GetGold()); goldNumLabel->setString(text); sprintf(text, "HP: %d", player->GetHP()); hpNumLabel->setString(text); sprintf(text, "Monsters: %d", gameScene->getNumberOfActiveMonsters()); monsterNumLabel->setString(text); sprintf(text, "Wave %d", gameScene->getWaveNum() + 1); waveNumLabel->setString(text); if (gameScene->AllWavesCleared()){ sprintf(text, "Finished!"); waveChangeTimerLabel->setString(text); } else if (gameScene->getWaveChangeTimer() < 10.0f){ sprintf(text, "Next wave start in: %i", (int)gameScene->getWaveChangeTimer()); waveChangeTimerLabel->setString(text); } else waveChangeTimerLabel->setString(""); }
void SerializedGameData::MakeSnapshot(GameWorld& gw) { Prepare(false); // Anzahl Objekte reinschreiben expectedObjectsCount = GameObject::GetObjCount(); PushUnsignedInt(expectedObjectsCount); // Objektmanager serialisieren gw.Serialize(*this); // EventManager serialisieren gw.GetEvMgr().Serialize(*this); // Spieler serialisieren for(unsigned i = 0; i < gw.GetPlayerCount(); ++i) gw.GetPlayer(i).Serialize(*this); // If this check fails, we missed some objects or some objects were destroyed without decreasing the obj count RTTR_Assert(writtenObjIds.size() == objectsCount); RTTR_Assert(expectedObjectsCount == objectsCount + 1); // "Nothing" nodeObj does not get serialized writtenObjIds.clear(); }
void Initialize() { renderer = world.CreateSystem<RenderSystem>(); camera = world.CreateObject(); camera->AddComponent<Camera>()->Viewport = Manager().Viewport(); camera->AddComponent<Transform>()->Position = { 0, 0, 10 }; camera->GetComponent<Camera>()->FieldOfView = 40; cube = world.CreateObject(); cube->AddComponent<Transform>(); cube->AddComponent<Mesh>()->AddCube(0, 1); cube->AddComponent<Material>(); Mesh::VerticesList& verts = cube->GetComponent<Mesh>()->Vertices(); for (int i=0; i<verts.size(); i++) { verts[i].Color = Colour::HslToRgb(i * 10, 1, 1, 1); } Input.GamePad.AnalogChanged += event_handler(this, &Game::AnalogChanged); }
void NavigationMeshUpdated(Map* map) { if (navMesh) navMesh->Remove(); if (collisionMesh) collisionMesh->Remove(); NavMesh& mesh = *map->NavMesh(); for (int i=0; i<2; i++) { GameObject* meshObject = world.CreateObject(); meshObject->Enabled() = false; meshObject->AddComponent<Transform>(); meshObject->AddComponent<Material>()->Shader = &renderer->Shaders.Colored; meshObject->GetComponent<Material>()->BlendMode = BlendModeType::Alpha; //meshObject->EnableComponent<Material>(false); auto& navMeshMesh = meshObject->AddComponent<Mesh>()->GetMesh<Vertex>(); NavMesh::Vertices& vertices = i==0 ? mesh.navigation : mesh.collision; for(auto& p : vertices) { Vertex v; v.Position = {p.x, 1.50f+i*0.1f, p.y}; v.Color = i==0 ? Colour::Red() : Colour::Green(); //Colour::HslToRgb(i*180, 1, 1, 1); navMeshMesh.vertices.push_back(v); if (navMeshMesh.vertices.size()>25000) break; } for (auto& p : mesh.GetTriangles()) { bool valid = true; for (int i=0; i<3; i++) { if (p->corners[i]>=navMeshMesh.vertices.size()) { valid = false; break; } } if (!valid) continue; for (int i=0; i<3; i++) { navMeshMesh.triangles.push_back(p->corners[i]); } } navMeshMesh.Flip(); if (i==0) { navMesh = meshObject; } else { collisionMesh = meshObject; } } }
void PlatformPhysicsComponent::init() { b2BodyDef bodyDef; bodyDef.type = b2_staticBody; bodyDef.position.Set(gameObjectRef->posX, gameObjectRef->posY); bodyDef.angle = 0;// ... which direction it's facing GameWorld* gameWorld = GameWorld::getInstance(); mBody = gameWorld->getPhysicsWorld()->CreateBody(&bodyDef); /// Hitbox instantiation b2PolygonShape box; /// Set Box Shape box.SetAsBox(12.0f, .9f);// look up other functions for polygons // boxFixtureDef.shape = &box; boxFixtureDef.density = 1; // Create Fixture mFixture = mBody->CreateFixture(&boxFixtureDef); mBody->SetUserData(gameObjectRef); mBody->SetTransform(b2Vec2(gameObjectRef->posX/worldScale, gameObjectRef->posY/worldScale), 0); setCollisionFilter(COLLISION_PLATFORM, COLLISION_PLAYER | COLLISION_MINION | COLLISION_MINE); }
GameObject* CreateObject(Vector3 pos) { GameObject* cube = world.CreateObject(); cube->AddComponent<Transform>()->Position = pos; cube->AddComponent<Mesh>()->GetMesh<Vertex>().AddCube({-2,0,0}, {2,1,1}); auto& verts = cube->GetComponent<Mesh>()->GetMesh<Vertex>().vertices; for (int i=0; i<verts.size(); i++) { verts[i].Color = Colour::Blue();// Colour::HslToRgb(i * 10, 1, 1, 1); } cube->AddComponent<Material>(); cube->AddComponent<Touchable>()->Click.Bind([cube] (TouchData d) { cube->GetComponent<Transform>()->Rotation *= Quaternion(0.1f); }); cube->AddComponent<Rotator>()->angles = Vector3(1,1,2) * 0.1f; cube->AddComponent<Draggable>()->Movement = Draggable::MovementMode::XYPlane; return cube; }
void SerializedGameData::ReadSnapshot(GameWorld& gw, EventManager& evMgr) { Prepare(true); em = &evMgr; expectedObjectsReadCount = PopUnsignedInt(); GameObject::SetObjCount(expectedObjectsReadCount); gw.Deserialize(*this); evMgr.Deserialize(*this); for (unsigned i = 0; i < GAMECLIENT.GetPlayerCount(); ++i) GAMECLIENT.GetPlayer(i).Deserialize(*this); em = NULL; readObjects.clear(); }
void SerializedGameData::MakeSnapshot(GameWorld& gw, EventManager& evMgr) { Prepare(false); // Anzahl Objekte reinschreiben PushUnsignedInt(GameObject::GetObjCount()); // Objektmanager serialisieren gw.Serialize(*this); // EventManager serialisieren evMgr.Serialize(*this); // Spieler serialisieren for(unsigned i = 0; i < GAMECLIENT.GetPlayerCount(); ++i) GAMECLIENT.GetPlayer(i).Serialize(*this); writtenObjIds.clear(); }
int main(int argc, char** argv) { /* Initializers */ srand(time(NULL)); glutInit(&argc, argv); glutInitWindowSize(GameWorld::SUGGESTED_WIDTH, GameWorld::SUGGESTED_HEIGHT); glutInitWindowPosition(GameWorld::STARTING_WINDOW_X, GameWorld::STARTING_WINDOW_Y); glutCreateWindow("Assignment 1 - Space Invaders"); /* Callbacks */ glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboardListener); glutMouseFunc(mouseListener); glutTimerFunc(GameWorld::REFRESH_RATE, update, 0); world.resetTime(); /* Main loop */ glutMainLoop(); return 0; }
void ButtonDown(std::string b) { if (b=="f") { follow = !follow; } else if (b=="w") { wireframe = !wireframe; } else if (b=="n") { navMesh->Enabled() = !navMesh->Enabled(); //navMesh->EnableComponent<Material>(!navMesh->IsComponentEnabled<Material>()); }else if (b=="c") { collisionMesh->Enabled() = !collisionMesh->Enabled(); //collisionMesh->EnableComponent<Material>(!collisionMesh->IsComponentEnabled<Material>()); } else if (b=="b") { Point size(1 + MathHelper::Random(3), 1 + MathHelper::Random(3)); GameObject* building = world.CreateObject(); building->AddComponent<Transform>()->Position = marker->GetComponent<Transform>()->Position; building->GetComponent<Transform>()->Rotation = Quaternion(MathHelper::Random(0, MathHelper::DegToRad * 360.0f), {0,1,0}); building->AddComponent<Obstacle>()->size = size; building->AddComponent<Material>()->Shader = &renderer->Shaders.LitColored; building->AddComponent<Mappable>()->Map = map->GetComponent<Map>(); auto& mesh = building->AddComponent<Mesh>()->GetMesh<Vertex>(); mesh.AddCube({0,1,0}, {(float)size.x,1,(float)size.y}); } }
void play(GameWorld& gameWorld){ for(int i = 0; i < gameWorld.gameObjectCount; i++){ GameObject aObject = gameWorld.gameObjects[i]; if(aObject.player == gameWorld.myId){ GameObjectType gameObjectType = gameWorld.getGameObjectType(aObject.gameObjectType); // Produce if we can if(gameObjectType.canProduce){ vector<int> options = gameWorld.getGameObjectType(aObject.gameObjectType).produceList; int newGameObjectType = options[rand() % options.size()]; pair<int, int> pos = getRandomPosition(gameWorld, aObject, gameObjectType.radiusProduceMin, gameObjectType.radiusProduceMax, true, newGameObjectType == 1); if(pos != make_pair(-1, -1) && gameWorld.getGameObjectType(newGameObjectType).value <= gameWorld.getPlayerMoney(gameWorld.myId)){ gameWorld.produce(aObject.x, aObject.y, pos.first, pos.second, newGameObjectType); } } // Fight if we can if(gameObjectType.canFight){ pair<int, int> pos = getRandomPosition(gameWorld, aObject, gameObjectType.radiusFightMin, gameObjectType.radiusFightMax, false, false); if(pos != make_pair(-1, -1)){ gameWorld.fight(aObject.x, aObject.y, pos.first, pos.second); } } // Move if we can if(gameObjectType.canMove){ pair<int, int> pos = getRandomPosition(gameWorld, aObject, gameObjectType.radiusWalkMin, gameObjectType.radiusWalkMax, true, false); if(pos != make_pair(-1, -1)){ gameWorld.move(aObject.x, aObject.y, pos.first, pos.second); } } } } }
void Render() { world.Render(); }
void Update(float dt) { world.Update(dt); }