added old man npc and AI

This commit is contained in:
2025-11-28 17:05:23 +01:00
parent 1c23a1528e
commit c4d6539db7
4 changed files with 71 additions and 1 deletions

View File

@@ -24,11 +24,54 @@ public class Entity {
public Rectangle solidArea = new Rectangle(0, 0, 48, 48);
public int solidAreaDefaultX, solidAreaDefaultY;
public boolean collisionOn = false;
public int actionLock = 0;
public Entity(GamePanel panel) {
this.panel = panel;
}
public void setAction() {}
public void update() {
setAction();
collisionOn = false;
panel.collisionH.checkTile(this);
if(!collisionOn) {
switch (direction) {
case UP -> worldY -= speed;
case DOWN -> worldY += speed;
case LEFT ->worldX -= speed;
case RIGHT -> worldX += speed;
}
}
spriteCounter++;
if(spriteCounter > 12) {
if(spriteNum == 1) spriteNum = 2;
else if(spriteNum == 2) spriteNum = 1;
else spriteNum = 0;
}
}
public void draw(Graphics graphics2d) {
int screenX = worldX - panel.player.worldX + panel.player.screenX;
int screenY = worldY - panel.player.worldY + panel.player.screenY;
if(worldX + panel.tileSize > panel.player.worldX - panel.player.screenX &&
worldX - panel.tileSize < panel.player.worldX + panel.player.screenX &&
worldY + panel.tileSize > panel.player.worldY - panel.player.screenY &&
worldY - panel.tileSize < panel.player.worldY + panel.player.screenY
) {
BufferedImage image = switch (direction) {
case UP -> (spriteNum == 1) ? up1 : up2;
case DOWN -> (spriteNum == 1) ? down1 : down2;
case LEFT -> (spriteNum == 1) ? left1 : left2;
case RIGHT -> (spriteNum == 1) ? right1 : right2;
};
graphics2d.drawImage(image, screenX, screenY, panel.tileSize, panel.tileSize, null);
}
}
public BufferedImage initEntitySprites(String name) {
try {
return Utility.scaleImage(ImageIO.read(new FileInputStream("assets/" + name + ".png")), panel.tileSize, panel.tileSize);

View File

@@ -3,6 +3,8 @@ package de.miaurizius.jgame2d.entity;
import de.miaurizius.jgame2d.core.enums.Direction;
import de.miaurizius.jgame2d.core.GamePanel;
import java.util.Random;
public class OldManNPC extends Entity {
public OldManNPC(GamePanel panel) {
@@ -24,4 +26,17 @@ public class OldManNPC extends Entity {
right2 = initEntitySprites("npc/oldman_right_2");
}
public void setAction() {
actionLock++;
if(actionLock != 120) return; //lock action for x frames
Random rand = new Random();
int i = rand.nextInt(100)+1; //Generate number between 1 and 100
if(i <= 25) direction = Direction.UP;
if(i > 25 && i <= 50) direction = Direction.DOWN;
if(i > 50 && i <= 75) direction = Direction.LEFT;
if(i > 75) direction = Direction.RIGHT;
actionLock = 0;
}
}