Skip to content

Instantly share code, notes, and snippets.

@Abhilekhgautam
Last active January 17, 2023 11:52
Show Gist options
  • Save Abhilekhgautam/bba81f6ed5294ad4038d6538fe94b9fc to your computer and use it in GitHub Desktop.
Save Abhilekhgautam/bba81f6ed5294ad4038d6538fe94b9fc to your computer and use it in GitHub Desktop.
bool OnUserUpdate(float fElapsedTime) override
{
Clear(olc::BLACK);
DrawSprite(fPlayerPositionX, fPlayerPositionY, sprPlayer.get());
if (GetKey(olc::Key::LEFT).bHeld) {
fPlayerPositionX = fPlayerPositionX - fPlayerVel * fElapsedTime;
}
if (GetKey(olc::Key::RIGHT).bHeld) {
fPlayerPositionX = fPlayerPositionX + fPlayerVel * fElapsedTime;
}
if (GetKey(olc::Key::UP).bHeld) {
fPlayerPositionY = fPlayerPositionY - fPlayerVel * fElapsedTime;
}
if (GetKey(olc::Key::DOWN).bHeld) {
fPlayerPositionY = fPlayerPositionY + fPlayerVel * fElapsedTime;
}
if (GetKey(olc::Key::SPACE).bPressed) {
float ftempX = fPlayerPositionX;
float ftempY = fPlayerPositionY;
vBullet.emplace_back(Bullet{ftempX + float(sprPlayer->width) / 2, ftempY, false});
}
for (auto elm: vEnemy) {
if (elm.alive)
DrawSprite(elm.x, elm.y, sprEnemy.get());
}
for (auto &elm: vBullet) {
// only take care of bullets which are visible on the screen
if (elm.y > -1 && !elm.dead) {
FillCircle(int(elm.x), int(elm.y), 1, olc::RED);
elm.y = elm.y - fBulletVel * fElapsedTime;
}
}
for (auto &elm: vBullet)
{
for (auto &enemy: vEnemy)
{
if (!elm.dead && enemy.alive && elm.y > enemy.y && elm.x + 1 >= enemy.x &&
elm.x - 1 <= enemy.x + float(sprEnemy->width) &&
elm.y - 1 <= enemy.y + float(sprEnemy->height))
{
// kill both bullet and enemy.
elm.dead = true;
enemy.alive = false;
}
}
}
for(auto &elm : vEnemy){
if(elm.alive){
float tempX = ((fPlayerPositionX + float(sprPlayer->width) / 2
) - elm.x + float(sprEnemy->height) + float(sprEnemy->width) / 2
);
float tempY = (fPlayerPositionY - elm.y + float(sprEnemy->height));
// simple pythagoras theorem
float tempHypo = powf(tempX, 2) + powf(tempY, 2);
float Hypo = sqrtf(tempHypo);
float sinTheta = (tempY / Hypo);
float cosTheta = (tempX / Hypo);
elm.x = elm.x + fEnemyVel * cosTheta * fElapsedTime;
elm.y = elm.y + fEnemyVel * sinTheta * fElapsedTime;
if (elm.x + sprEnemy->width >= fPlayerPositionX &&
elm.x <= fPlayerPositionX + sprPlayer->width &&
elm.y + sprEnemy->height >= fPlayerPositionY)
{
elm.alive = false;
}
break;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment