How can the motion of the rocket be optimized? - android

I am making a missile interception strategy game, why does it give an error message when trying to removing enemy birds?
How can the motion of the rocket be optimized ?
Why aren't the enemies eliminated?
Here is my Build Rocket code...
stage.addEventListener(MouseEvent.CLICK, letsgoeasy)
function letsgoeasy(e: MouseEvent): void {
var Rocket: Hawk = new Hawk();
Rocket.x = p.x;
Rocket.y = p.y;
Rocket.scaleX = 0.2;
Rocket.scaleY = 0.2;
addChild(Rocket);
Rocket.addEventListener(Event.ENTER_FRAME, moveBullet);
function moveBullet(e: Event) {
}
var myTimer: Timer = new Timer(2000);
var speedF: Number = 5;
var RocketBox: Array = new Array;
Rocket.addEventListener(Event.ENTER_FRAME, follow);
function follow(e: Event): void {
myTimer.start();
if (enemyFleet[h].y > 100) {
for (var h: int = 0; h < enemyFleet.length; h++) {
Rocket.x -= (Rocket.x - enemyFleet[h].x) / speedF;
Rocket.x = Rocket.x + 2;
Rocket.y -= (Rocket.y - enemyFleet[h].y) / speedF;
Rocket.y = Rocket.y + 3;
RocketBox.push(Rocket)
}
}
//Fire Rocket part
var smoke: smoke_shell = new smoke_shell();
addChild(smoke);
smoke.scaleX = 0.1;
smoke.scaleY = 0.1;
smoke.x = Rocket.x
smoke.y = Rocket.y + 10
smoke.rotation = 0
smoke.color = 0xE77471;
smoke.blurX = 3;
smoke.blurY = 3;
smoke.strength = 100;
smoke.quality = 3;
removeChild(null);
}
// collision part
addEventListener(Event.ENTER_FRAME, collCkeck);
function collCkeck(e: Event): void {
for (var s: int = Rocket.length - 1; s >= 0; s--) {
if (Rocket.hitTestObject(enemyFleet[s])) {
enemyDeaths();
}
function enemyDeaths() {
removeChild(Rocket);
trace("Rocket");
removeChild(enemyFleet[s]);
enemyFleet.splice(s, 1);
}
}
}
}
My error:
TypeError: Error #2007: Parameter child must be non-null. at
flash.display::DisplayObjectContainer/removeChild() at
Function/TrackermissileRocket190714002_fla:MainTimeline/letsgoeasy/TrackermissileRocket190714002_fla:follow()[TrackermissileRocket190714002_fla.MainTimeline::frame1:101]
My game image:

(1) You should make your vars as global (outside of and best before the functions part).
(2) Don't trap vars and functions inside other functions...
Try a setup similar to something like this:
//# globally declare the VARS (now available to all functions)...
var Rocket: Hawk;
var myTimer: Timer;
var RocketBox : Array = new Array;
var speedF: Number = 0;
stage.addEventListener(MouseEvent.CLICK, letsgoeasy);
function letsgoeasy(e: MouseEvent): void
{
speedF = 5;
Rocket = new Hawk();
Rocket.x = p.x;
Rocket.y = p.y;
Rocket.scaleX = Rocket.scaleY = 0.2;
Rocket.addEventListener(Event.ENTER_FRAME, moveBullet);
Rocket.addEventListener(Event.ENTER_FRAME, follow);
Rocket.addEventListener(Event.ENTER_FRAME, collCkeck);
addChild(Rocket);
RocketBox.push( Rocket );
myTimer = new Timer(2000); //# what for...?
myTimer.start(); //# maybe start Timer here at creation...?
}
function moveBullet(e: Event) : void
{
}
function follow( currRocket : Event) : void
{
//myTimer.start();
for (var h: int = 0; h < (enemyFleet.length-1); h++)
{
if (enemyFleet[h].y > 100)
{
currRocket.x -= (currRocket.x - enemyFleet[h].x) / speedF;
currRocket.x = currRocket.x + 2;
currRocket.y -= (currRocket.y - enemyFleet[h].y) / speedF;
currRocket.y = currRocket.y + 3;
//RocketBox.push( currRocket );
}
}
}
/////////
function collCkeck( currRocket : Event ) : void
{
for (var s: int = (RocketBox.length-1); s >= 0; s--)
{
if ( (s >= 0 ) && ( ( currRocket.hitTestObject(enemyFleet[s])) == true ) )
{
enemyDeaths( s );
}
}
}
function enemyDeaths( input_S ) : void
{
removeChild(Rocket);
trace("Removed... Rocket");
removeChild(enemyFleet[input_S]);
enemyFleet.splice(input_S, 1);
}

Related

Flutter tflite MoveNet model java.lang.RuntimeException: doInBackground()

I was trying to implement MoveNet tflite pose estimation model on Flutter via https://pub.dev/packages/tflite package. MoveNet lightning model accepts 192x192 image size and uses float32 tensor of shape. I loaded the lightning model and camera streaming like this :
class _AppCameraState extends State<AppCamera> {
late CameraController controller;
bool isDetecting = false;
#override
void initState() {
super.initState();
if (widget.cameras!.length < 1) {
print('No camera is found');
} else {
controller = new CameraController(
widget.cameras![0],
ResolutionPreset.high,
);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
detectPose();
});
}
}
detectPose() {
controller.startImageStream((CameraImage img) {
if (!isDetecting) {
isDetecting = true;
Tflite.runModelOnBinary(binary: imageToByteListFloat32(convertCameraImage(img)!, 192, 127.5, 127.5)).then((recognition) {
widget.setRecognitions!(recognition, 192, 192);
isDetecting = false;
});
}
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
Helper functions :
Uint8List imageToByteListFloat32(imgLib.Image image, int inputSize, double mean, double std) {
var convertedBytes = Float32List(1 * inputSize * inputSize * 3);
var buffer = Float32List.view(convertedBytes.buffer);
int pixelIndex = 0;
for (var i = 0; i < inputSize; i++) {
for (var j = 0; j < inputSize; j++) {
var pixel = image.getPixel(j, i);
buffer[pixelIndex++] = (imgLib.getRed(pixel) - mean) / std;
buffer[pixelIndex++] = (imgLib.getGreen(pixel) - mean) / std;
buffer[pixelIndex++] = (imgLib.getBlue(pixel) - mean) / std;
}
}
return convertedBytes.buffer.asUint8List();
}
imageLib.Image? convertCameraImage(CameraImage cameraImage) {
if (cameraImage.format.group == ImageFormatGroup.yuv420) {
return _convertYUV420ToImage(cameraImage);
} else if (cameraImage.format.group == ImageFormatGroup.bgra8888) {
return _convertBGRA8888ToImage(cameraImage);
}
}
imageLib.Image _convertBGRA8888ToImage(CameraImage cameraImage) {
imageLib.Image img = imageLib.Image.fromBytes(cameraImage.planes[0].width!, cameraImage.planes[0].height!, cameraImage.planes[0].bytes,
format: imageLib.Format.bgra);
return img;
}
imageLib.Image _convertYUV420ToImage(CameraImage cameraImage) {
final int width = cameraImage.width;
final int height = cameraImage.height;
final int uvRowStride = cameraImage.planes[1].bytesPerRow;
final int uvPixelStride = cameraImage.planes[1].bytesPerPixel!;
final image = imageLib.Image(width, height);
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
final int uvIndex = uvPixelStride * (w / 2).floor() + uvRowStride * (h / 2).floor();
final int index = h * width + w;
final y = cameraImage.planes[0].bytes[index];
final u = cameraImage.planes[1].bytes[uvIndex];
final v = cameraImage.planes[2].bytes[uvIndex];
image.data[index] = _yuv2rgb(y, u, v);
}
}
return image;
}
int _yuv2rgb(int y, int u, int v) {
// Convert yuv pixel to rgb
int r = (y + v * 1436 / 1024 - 179).round();
int g = (y - u * 46549 / 131072 + 44 - v * 93604 / 131072 + 91).round();
int b = (y + u * 1814 / 1024 - 227).round();
// Clipping RGB values to be inside boundaries [ 0 , 255 ]
r = r.clamp(0, 255);
g = g.clamp(0, 255);
b = b.clamp(0, 255);
return 0xff000000 | ((b << 16) & 0xff0000) | ((g << 8) & 0xff00) | (r & 0xff);
}
And output like this below :
Which part should be edit? , thank you.

How to fill the color gradually on drawn view canvas Android

I am having a WaveFormView on which I want to change the color of it while playing Audio file and as the Audio is paused it should be stopped coloring at that certain point and when resumed it should continue forward with coloring. I am not getting how to do it in my code..
This is the screen shot of my generated waveform. Now when I will click on Play button it should change the color of waveform gradually with red color (from start to end slowly).
Here is my code to draw waveform view.
WaveFormView.class
public class WaveformView extends View {
public interface WaveformListener {
public void waveformFling(float x);
public void waveformDraw();
}
;
// Colors
private Paint mGridPaint;
private Paint mSelectedLinePaint;
private Paint mUnselectedLinePaint;
private Paint mUnselectedBkgndLinePaint;
private Paint mBorderLinePaint;
private Paint mPlaybackLinePaint;
private Paint mTimecodePaint;
private SoundFile mSoundFile;
private int[] mLenByZoomLevel;
private double[][] mValuesByZoomLevel;
private double[] mZoomFactorByZoomLevel;
private int[] mHeightsAtThisZoomLevel;
private int mZoomLevel;
private int mNumZoomLevels;
private int mSampleRate;
private int mSamplesPerFrame;
private int mOffset;
private int mSelectionStart;
private int mSelectionEnd;
private int mPlaybackPos;
private float mDensity;
private float mInitialScaleSpan;
private WaveformListener mListener;
private GestureDetector mGestureDetector;
private ScaleGestureDetector mScaleGestureDetector;
private boolean mInitialized;
Color color;
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
// We don't want keys, the markers get these
setFocusable(false);
mGridPaint = new Paint();
mGridPaint.setAntiAlias(false);
mGridPaint.setColor(
getResources().getColor(R.color.grid_line));
mSelectedLinePaint = new Paint();
mSelectedLinePaint.setAntiAlias(false);
mSelectedLinePaint.setColor(
getResources().getColor(R.color.waveform_selected));
mUnselectedLinePaint = new Paint();
mUnselectedLinePaint.setAntiAlias(false);
mUnselectedLinePaint.setColor(
getResources().getColor(R.color.waveform_unselected));
mUnselectedBkgndLinePaint = new Paint();
mUnselectedBkgndLinePaint.setAntiAlias(false);
mUnselectedBkgndLinePaint.setColor(
getResources().getColor(
R.color.selection_border));
mBorderLinePaint = new Paint();
mBorderLinePaint.setAntiAlias(true);
mBorderLinePaint.setStrokeWidth(1.5f);
mBorderLinePaint.setPathEffect(
new DashPathEffect(new float[]{3.0f, 2.0f}, 0.0f));
mBorderLinePaint.setColor(
getResources().getColor(R.color.selection_border));
mPlaybackLinePaint = new Paint();
mPlaybackLinePaint.setAntiAlias(false);
mPlaybackLinePaint.setColor(
getResources().getColor(R.color.playback_indicator));
mTimecodePaint = new Paint();
mTimecodePaint.setTextSize(12);
mTimecodePaint.setAntiAlias(true);
mTimecodePaint.setColor(
getResources().getColor(R.color.timecode));
mTimecodePaint.setShadowLayer(
2, 1, 1,
getResources().getColor(R.color.timecode_shadow));
mGestureDetector = new GestureDetector(
context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(
MotionEvent e1, MotionEvent e2, float vx, float vy) {
mListener.waveformFling(vx);
return true;
}
});
mSoundFile = null;
mLenByZoomLevel = null;
mValuesByZoomLevel = null;
mHeightsAtThisZoomLevel = null;
mOffset = 0;
mPlaybackPos = -1;
mSelectionStart = 0;
mSelectionEnd = 0;
mDensity = 1.0f;
mInitialized = false;
}
public boolean hasSoundFile() {
return mSoundFile != null;
}
public void setSoundFile(SoundFile soundFile) {
mSoundFile = soundFile;
mSampleRate = mSoundFile.getSampleRate();
mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
computeDoublesForAllZoomLevels();
mHeightsAtThisZoomLevel = null;
}
/**
* Called once when a new sound file is added
*/
private void computeDoublesForAllZoomLevels() {
int numFrames = mSoundFile.getNumFrames();
int[] frameGains = mSoundFile.getFrameGains();
double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (double)(
(frameGains[0] / 2.0) +
(frameGains[1] / 2.0));
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] = (double)(
(frameGains[i - 1] / 3.0) +
(frameGains[i ] / 3.0) +
(frameGains[i + 1] / 3.0));
}
smoothedGains[numFrames - 1] = (double)(
(frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0));
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0)
smoothedGain = 0;
if (smoothedGain > 255)
smoothedGain = 255;
if (smoothedGain > maxGain)
maxGain = smoothedGain;
gainHist[smoothedGain]++;
}
// Re-calibrate the min to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the heights
double[] heights = new double[numFrames];
double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0)
value = 0.0;
if (value > 1.0)
value = 1.0;
heights[i] = value * value;
}
mNumZoomLevels = 5;
mLenByZoomLevel = new int[5];
mZoomFactorByZoomLevel = new double[5];
mValuesByZoomLevel = new double[5][];
// Level 0 is doubled, with interpolated values
mLenByZoomLevel[0] = numFrames * 2;
mZoomFactorByZoomLevel[0] = 2.0;
mValuesByZoomLevel[0] = new double[mLenByZoomLevel[0]];
if (numFrames > 0) {
mValuesByZoomLevel[0][0] = 0.5 * heights[0];
mValuesByZoomLevel[0][1] = heights[0];
}
for (int i = 1; i < numFrames; i++) {
mValuesByZoomLevel[0][2 * i] = 0.5 * (heights[i - 1] + heights[i]);
mValuesByZoomLevel[0][2 * i + 1] = heights[i];
}
// Level 1 is normal
mLenByZoomLevel[1] = numFrames;
mValuesByZoomLevel[1] = new double[mLenByZoomLevel[1]];
mZoomFactorByZoomLevel[1] = 1.0;
for (int i = 0; i < mLenByZoomLevel[1]; i++) {
mValuesByZoomLevel[1][i] = heights[i];
}
// 3 more levels are each halved
for (int j = 2; j < 5; j++) {
mLenByZoomLevel[j] = mLenByZoomLevel[j - 1] / 2;
mValuesByZoomLevel[j] = new double[mLenByZoomLevel[j]];
mZoomFactorByZoomLevel[j] = mZoomFactorByZoomLevel[j - 1] / 2.0;
for (int i = 0; i < mLenByZoomLevel[j]; i++) {
mValuesByZoomLevel[j][i] =
0.5 * (mValuesByZoomLevel[j - 1][2 * i] +
mValuesByZoomLevel[j - 1][2 * i + 1]);
}
}
if (numFrames > 5000) {
mZoomLevel = 3;
} else if (numFrames > 1000) {
mZoomLevel = 2;
} else if (numFrames > 300) {
mZoomLevel = 1;
} else {
mZoomLevel = 0;
}
mInitialized = true;
}
public boolean canZoomIn() {
return (mZoomLevel > 0);
}
public void zoomIn() {
if (canZoomIn()) {
mZoomLevel--;
mSelectionStart *= 2;
mSelectionEnd *= 2;
mHeightsAtThisZoomLevel = null;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter *= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
invalidate();
}
}
public boolean canZoomOut() {
return (mZoomLevel < mNumZoomLevels - 1);
}
public void zoomOut() {
if (canZoomOut()) {
mZoomLevel++;
mSelectionStart /= 2;
mSelectionEnd /= 2;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter /= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
mHeightsAtThisZoomLevel = null;
invalidate();
}
}
public double pixelsToSeconds(int pixels) {
double z = mZoomFactorByZoomLevel[mZoomLevel];
return (pixels * (double)mSamplesPerFrame / (mSampleRate * z));
}
public void setListener(WaveformListener listener) {
mListener = listener;
}
public void recomputeHeights(float density) {
mHeightsAtThisZoomLevel = null;
mDensity = density;
mTimecodePaint.setTextSize((int)(12 * density));
invalidate();
}
protected void drawWaveformLine(Canvas canvas,
int x, int y0, int y1,
Paint paint) {
canvas.drawLine(x, y0, x, y1, paint);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSoundFile == null)
return;
if (mHeightsAtThisZoomLevel == null)
computeIntsForThisZoomLevel();
DisplayMetrics displaymetrics = getContext().getResources().getDisplayMetrics();
int height = displaymetrics.heightPixels;
int widths = displaymetrics.widthPixels;
// Draw waveform
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int start = mOffset;
int width = mHeightsAtThisZoomLevel.length - start;
int ctr = measuredHeight / 2;
Log.e("wid",String.valueOf(width));
Log.e("widCal",String.valueOf(mHeightsAtThisZoomLevel.length));
Log.e("widstart",String.valueOf(start));
if (width > measuredWidth)
width = measuredWidth;
Log.e("measured",String.valueOf(measuredWidth));
// Draw grid
double onePixelInSecs = pixelsToSeconds(1);
boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
double fractionalSecs = mOffset * onePixelInSecs;
int integerSecs = (int) fractionalSecs;
int i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
int integerSecsNew = (int) fractionalSecs;
if (integerSecsNew != integerSecs) {
integerSecs = integerSecsNew;
if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
}
}
}
// Draw waveform
for ( i = 0; i < width; i++) {
Paint paint;
if (i + start >= mSelectionStart &&
i + start < mSelectionEnd) {
paint = mSelectedLinePaint;
// paint.setColor(color);
} else {
drawWaveformLine(canvas, ((widths/width)*i), 0, measuredHeight,
mUnselectedBkgndLinePaint);
paint = mUnselectedLinePaint;
}
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
paint);
if (i + start == mPlaybackPos) {
canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
}
}
if (mListener != null) {
mListener.waveformDraw();
}
}
private void computeIntsForThisZoomLevel() {
int halfHeight = (getMeasuredHeight() / 2) - 1;
mHeightsAtThisZoomLevel = new int[mLenByZoomLevel[mZoomLevel]];
for (int i = 0; i < mLenByZoomLevel[mZoomLevel]; i++) {
mHeightsAtThisZoomLevel[i] =
(int)(mValuesByZoomLevel[mZoomLevel][i] * halfHeight);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity implements WaveformView.WaveformListener {
WaveformView mWaveformView;
SoundFile mSoundFile;
private float mDensity;
private File mFile;
private String mFilename;
private long mLoadingLastUpdateTime;
boolean mLoadingKeepGoing;
boolean mFinishActivity;
private ProgressDialog mProgressDialog;
String mTitle,mArtist;
private Thread mLoadSoundFileThread;
private Thread mRecordAudioThread;
private Thread mSaveSoundFileThread;
private boolean mIsPlaying;
private SamplePlayer mPlayer;
private String mInfoContent;
private int mWidth;
private int mMaxPos;
private int mStartPos;
private int mEndPos;
private boolean mStartVisible;
private boolean mEndVisible;
private int mLastDisplayedStartPos;
private int mLastDisplayedEndPos;
private int mOffset;
private int mOffsetGoal;
private int mFlingVelocity;
private int mPlayStartMsec;
private int mPlayEndMsec;
private Handler mHandler;
Button pla;
MediaPlayer mediaPlayer;
boolean ismIsPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pla = (Button)findViewById(R.id.play);
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
mHandler = new Handler();
Uri uri = Uri.parse("/sdcard/audio_file.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
loadGui();
loadFromFile();
}
/**
* Called from both onCreate and onConfigurationChanged
* (if the user switched layouts)
*/
private void loadGui() {
// Inflate our UI from its XML layout description.
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.density;
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
if (mSoundFile != null && !mWaveformView.hasSoundFile()) {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
}
}
private void loadFromFile() {
mFilename = "/sdcard/audio_file.mp3";
mFile = new File(mFilename);
SongMetadataReader metadataReader = new SongMetadataReader(
this, mFilename);
mTitle = metadataReader.mTitle;
mArtist = metadataReader.mArtist;
String titleLabel = mTitle;
if (mArtist != null && mArtist.length() > 0) {
titleLabel += " - " + mArtist;
}
setTitle(titleLabel);
mLoadingLastUpdateTime = getCurrentTime();
mLoadingKeepGoing = true;
mFinishActivity = false;
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setTitle("Loading...");
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mLoadingKeepGoing = false;
mFinishActivity = true;
}
});
mProgressDialog.show();
final SoundFile.ProgressListener listener =
new SoundFile.ProgressListener() {
public boolean reportProgress(double fractionComplete) {
long now = getCurrentTime();
if (now - mLoadingLastUpdateTime > 100) {
mProgressDialog.setProgress(
(int) (mProgressDialog.getMax() * fractionComplete));
mLoadingLastUpdateTime = now;
}
return mLoadingKeepGoing;
}
};
// Load the sound file in a background thread
mLoadSoundFileThread = new Thread() {
public void run() {
try {
mSoundFile = SoundFile.create(mFile.getAbsolutePath(), listener);
if (mSoundFile == null) {
mProgressDialog.dismiss();
String name = mFile.getName().toLowerCase();
String[] components = name.split("\\.");
String err;
if (components.length < 2) {
err = getResources().getString(
R.string.no_extension_error);
} else {
err = getResources().getString(
R.string.bad_extension_error) + " " +
components[components.length - 1];
}
final String finalErr = err;
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(new Exception(), finalErr);
}
};
mHandler.post(runnable);
return;
}
mPlayer = new SamplePlayer(mSoundFile);
} catch (final Exception e) {
mProgressDialog.dismiss();
e.printStackTrace();
mInfoContent = e.toString();
runOnUiThread(new Runnable() {
public void run() {
}
});
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(e, getResources().getText(R.string.read_error));
}
};
mHandler.post(runnable);
return;
}
mProgressDialog.dismiss();
if (mLoadingKeepGoing) {
Runnable runnable = new Runnable() {
public void run() {
finishOpeningSoundFile();
}
};
mHandler.post(runnable);
} else if (mFinishActivity){
MainActivity.this.finish();
}
}
};
mLoadSoundFileThread.start();
}
private void finishOpeningSoundFile() {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
Log.e("sound file",mFilename);
Log.e("sound", String.valueOf(mSoundFile));
}
/**
* Show a "final" alert dialog that will exit the activity
* after the user clicks on the OK button. If an exception
* is passed, it's assumed to be an error condition, and the
* dialog is presented as an error, and the stack trace is
* logged. If there's no exception, it's a success message.
*/
private void showFinalAlert(Exception e, CharSequence message) {
CharSequence title;
if (e != null) {
Log.e("Ringdroid", "Error: " + message);
Log.e("Ringdroid", getStackTrace(e));
title = getResources().getText(R.string.alert_title_failure);
setResult(RESULT_CANCELED, new Intent());
} else {
Log.v("Ringdroid", "Success: " + message);
title = getResources().getText(R.string.alert_title_success);
}
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void showFinalAlert(Exception e, int messageResourceId) {
showFinalAlert(e, getResources().getText(messageResourceId));
}
#Override
public void waveformTouchStart(float x) {
}
#Override
public void waveformTouchMove(float x) {
}
#Override
public void waveformTouchEnd() {
}
#Override
public void waveformFling(float x) {
}
#Override
public void waveformDraw() {
mWidth = mWaveformView.getMeasuredWidth();
if (mOffsetGoal != mOffset) {
// updateDisplay();
}
else if (mIsPlaying) {
// updateDisplay();
} else if (mFlingVelocity != 0) {
// updateDisplay();
}
}
private long getCurrentTime() {
return System.nanoTime() / 1000000;
}
private String getStackTrace(Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
public void buttonClick(View view) {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
ismIsPlaying = true;
}
}
In your onDraw(Canvas canvas) add the following lines
if (i + start <= mPlaybackPos) {
Paint mPaint = new Paint(paint);
mPaint.setColor(Color.RED);
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
mPaint);
}
add them above the line:
if (i + start == mPlaybackPos) {
And if this works, consider to allocate the Paint-object outside the onDraw() method.

I am using unity3D engine to create a game involving cars

while doing the controls I have encountered the following errors.
Assets/Car/Scripts/NewBehaviourScript.js(78,22): UCE0001: ';' expected. Insert a semicolon at the end.
Assets/Car/Scripts/NewBehaviourScript.js(78,10): BCE0044: expecting (, found 'ShiftGears'.
Assets/Car/Scripts/NewBehaviourScript.js(79,9): BCE0043: Unexpected token: if.
Assets/Car/Scripts/NewBehaviourScript.js(79,41): UCE0001: ';' expected. Insert a semicolon at the end.
these errors does'nt usually appear in sxripting in unity and this is the first time that I have encountered it.
here is my code
#pragma strict
var FrontLeftWheel : WheelCollider;
var FrontRightWheel : WheelCollider;
var BackLeftWheel : WheelCollider;
var BackRightWheel : WheelCollider;
var gasButton : GUITexture;
var breakButton : GUITexture;
var leftTurnButton : GUITexture;
var rightTurnButton : GUITexture;
var motorInputTouch : int = 0;
var breakPower : float = 200;
var GearRatio : float[];
var CurrentGear : int = 0;
var EngineTorque : float = 230.0;
var MaxEngineRPM : float = 3000.0;
var MinEngineRPM : float = 1000.0;
private var EngineRPM : float = 0.0;
function Awake() {
gasButton = GameObject.Find("Gas_Pedal").guiTexture;
breakButton = GameObject.Find("brake_Pedal").guiTexture;
leftTurnButton = GameObject.Find("Left_Turn_Button").guiTexture;
rightTurnButton = GameObject.Find("Right_Turn_Button").guiTexture;
}
function start() {
rigidbody.centerOfMass += Vector3(0, -1, .25);
}
function update() {
for (var touch : Touch in Input.touches)
{
if (touch.phase == TouchPhase.Stationary && gasButton.HitTest (touch.position)){
motorInputTouch = 1;
}
else if (touch.phase == TouchPhase.Ended && gasButton.HitTest){
motorInputTouch = 0;
}
if (touch.phase == TouchPhase.Stationary && breakButton.HitTest (touch.position)){
breakPower = 200;
}
else if (touch.phase == TouchPhase.Ended && breakButton.HitTest){
breakPower = 0;
}
if (touch.phase == TouchPhase.Stationary && leftTurnButton.HitTest (touch.position)){
FrontLeftWheel.steerAngle = -15;
FrontRightWheel.steerAngle = -15;
}
else if (touch.phase == TouchPhase.Ended && leftTurnButton.HitTest){
FrontLeftWheel.steerAngle = 0;
FrontRightWheel.steerAngle = 0;
}
if (touch.phase == TouchPhase.Stationary && rightTurnButton.HitTest (touch.position)){
FrontLeftWheel.steerAngle = 15;
FrontRightWheel.steerAngle = 15;
}
else if (touch.phase == TouchPhase.Ended && rightTurnButton.HitTest){
FrontLeftWheel.steerAngle = 0;
FrontRightWheel.steerAngle = 0;
}
EngineRPM = (FrontLeftWheel.rpm + FrontRightWheel.rpm)/2 * GearRatio[CurrentGear];
ShiftGears();
audio.pitch = Mathf.Aba(EngineRPM / MaxEngine + 1.0);
if (audio.pitch > 2.0) {
audio.pitch = 2.0;
}
FrontLeftWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * motorInputTouch;
FrontRightWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * motorInputTouch;
//FrontLeftWheel.steerAngle = 10 * Input.GetAxis("Horizontal");
//FrontRightWheel.steerAngle = 10 * Input.GetAxis("Horizontal");
}
function ShiftGears() {
if ( EngineRPM >= MaxEngineRPM ) {
var AppropriateGear : int = CurrentGear;
for ( var i = 0; i < GearRatio.length; i++) {
if (FrontLeftWheel.rpm * GearRatio[i] < MaxEngineRPM ) {
AppropriateGear = i;
break;
}
}
CurrentGear = AppropriateGear;
}
if (EngineRPM <= MinEngineRPM ) {
AppropriateGear = CurrentGear;
for (var j = GearRatio.Length-1; j >= 0; j--) {
if ( FrontLeftWheel.rpm * GearRatio[j] > MinEngineRPM ) {
AppropriateGear = j;
break;
}
}
CurrentGear = AppropriateGear;
}
}
any one here who can help me debug this? thanks a lot.
You are missing a closing bracket }. Either to end your for loop inside the Update(), or to signify the end of your Update() function. That causes the rest of the errors you're seeing.

How I can create a pattern login like Android in HTML5?

I created the HTML5 version for the Pattern login like Android, but unfortunately I know not much of HTML5 as to give the required functionality.
How I can do that with the mouse can given action?
My project is this:
http://jsfiddle.net/atiruz/mvkv9/3/
var size = 3; // Dimensions -> 3x3.
var ancho = size * 82 + 10;
var alto = ancho;
var drawingCanvas = createCanvas(document.getElementById('canvas'), 600, 600);
var context = drawingCanvas.context;
context.beginPath();
CrearContenedor(context,0,0,ancho,alto,15);
for (var i = 1; i <= size; i++) {
for (var j = 1; j <= size; j++) {
CrearBoton(context, i * 80 - 32, j * 80 - 32, ancho, alto);
}
}
And the result is:
Here's a very basic (webkit only) canvas implementation: http://jsfiddle.net/ChfGh/1/
I'm using jQuery for event handling, but that isn't strictly necessary.
var can = $("#canvas")[0],
ctx = can.getContext('2d'),
wid = can.width,
hei = can.height,
pad = 20,
circles = [],
selCircs = [],
correctPath = [0,3,7,5,2],
startPoint = {
x: 0,
y: 0
},
dragging = false;
(function init() {
var rad = (wid - pad * 4) / 3;
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
circles.push(new Circle({
x: j * (pad + rad) + pad + rad / 2,
y: i * (pad + rad) + pad + rad / 2
}, rad / 2));
}
}
})();
(function draw() {
ctx.clearRect(0, 0, wid, hei);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
if (dragging && selCircs.length > 1) {
var pos = selCircs[0].circ.position();
ctx.beginPath();
ctx.lineWidth = 10;
ctx.strokeStyle = "#000";
ctx.moveTo(pos.x, pos.y);
for (var j = 1; j < selCircs.length; j++){
pos = selCircs[j].circ.position();
ctx.lineTo(pos.x,pos.y);
}
ctx.stroke();
}
webkitRequestAnimationFrame(draw);
})();
function Circle(center, radius, fill, stroke, hover, active) {
var center = {
x: center.x,
y: center.y
},
radius = radius,
fill = fill || '#ccc',
hover = hover || '#ddd',
active = active || '#0f0',
stroke = stroke || '',
path;
this.position = function(){
return {x:center.x, y:center.y};
}
this.draw = function(ctx) {
ctx.fillStyle = this.selected ? active : this.hovering ? hover : fill;
if (stroke) ctx.strokeStyle = stroke;
ctx.beginPath();
ctx.arc(center.x, center.y, radius, 0, Math.PI * 2, false);
ctx.fill();
if (stroke) ctx.stroke();
};
this.isPointInPath = function(x, y) {
return Math.sqrt(Math.pow(center.x - x, 2) + Math.pow(center.y - y, 2)) <= radius;
};
this.hovering = false;
this.selected = false;
}
$("#canvas").mousemove(function(e) {
for (var i = 0; i < circles.length; i++) {
var cir = circles[i];
var pip = cir.isPointInPath(e.offsetX, e.offsetY);
cir.hovering = pip;
if (dragging && pip && !cir.selected) {
selCircs.push({circ:cir, index:i});
cir.selected = true;
}
}
});
$("#canvas").mousedown(function(e) {
dragging = true;
});
$("#canvas").mouseup(function(e) {
dragging = false;
// validate path
if (selCircs.length == correctPath.length){
var valid = true;
for (var i = 0; valid && i < correctPath.length; i++){
var index = correctPath[i];
if (selCircs[i].index !== index) valid = false;
}
if (valid) alert('correct!');
}
// reset selection
for (var i = 0; i < selCircs.length; i++)
selCircs[i].circ.selected = false;
selCircs = [];
});​
Here's the style I ended up implementing for fun: http://jsfiddle.net/ChfGh/6/
You can use map to extract the indexes from the selected circles:
var path = selCircs.map(function(ele){
return ele.index;
}).join(" "); // " " if you want a space between, otherwise ""
It will give you a string representation of the input.
Checkout "Pattern Lock" jquery plugin at http://pagoenka.github.io/

