I'm developing a map kind of simple game using slick 2D library, and I want to get the current location of the user. When the user runs into a special location (ex: hole) to indicate that is dangerous. How can I achieve this? I'm a new comer to games.
-
\$\begingroup\$ Your question is really vague. What exactly are you trying to achieve? You want to make the user aware of dangerous sections of the map? Or you want to know how to define such regions in a map-editor? Is this an implementation or design (how it should look/behave) question? \$\endgroup\$– bummzackCommented Aug 19, 2011 at 16:21
-
\$\begingroup\$ For anyone looking for background on the Slick2D library, see slick.cokeandcode.com/index.php \$\endgroup\$– Tim HoltCommented Aug 19, 2011 at 16:49
1 Answer
Assuming that I understand what you are trying to do, that is, a 2D dungeon-like tiled game, here is what I would do:
The current location of the player can be stored in a Point class, and the entire player entity into a sprite, as is typically done in simple 2D game. I.e.:
class Sprite {
Point position;
Texture texture;
...
public Point getPosition() {
return this.position;
}
}
So, to move your player all you do is listen for keyboard events and update the location:
class MyGame implements KeyListener
{
Sprite player;
...
public void keyPressed(int key, char c) {
if (key == Input.KEY_W) {
player.getPosition().X += 1;
} else if (key == Input.KEY_S) {
player.getPosition().X -= 1;
} else if (key == Input.KEY_A) {
player.getPoisition().Y -= 1;
} else if (key == Input.KEY_D) {
player.getPosition().Y += 1;
}
}
}
As for informing the player of dangerous locations, have a list of triggers that will fire whenever the player is inside an area. The triggers could be a rectangular location, a circle or anything. In general, you would have something like this:
class Level implements TriggerListener {
List<LevelTriggers> levelTriggers;
Sprite player;
...
void initialize() {
// Initialize all triggers (usually you read this part from a file)
for (int i = 0; i < numberOfTriggers; i++) {
LevelTrigger trigger = new LevelTrigger();
trigger.addListener(this);
levelTriggers.add(trigger);
}
}
void update(...) {
...
for (LevelTrigger trigger : levelTriggers) {
if (trigger.isIn(player.getPosition())) {
trigger.fire();
}
}
}
...
void triggered() {
// Show your message
}
}
abstract class LevelTrigger {
List<TriggerListeners> triggerListeners;
void addListener(TriggerListener triggerListener)
{
triggerLIsteners.add(triggerListeners);
}
void fire()
{
for (TriggerListener listener : triggerListeners)
{
listener.triggered();
}
}
abstract bool isIn(Point position);
}
interface TriggerListener
{
triggered();
}
EDIT: Totally forgot to mention the "current location" part.
EDIT2: OK, I GOT to stop writing C# code in Java questions :/