Skip to content

Instantly share code, notes, and snippets.

@ianbarber
Created September 6, 2013 13:47
Show Gist options
  • Save ianbarber/6464032 to your computer and use it in GitHub Desktop.
Save ianbarber/6464032 to your computer and use it in GitHub Desktop.
An Android view that responds to gamepad events
package com.riskcompletefailure.happydot;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
public class DotView extends View {
private final Rect mRect = new Rect();
private static final double DOT_SIZE = 0.025;
private static final double BUTTON_SIZE = 0.05;
private static final double BASE_DOT_Y = 0.5;
private static final double BASE_DOT_X = 0.5;
private double mDoty = 0;
private double mDotx = 0;
private int mHeightInPixels;
private int mWidthInPixels;
private boolean mDrawA = false;
private boolean mDrawB = false;
private Paint mPaint = new Paint();
public Context mActivity;
public DotView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
mActivity = context;
}
// Convert back from screenspace
public int spy(double screenSpaceCoordinate) {
return (int) Math.round(screenSpaceCoordinate * mHeightInPixels);
}
// Convert back from screenspace
public int spx(double screenSpaceCoordinate) {
return (int) Math.round(screenSpaceCoordinate * mWidthInPixels);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mHeightInPixels = this.getHeight();
mWidthInPixels = this.getWidth();
// Draw Background.
mRect.top = 0;
mRect.bottom = mHeightInPixels;
mRect.left = 0;
mRect.right = mWidthInPixels;
mPaint.setColor(0xFF000000);
canvas.drawRect(mRect, mPaint);
// Draw Dot
mPaint.setColor(0xFFFFFFFF);
canvas.drawCircle(
spx(BASE_DOT_X + mDotx),
spy(BASE_DOT_Y + mDoty),
spx(DOT_SIZE),
mPaint);
// Draw Buttons
if (mDrawA) {
mPaint.setColor(0xFFFF00FF);
canvas.drawCircle(spx(0.8), spy(0.9), spx(BUTTON_SIZE), mPaint);
}
if (mDrawB) {
mPaint.setColor(0xFFFFFF00);
canvas.drawCircle(spx(0.9), spy(0.8), spx(BUTTON_SIZE), mPaint);
}
}
public boolean onGenericMotionEvent(MotionEvent e) {
if ((e.getDevice().getSources() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
mDotx = e.getX() / 4.0;
mDoty = e.getY() / 4.0;
// Debug: Log.d("JOY", e.toString());
// Trigger a redraw.
invalidate();
return true;
}
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Debug: Log.d("JOY", event.toString());
if(event.getAction() == KeyEvent.ACTION_DOWN) {
if(keyCode == KeyEvent.KEYCODE_BUTTON_A) {
mDrawA = !mDrawA;
} else if(keyCode == KeyEvent.KEYCODE_BUTTON_B) {
mDrawB = !mDrawB;
}
// Trigger a redraw.
invalidate();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment