📄 chasesprite.java
字号:
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import java.util.*;
public class ChaseSprite extends Sprite {
private Random rand;
private int speed;
private TiledLayer barrier;
private boolean directional;
private Sprite chasee;
private int aggression; // 0 - 10
public ChaseSprite(Image image, int frameWidth, int frameHeight, int chaseSpeed,
TiledLayer barrierLayer, boolean hasDirection, Sprite chaseeSprite,
int aggressionLevel) {
super(image, frameWidth, frameHeight);
// Initialize the random number generator
rand = new Random();
// Set the speed
speed = chaseSpeed;
// Set the tiled layer barrier
barrier = barrierLayer;
// Set whether or not the sprite is directional
directional = hasDirection;
// Set the chasee sprite
chasee = chaseeSprite;
// Set the aggression level
aggression = aggressionLevel;
}
public void update() {
// Temporarily save the position
int xPos = getX();
int yPos = getY();
int direction = 0; // up = 0, right = 1, down = 2, left = 3
// Chase or move randomly based on the aggression level
if (Math.abs(rand.nextInt() % (aggression + 1)) > 0) {
// Chase the chasee
if (getX() > (chasee.getX() + chasee.getWidth() / 2)) {
// Chase left
move(-speed, 0);
direction = 3;
}
else if ((getX() + getWidth() / 2) < chasee.getX()) {
// Chase right
move(speed, 0);
direction = 1;
}
if (getY() > (chasee.getY() + chasee.getHeight() / 2)) {
// Chase up
move(0, -speed);
direction = 0;
}
else if ((getY() + getHeight() / 2) < chasee.getY()) {
// Chase down
move(0, speed);
direction = 2;
}
}
else {
// Move in a random direction
switch (Math.abs(rand.nextInt() % 4)) {
// Move left
case 0:
move(-speed, 0);
direction = 3;
break;
// Move right
case 1:
move(speed, 0);
direction = 1;
break;
// Move up
case 2:
move(0, -speed);
direction = 0;
break;
// Move down
case 3:
move(0, speed);
direction = 2;
break;
}
}
// Check for a collision with the barrier
if (barrier != null && collidesWith(barrier, true)) {
// Move the sprite back to its original position
setPosition(xPos, yPos);
}
// Move to the next animation frame based on directional or not
if (directional)
setFrame(direction);
else
nextFrame();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -