如何在接触边框时循环sprite(android游戏开发)

时间:2012-12-14 09:12:47

标签: java android eclipse

请帮忙。我是Android游戏开发和java的新手。我希望我的鹿在接触屏幕边框时再次循环或从0开始,但我不知道如何编码它。

包com.cmanres.bunnyjourney;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;



public class Spriteleft {
       private static final int BMP_COLUMNS = 3;
   private static final int BMP_ROWS = 2;
   private int x = 0; 
   private int y=0;
       private int xSpeed = 3;
       private Levelunogame gameView;
       private Bitmap deer1;
   private int width;
   private int height;
   private int currentFrame=0;

 public Spriteleft(Levelunogame gameView, Bitmap deer1) {
         this.gameView=gameView;
         this.deer1=deer1;
         this.width = deer1.getWidth() / BMP_COLUMNS;
         this.height = deer1.getHeight() / BMP_ROWS;
   }

   private void update() {
         if (x > gameView.getWidth() - width - xSpeed) {
                xSpeed = -3;
         }
         if (x + xSpeed< 0) {
                xSpeed = 3;
         }
         x = x + xSpeed;
         currentFrame = ++currentFrame % BMP_COLUMNS;
   }


   public void onDraw(Canvas canvas) {
         update();
         int srcX = currentFrame * width;
         int srcY = 1 * height;
         Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
         Rect dst = new Rect(x, y, x + width, y + height);
         canvas.drawBitmap(deer1, src , dst, null);
       }
 }  

这是我在Android手机游戏教程中遵循的代码。任何人都可以告诉我该怎么做?或者为教程提供任何链接?我会非常感激。

1 个答案:

答案 0 :(得分:0)

假设你的精灵位于x,y,sprite_width,sprite_height

//检查您的精灵位置是否在屏幕边界之外

if( x < 0 || x > gameView.getWidth() - sprite_width 
 || y < 0 || y > gameView.getHeight() - sprite_height ) {
    // Set x, y to 0,0
    x = 0;
    y = 0;
}