2016-12-10 8 views
0

(Примечание: Это сообщение было копия вставленный из развития игры, потому что я получил комментарии говоривший этот пост на переполнение стека)Как добавить функцию смерти с обнаружением столкновения?

То, что я хочу, что, когда мой игрок сталкивается с моими Плитки (которые являются твердыми) они» будет отправлено на менустат (или в меню). Я уже обнаружил обнаружение столкновений для своих плит (с isSolid). Итак, как сделать так, чтобы, если мой игрок столкнулся с плиткой (те, которые тверды, что есть), она будет отправлена ​​на мой менструации.

и извините, если я добавил нежелательные классы, это то, что мой класс Player, Creature и Entity расширяется друг к другу.

Это мой класс существ, где присутствует обнаружение столкновения.

public abstract class Creatures extends Entity { 

public static final int DEFAULT_HEALTH = 1; 
public static final float DEFAULT_SPEED = 5.0f; 
public static final int DEFAULT_CREATURE_WIDTH = 128; 
public static final int DEFAULT_CREATURE_HEIGHT = 128; 

protected int health; 
protected float speed; 
public static float xMove; 
public static float yMove; 
protected int MinHeight; 

public Creatures(Handler handler, float x, float y, int width, int height) { 
    super(handler, x, y, width, height); 
    health = DEFAULT_HEALTH; 
    speed = DEFAULT_SPEED; 
    xMove = 0; 
    yMove = 0; 
    MinHeight = -1; 
} 

public void move(){ 
    moveX(); 
    moveY(); 
} 

//COLLISION DETECTION BELOW 
public void moveX(){ 
    if(xMove > 0){//Moving right 
     int tx = (int) (x + xMove + bounds.x + bounds.width)/Tile.TILEWIDTH; 

     if(!collisionWithTile(tx, (int) (y + bounds.y)/Tile.TILEHEIGHT) && 
       !collisionWithTile(tx, (int) (y + bounds.y + bounds.height)/Tile.TILEHEIGHT)){ 
      x += xMove; 
     }else{ 
      x = tx * Tile.TILEWIDTH - bounds.x - bounds.width - 1; 
     } 

    }else if(xMove < 0){//Moving left 
     int tx = (int) (x + xMove + bounds.x)/Tile.TILEWIDTH; 

     if(!collisionWithTile(tx, (int) (y + bounds.y)/Tile.TILEHEIGHT) && 
       !collisionWithTile(tx, (int) (y + bounds.y + bounds.height)/Tile.TILEHEIGHT)){ 
      x += xMove; 
     }else{ 
      x = tx * Tile.TILEWIDTH + Tile.TILEWIDTH - bounds.x; 
     } 
    } 
} 

public void moveY(){ 
    if(yMove < 0){//Up 
     int ty = (int) (y + yMove + bounds.y)/Tile.TILEHEIGHT; 

     if(!collisionWithTile((int) (x + bounds.x)/Tile.TILEWIDTH, ty) && 
       !collisionWithTile((int) (x + bounds.x + bounds.width)/Tile.TILEWIDTH, ty)){ 
      y += yMove; 
     }else{ 
      y = ty * Tile.TILEHEIGHT + Tile.TILEHEIGHT - bounds.y; 
     } 

    }else if(yMove > 0){//Down 
     int ty = (int) (y + yMove + bounds.y + bounds.height)/Tile.TILEHEIGHT; 

     if(!collisionWithTile((int) (x + bounds.x)/Tile.TILEWIDTH, ty) && 
       !collisionWithTile((int) (x + bounds.x + bounds.width)/Tile.TILEWIDTH, ty)){ 
      y += yMove; 
     }else{ 
      y = ty * Tile.TILEHEIGHT - bounds.y - bounds.height - 1; 
     } 
    } 
} 

//This code below checks if the tile im colliding is Solid or not 
protected boolean collisionWithTile(int x, int y){ 
    return handler.getWorld().getTile(x, y).isSolid(); 
} 

//GETTERS AND SETTERS 

public float getxMove() { 
    return xMove; 
} 

@SuppressWarnings("static-access") 
public void setxMove(float xMove) { 
    this.xMove = xMove; 
} 

public float getyMove() { 
    return yMove; 
} 

@SuppressWarnings("static-access") 
public void setyMove(float yMove) { 
    this.yMove = yMove; 
} 

public int getHealth() { 
    return health; 
} 

public void setHealth(int health) { 
    this.health = health; 
} 

public float getSpeed() { 
    return speed; 
} 

public void setSpeed(float speed) { 
    this.speed = speed; 
} 

} 

