I am trying to put obstacles inside my game that both player and hostile actors cannot pass through. The player movement code works but I'm not sure how to tie the same concept into the hostile code since it relies on direction finding with Math.tan and not keyboard input. Here is my player code, which uses keyboard input and Obstacle direction within the same method:
Here is my hostile code:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Hostile here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Hostile extends Actor
{
private Player player;
public Hostile(Player player){
this.player = player;
}
/**
* Act - do whatever the Red wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
}
public void chasePlayer()
{
if (player == null || player.getWorld() == null || getWorld() == null){
return;
}
int deltaX = player.getX() - getX();
int deltaY = player.getY() - getY();
setRotation((int) (180 * Math.atan2(deltaY, deltaX) / Math.PI));
}
public void isAtHole(){
Hole hole = (Hole) getOneIntersectingObject(Hole.class);
if(hole!=null){
World board = (World) getWorld();
board.removeObject(this);
}
}
public void killPlayer(){
if (getWorld() == null){
return;
}
Player player = (Player) getOneIntersectingObject(Player.class);
if(player!=null){
World board = (World) getWorld();
board.removeObject(player);
}
}
}
I'm not sure whether I should add Obstacle detection within the chasePlayer() method or override default move().
Any suggestions are welcome.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Player here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Player extends Actor
{
public Player(){
}
/**
* Act - do whatever the Player wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
move(8);
}
/**
* Check whether a keyboard key has been pressed and react if it has.
*/
public void move(int speed)
{
int dx = 0;
int dy = 0;
if (Greenfoot.isKeyDown("right")||Greenfoot.isKeyDown("D")){
dx += 1;
}
if (Greenfoot.isKeyDown("left")||Greenfoot.isKeyDown("A")){
dx -= 1;
}
if (Greenfoot.isKeyDown("down")||Greenfoot.isKeyDown("S")){
dy += 1;
}
if (Greenfoot.isKeyDown("up")||Greenfoot.isKeyDown("W")){
dy -= 1;
}
for (int i = 0; i < speed; i++)
{
setLocation(getX() + dx, getY());
if (getOneIntersectingObject(Obstacle.class) != null) setLocation(getX() - dx, getY());
setLocation(getX(), getY() + dy);
if (getOneIntersectingObject(Obstacle.class) != null) setLocation(getX(), getY() - dy);
}
}
}
