我的 Android 游戏的 Sprite 在各处弹跳,但在屏幕的右侧和底部边缘/墙壁上, Sprite 在弹跳之前会稍微消失。
我知道这与位图的大小有关,并且它位于下面的 Sprite 类中,但我不知道需要修改什么。
这是 Sprite 类:
public class Sprite extends AppCompatActivity {
private static final int BMP_ROWS = 4;
private static final int BMP_COLUMNS = 3;
//x,y position of sprite - initial position (0,50)
private int x = 0;
private int y = 0;
private int xSpeed = 5;//Horizontal increment of position (speed)
private int ySpeed = 5;// Vertical increment of position (speed)
private GameView gameView;
private Bitmap spritebmp;
private int currentFrame = 0;
//Width and Height of the Sprite image
private int bmp_width;
private int bmp_height;
// Needed for new random coordinates.
private Random random = new Random();
private SoundPool mySound;
int zapSoundId;
public Sprite(GameView gameView) {
this.gameView = gameView;
spritebmp = BitmapFactory.decodeResource(gameView.getResources(),
R.drawable.bad4);
this.bmp_width = spritebmp.getWidth() / BMP_COLUMNS;
this.bmp_height = spritebmp.getHeight() / BMP_ROWS;
xSpeed = random.nextInt(15) + 1;
ySpeed = random.nextInt(15) + 1;
x = random.nextInt(gameView.getWidth() - bmp_width);
y = random.nextInt(gameView.getHeight() - bmp_height);
}
public Sprite(GameView gameView, Bitmap bmp) {
spritebmp.recycle();
}
//update the position of the sprite
public void update() {
x = x + xSpeed;
y = y + ySpeed;
bounce();
//y = random.nextInt(gameView.getWidth());
//wrapAround(); //Adjust motion of sprite.
}
private void bounce() {
if (x <= 0 || x >= gameView.getWidth() ) {
xSpeed = xSpeed * -1;
}
if (y <= 0 || y >= gameView.getHeight() ) {
ySpeed = ySpeed * -1;
}
currentFrame = ++currentFrame % BMP_COLUMNS;
}
public void draw(Canvas canvas) {
update();
int srcX = currentFrame * bmp_width;
int srcY;
if (xSpeed > 0) {
srcY = 0 * bmp_height;
}
else {
srcY = 1 * bmp_height;
}
// Create Rect around the source image to be drawn
Rect src = new Rect(srcX, srcY, srcX + bmp_width, srcY + bmp_height);
// Rect for destination image
Rect dst = new Rect(x, y, x + bmp_width, y + bmp_height);
//
// Draw the image frame
canvas.drawBitmap(spritebmp, src, dst, null);
}
// Checks if the sprite was touched
public boolean wasItTouched(float ex, float ey) {
boolean touched = false;
if ((x <= ex) && (ex < x + bmp_width) &&
(y <= ey) && (ey < y + bmp_height)) {
touched = true;
}
return touched;
}
}
非常感谢任何帮助。
谢谢
最佳答案
我已经修复了它。
我需要将'this.bmp_width'和'this.bmp_height'添加到我的bounce()方法中。
private void bounce() {
if (x <= 0 || x + this.bmp_width >= gameView.getWidth() ) {
xSpeed = xSpeed * -1;
}
if (y <= 0 || y + this.bmp_height >= gameView.getHeight() ) {
ySpeed = ySpeed * -1;
}
currentFrame = ++currentFrame % BMP_COLUMNS;
}
关于java - 在Android应用程序中定义位图的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762819/