• ### Announcements

• #### Wondering what's new and changed at GameDev.net?06/20/17

Check out the latest Staff Blog update that talks about what's changed, what's new, and what's up with these "Pixels".
Followers 0

# making a bitmap follow a character

## 1 post in this topic

Hi.

I have created a function for an enemy and I'm trying to make the bitmap follow my character and when they interact the character dies and the game ends.

Can someone give me heads up?

Here is the class code:

#ifndef _ENEMY_H_
#define _ENEMY_H_

#include <allegro.h>

class Enemy
{
public:
int x;
int y;
BITMAP *enemy;
Enemy();
~Enemy();
void blitenemy(BITMAP*buffer);
};

#endif



and here is the cpp code:

#include <allegro.h>
#include "Enemy.h"

Enemy::Enemy()
{
srand(time(NULL));
x = rand() % 400 + 1;
y = rand() % 300 + 1;
}

Enemy::~Enemy()
{
destroy_bitmap(enemy);
}

void Enemy::blitenemy(BITMAP*buffer)
{
}


0

##### Share on other sites

Didn't really got the question.

You want the enemy to get to the character? If that is the case, on an open world (in other words, a scenario with no obstacles) all you have to do is update the enemy position by this formula:

    angle = atan2f(playerY - monsterY, playerX - monsterX);
nextX = monsterX + (cos(angle) * moveSpeed * dt);
nextY = monsterY + (sin(angle)  * moveSpeed * dt);
setMonsterPosition(nextX, nextY);


moveSpeed is the monster speed and dt is the amount of time passed since the last frame (your library probably gives you that with some function).

If the world has obstacles, then you must search for pathfinding, particularly A*.

1