Тогда Мой класс Entity (мой класс Существо простирается к этому классу)

import java.awt.Graphics; 
import java.awt.Rectangle; 

public abstract class Entity { 

protected Handler handler; 
protected float x, y; 
protected int width, height; 
protected Rectangle bounds; 

public Entity(Handler handler, float x, float y, int width, int height){ 
    this.handler = handler; 
    this.x = x; 
    this.y = y; 
    this.width = width; 
    this.height = height; 

    bounds = new Rectangle(0, 0, width, height); 
} 

public abstract void tick(); 

public abstract void render(Graphics g); 

public float getX() { 
    return x; 
} 

public void setX(float x) { 
    this.x = x; 
} 

public float getY() { 
    return y; 
} 

public void setY(float y) { 
    this.y = y; 
} 

public int getWidth() { 
    return width; 
} 

public void setWidth(int width) { 
    this.width = width; 
} 

public int getHeight() { 
    return height; 
} 

public void setHeight(int height) { 
    this.height = height; 
} 

} 

Мой класс Player (мой игрок класса продолжается до моего класса Creature)

import java.awt.Graphics; 
import java.awt.image.BufferedImage; 

public class Player extends Creatures{ 

//Animations 
private Animation animRight, animLeft; 

public Player(Handler handler, float x, float y) { 
    super(handler, x, y, Creatures.DEFAULT_CREATURE_WIDTH, Creatures.DEFAULT_CREATURE_HEIGHT); 

    bounds.x = 32; 
    bounds.y = 32; 
    bounds.width = 92; 
    bounds.height = 96; 

    //Animations 
    animRight = new Animation(100, Assets.DerpDino_right); 
    animLeft = new Animation(100, Assets.DerpDino_left); 
} 

@Override 
public void tick() { 

    //Animations 
    animRight.tick(); 
    animLeft.tick(); 
    //Movement 
    getInput(); 
    move(); 
    handler.getGameCamera().centerOnEntity(this); 

} 

@SuppressWarnings("unused") 
private void Dead(){ 
    //what to put in here 
} 

private void getInput(){ 
    xMove = 6; 
    //Gravity 
    yMove = 6; 
    MinHeight = 0; 

    if(handler.getKeyManager().left) 
     xMove = -speed; 
    if(handler.getKeyManager().right) 
     xMove = speed; 
    if(handler.getKeyManager().jumping) 
     //this makes my player fly 
     yMove = -speed; 
} 

@Override 
public void render(Graphics g) { 
    g.drawImage(getCurrentAnimationFrame(), (int) (x - handler.getGameCamera().getxOffset()), (int) (y -handler.getGameCamera().getyOffset()), width, height, null);  


private BufferedImage getCurrentAnimationFrame(){ 
    if(xMove < 0){ 
     return animLeft.getCurrentFrame(); 
    }else{ 
     return animRight.getCurrentFrame(); 
    } 
} 

} 

плитка класса (где isSolid() is)

import java.awt.Graphics; 
import java.awt.image.BufferedImage; 

public class Tile { 

//STATIC STUFF HERE 

public static Tile[] tiles = new Tile[256]; 
public static Tile grassTile = new GrassTile(0); 
public static Tile cactusTile = new CactusTile(1); 
public static Tile dirtTile = new DirtTile(2); 
public static Tile skyTile = new SkyTile(3); 
public static Tile cloudTile = new CloudTile(4); 
public static Tile caveTile = new CaveTile(5); 
public static Tile stoneTile = new StoneTile(6); 

//CLASS 

public static final int TILEWIDTH = 128, TILEHEIGHT = 128; 

protected BufferedImage texture; 
protected final int id; 

public Tile(BufferedImage texture, int id){ 
    this.texture = texture; 
    this.id = id; 

    tiles[id] = this; 
} 

public void tick(){ 

} 

public void render(Graphics g, int x, int y){ 
    g.drawImage(texture, x, y, TILEWIDTH, TILEHEIGHT, null); 
} 

//HERE!! 
public boolean isSolid(){ 
    return false; 
} 

public int getId(){ 
    return id; 
} 

} 

ответ

0

Получил ответ !!! Я просто добавил State.setstate(menustate) в, если мой игрок сталкивается с блоком, найти // здесь в моем коде.

public boolean moveX(){ 
    if(xMove > 0){//Moving right 
     int tx = (int) (x + xMove + bounds.x + bounds.width)/Tile.TILEWIDTH; 

     if(!collisionWithTile(tx, (int) (y + bounds.y)/Tile.TILEHEIGHT) && 
       !collisionWithTile(tx, (int) (y + bounds.y + bounds.height)/Tile.TILEHEIGHT)){ 
      x += xMove; 
     }else{ 
      x = tx * Tile.TILEWIDTH - bounds.x - bounds.width - 1; 
      State.setState(handler.getGame().menuState);//here!!! 
     } 

    }else if(xMove < 0){//Moving left 
     int tx = (int) (x + xMove + bounds.x)/Tile.TILEWIDTH; 

     if(!collisionWithTile(tx, (int) (y + bounds.y)/Tile.TILEHEIGHT) && 
       !collisionWithTile(tx, (int) (y + bounds.y + bounds.height)/Tile.TILEHEIGHT)){ 
      x += xMove; 
     }else{ 
      x = tx * Tile.TILEWIDTH + Tile.TILEWIDTH - bounds.x; 
      State.setState(handler.getGame().menuState);//here!!! 
     } 
    } 
    return false; 
} 

public boolean moveY(){ 
    if(yMove < 0){//Up 
     int ty = (int) (y + yMove + bounds.y)/Tile.TILEHEIGHT; 

     if(!collisionWithTile((int) (x + bounds.x)/Tile.TILEWIDTH, ty) && 
       !collisionWithTile((int) (x + bounds.x + bounds.width)/ Tile.TILEWIDTH, ty)){ 
      y += yMove; 
     }else{ 
      y = ty * Tile.TILEHEIGHT + Tile.TILEHEIGHT - bounds.y; 
      State.setState(handler.getGame().menuState);//here!!! 
     } 
0

Вы должны сделать перечисление под названием STATE, которое будет содержать и обрабатывать ваши игровые состояния.

public enum STATE {GAME, MENU}; 
public STATE state = STATE.GAME; 

В вашей петле игры вы должны выполнять инструкции if.

if (state == STATE.GAME) { 
    // game logic here 
} else if (state == STATE.MENU) { 
    // menu logic here 
} 

Также не забудьте добавить их в ваших графиках, что должно оказывать, когда состояние устанавливается в игру, и что, когда он установлен в меню.

Тогда вы должны позвонить:

if (collisionWithTile) { 
    state = STATE.MENU; 
} 
+0

Я уже сделал состояния (не с перечислением), и если вы хотите, чтобы я добавил его к своему сообщению, тогда скажите мне. – SreeLegend

+0

Так в чем проблема? Если объект сталкивается с плиткой, затем установите состояние в меню. Объясните проблему дальше, тогда я смогу помочь вам лучше. – Erninger

+0

Я не знаю, как это сделать – SreeLegend

 Смежные вопросы

  • Нет связанных вопросов^_^