Monodroid ViewPager

Is ViewPager available for monodroid developers? I've seen a lot of tutorials like this one for Android: http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html
I can do this and declare a ViewPager as code, for example:
using Android.Support.V4.Widget;
namespace ViewPagerTest
{
[Activity(Label = "ViewPager", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity1 : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
ViewPager pager = new ViewPager( this );
SetContentView(Resource.Layout.Main);
}
}
}
But in the tutorial he uses xml code such as this:
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Which Monodroid doesnt seem to like..
Any input of what I'm missing?
Not a direct answer to your question...
But someone's ported a separate ViewPager to MonoDroid: https://github.com/Cheesebaron/MonoDroid.HorizontalPager
And I've then added a simple page indicator based on http://buildmobile.com/how-to-build-an-android-pager-component/#fbid=TnZmgHdBfhF
// original credit to:
// https://github.com/brucejcooper/Android-Examples/blob/master/PagingScrollerExample/src/com/eightbitcloud/pagingscroller/PageIndicator.java
public class HorizontalPagerIndicator : View
{
private HorizontalPager _pager;
private Paint _textPaint;
private Paint _inactiveDotPaint;
private Paint _dotPaint;
private Paint _dotBackgroundPaint;
private int _textHeight;
private int _ascent;
private int _cellSize;
private float _displayDensity;
public HorizontalPagerIndicator(Context context, IAttributeSet attrs)
: base(context, attrs)
{
InitPaints(context);
}
public HorizontalPagerIndicator(Context context)
: base(context)
{
InitPaints(context);
}
private void InitPaints(Context context)
{
_displayDensity = context.Resources.DisplayMetrics.Density;
_textPaint = new Paint {AntiAlias = true, TextSize = DeviceIndependentToPixels(14), Color = Color.Black};
_inactiveDotPaint = new Paint { AntiAlias = true, Color = Color.Gray };
_dotPaint = new Paint {AntiAlias = true, Color = Color.White};
_dotBackgroundPaint = new Paint { AntiAlias = true, Color = Color.Cyan };
_ascent = -(int)_textPaint.Ascent();
_textHeight = (int)(_ascent + _textPaint.Descent());
_cellSize = DeviceIndependentToPixels(_textHeight + 6);
}
public HorizontalPager Pager
{
get { return _pager; }
set {
if (_pager != null)
{
_pager.ScreenChanged -= PagerOnScreenChanged;
}
_pager = value;
if (_pager != null)
{
_pager.ScreenChanged += PagerOnScreenChanged;
}
UpdatePageCount();
}
}
private void PagerOnScreenChanged(object sender, EventArgs eventArgs)
{
Invalidate();
}
public void UpdatePageCount()
{
RequestLayout();
Invalidate();
}
private int NumPages
{
get
{
return _pager == null ? 1 : _pager.ChildCount;
}
}
private int ActivePage
{
get
{
return _pager == null ? 0 : _pager.CurrentScreen;
}
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
SetMeasuredDimension(MeasureWidth(widthMeasureSpec), MeasureHeight(heightMeasureSpec));
}
private int MeasureWidth(int measureSpec)
{
var result = 0;
var specMode = MeasureSpec.GetMode(measureSpec);
var specSize = MeasureSpec.GetSize(measureSpec);
if (specMode == MeasureSpecMode.Exactly)
{
// We were told how big to be
result = specSize;
}
else
{
result = NumPages * _cellSize;
if (specMode == MeasureSpecMode.AtMost)
{
// Respect AT_MOST value if that was what is called for by
// measureSpec
result = Math.Min(result, specSize);
}
}
return result;
}
private int MeasureHeight(int measureSpec)
{
var result = 0;
var specMode = MeasureSpec.GetMode(measureSpec);
var specSize = MeasureSpec.GetSize(measureSpec);
if (specMode == MeasureSpecMode.Exactly)
{
// We were told how big to be
result = specSize;
}
else
{
result = _cellSize;
if (specMode == MeasureSpecMode.AtMost)
{
// Respect AT_MOST value if that was what is called for by
// measureSpec
result = Math.Min(result, specSize);
}
}
return result;
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
var numPages = NumPages;
var activePageIndex = ActivePage;
var x = (canvas.Width - numPages * _cellSize)/2;
//var smallBorder = _cellSize/4;
//var slightlySmallerBorder = smallBorder - 1;
var emptyDotSize = _cellSize/4;
var dotOffset = (_cellSize - emptyDotSize) / 2;
for (var i = 0; i < numPages; i++, x += _cellSize)
{
if (i == activePageIndex)
{
//var txt = (i + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture);
//var bounds = new Rect();
//_textPaint.GetTextBounds(txt, 0, txt.Length, bounds);
//var oval = new RectF(x + smallBorder, smallBorder, x + _cellSize - smallBorder, _cellSize - smallBorder);
var oval = new RectF(x + dotOffset, dotOffset, x + dotOffset + emptyDotSize, dotOffset + emptyDotSize);
var oval1 = new RectF(x + dotOffset - 1, dotOffset - 1, x + dotOffset + emptyDotSize + 1, dotOffset + emptyDotSize + 1);
canvas.DrawOval(oval1, _dotBackgroundPaint);
canvas.DrawOval(oval, _dotPaint);
//canvas.DrawText(txt, x + (_cellSize - bounds.Width()) / 2, (_cellSize - _textHeight) / 2 + _ascent, _textPaint);
}
else
{
var oval = new RectF(x + dotOffset, dotOffset, x + dotOffset + emptyDotSize, dotOffset + emptyDotSize);
canvas.DrawOval(oval, _inactiveDotPaint);
}
}
}
private int DeviceIndependentToPixels(int dpi)
{
return (int)Math.Round((float)dpi * _displayDensity);
}
}
I will get a sample project in GitHub one day!
Even this is answered already:
Its possible with the Support-packages.
I just implemented it following this Java example.
You can just transfer anything that is written there to C# code, there are only a few things to take care of:
also the stuff commented out must be used
dont call the Class PagerAdapter
when the author wrote super.anything()use base.Anything()
when instantiating the fragments, make sure that u write the packagename in all lowercase.
Hope this helps anyone.

Categories

Resources