Skip to content

Instantly share code, notes, and snippets.

@Janooba
Created April 8, 2016 21:17
Show Gist options
  • Save Janooba/e281c8e3d06125ee1f9a9a3d3397de01 to your computer and use it in GitHub Desktop.
Save Janooba/e281c8e3d06125ee1f9a9a3d3397de01 to your computer and use it in GitHub Desktop.
The basics needed to use Sprite.java or ScrollingImage.java
public class SpriteSheetActivity extends Activity
{
// Our object that will hold the view and
// the sprite sheet animation logic
GameView gameView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Initialize gameView and set it as the view
gameView = new GameView(this);
setContentView(gameView);
}
class GameView extends SurfaceView implements Runnable
{
// This is our thread
Thread gameThread = null;
// We need a SurfaceHolder when we use Paint and Canvas in a thread
SurfaceHolder ourHolder;
// A boolean which we will set and unset when the game is running- or not.
volatile boolean playing;
// A Canvas and a Paint object
Canvas canvas;
Paint paint;
private Sprite fireSprite;
float fireXPosition = 220;
float fireYPosition = 295;
private Sprite groundBackgroundSprite;
public GameView(Context context)
{
super(context);
ourHolder = getHolder();
paint = new Paint();
fireSprite = new Sprite(context, R.drawable.campfire, 5, 14, true);
groundBackgroundSprite = new Sprite(context, R.drawable.ground);
}
@Override
public void run()
{
while (playing)
{
// Update the frame
update();
// Draw the frame
draw();
}
}
public void update()
{
// Anything that needs to be updated
}
public void draw()
{
// Make sure our drawing surface is valid or we crash
if (ourHolder.getSurface().isValid())
{
// Lock the canvas ready to draw
canvas = ourHolder.lockCanvas();
// Draw the background color
groundBackgroundSprite.draw(canvas, paint, 0, 0, 0);
fireSprite.draw(canvas, paint, fireXPosition, fireYPosition, 0, false, false);
// Draw everything to the screen
ourHolder.unlockCanvasAndPost(canvas);
}
}
// If SimpleGameEngine Activity is paused/stopped
// shutdown our thread.
public void pause()
{
playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
Log.e("Error:", "joining thread");
}
}
// If SimpleGameEngine Activity is started then start our thread.
public void resume()
{
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
}
// This method executes when the player starts the game
@Override
protected void onResume()
{
super.onResume();
// Tell the gameView resume method to execute
gameView.resume();
}
// This method executes when the player quits the game
@Override
protected void onPause()
{
super.onPause();
// Tell the gameView pause method to execute
gameView.pause();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment