I'm making a simple Breakout game, and so far I have created the ball and the player. I made the ball so that it moves to the position you touch, but I'd rather have it moving towards the direction I swipe. As in, the player moves along with my finger. Here's the code I have in my MainActivity:
package com.example.breakout;
import android.os.Bundle;
import android.app.Activity;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends Activity implements OnTouchListener, OnGestureListener{
BreakoutView bv;
GestureDetector gs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bv = new BreakoutView(this);
setContentView(bv);
bv.setOnTouchListener(this);
gs = new GestureDetector(MainActivity.this, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
/*if(arg1.getY()<600){
bv.p1.x = arg1.getX();
bv.p1.y = 600;
}*/
return false;
}
#Override
public boolean onTouchEvent(MotionEvent me){
return gs.onTouchEvent(me);
}
#Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
/*if(e2.getX()>e1.getX()){
//Move right
bv.p1.x = e2.getX();
}*/
return false;
}
#Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
}
So, the two methods I have tried are the onTouch and the onFling ones. The onTouch "teleports" my player where I touch, which isn't what I want. The onFling only moves my player when I'm done swiping, so that doesnt work either. My question is, how can I make it move as I swipe my finger? Do I use onDown? Any help is appreciated.
Thanks!
Assuming you have some sort of game loop set up where the UI is updated on intervals:
/**
* Onclick event for Touch Screen
*/
#Override
public boolean onTouchEvent(MotionEvent input) {
if (input.getAction() == MotionEvent.ACTION_MOVE) {
float currX = input.getX();
float currY = input.getY();
if (!swiping) {
swiping = true;
swipeStartY = currY;
swipeStartX = currX;
}
if (swiping) {
double newDirection = Math.atan2((currY-ball.getY()),currX-ball.getX());
ball.setDirection(newDirection);
}
} else if (input.getAction() == MotionEvent.ACTION_UP) {
if (swiping) {
swiping = false;
}
}
}
This way the ball's direction is updated on each tick of the game thread and moves towards your finger (the touch event X/Y location). I'm not sure how you have set up your drawing/physics/etc. so I can't provide meaningful function calls here. If you need to modify it so it swipes in a straight line after you lift your finger then store the initial X/Y point (swipeStartX/swipeStartY in this case) and only set the new direction after you stop swiping.
EDIT:
I should mention, my class definition that contains this code is as follows:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
....
}
Related
after clicking the button mouse scroll will be activated and scroll up, button value should be increment and when scroll down value decrement. but button outside code working,then button inside code not work.my sample code here.
public class MainActivity extends Activity {
Button button;
int x,f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
button.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
// i need implement code here ,how can i do?
return false;
}
});
}
#SuppressLint("NewApi") #Override
public boolean onGenericMotionEvent(MotionEvent event) {
//if (0 != (event.getSource() & InputDevice.SOURCE_CLASS_POINTER)) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL:
if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f)
//selectNext();
{
x=Integer.parseInt(button.getText().toString());
f=x+5;
button.setText(""+f);
}
else
{
x=Integer.parseInt(button.getText().toString());
f=x-5;
button.setText(""+f);
return true;
}
}
return super.onGenericMotionEvent(event);
} }
i need those function inside the touch listener i don't know how can i do,please help me!
So I'm getting an error in my Java class that tells me that R isn't a resolved symbol. I also noticed that whenever I went around online, some of other ppl's codes was slightly different than others and assumed that it was because of the updates and such that's causing these sorts of errors.
In short, I want to know how you call a layout in the Java. R.layout.activity_main isn't working and returning an error.
This is the whole code and yes, I'm using someone's code online to see if I can connect my app. Think of it as a small test.
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class Search extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String serverKey = "AIzaSyCuwJyE96NvT62erGiWbMEefVAiQptAmus";
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
playerStateChangeListener = new MyPlayerStateChangeListener();
playbackEventListener = new MyPlaybackEventListener();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
if (!wasRestored) {
player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private MyPlayerStateChangeListener playerStateChangeListener;
private MyPlaybackEventListener playbackEventListener;
private final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {
#Override
public void onPlaying() {
// Called when playback starts, either due to user action or call to play().
showMessage("Playing");
}
#Override
public void onPaused() {
// Called when playback is paused, either due to user action or call to pause().
showMessage("Paused");
}
#Override
public void onStopped() {
// Called when playback stops for a reason other than being paused.
showMessage("Stopped");
}
#Override
public void onBuffering(boolean b) {
// Called when buffering starts or ends.
}
#Override
public void onSeekTo(int i) {
// Called when a jump in playback position occurs, either
// due to user scrubbing or call to seekRelativeMillis() or seekToMillis()
}
}
private final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoading() {
// Called when the player is loading a video
// At this point, it's not ready to accept commands affecting playback such as play() or pause()
}
#Override
public void onLoaded(String s) {
// Called when a video is done loading.
// Playback methods such as play(), pause() or seekToMillis(int) may be called after this callback.
}
#Override
public void onAdStarted() {
// Called when playback of an advertisement starts.
}
#Override
public void onVideoStarted() {
// Called when playback of the video starts.
}
#Override
public void onVideoEnded() {
// Called when the video reaches its end.
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
// Called when an error occurs.
}
}
}
For my Buttons onClickListener I have the following code:
on_enter_button.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
enter(words, linearLayout, llp, view);
}
});
Instead of pressing enter Button, I simply want to Swipe the screen in any direction and run the same method: enter(words, linearLayout, llp, view);
Currently I think my program does not recognize Swipe gestures at all. I assume it's because I placed enter(words, linearLayout, llp, view); incorrectly. Also, I put all the Gesture recognition code inside the onCreate(). Is that the correct way to program the code?
Can someone please help?
EDITED CODE:
public class Game extends Activity{
public void enter(String[] w, LinearLayout ll, LinearLayout.LayoutParams params, View v){
... //some code
... //some code
... //some code
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return myGestureDetector.onTouchEvent(event);
//error myGestureDetector not recognized since it's created in onCreate so it does not exist here
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
SimpleOnGestureListener mySimpleGestureListener = new SimpleOnGestureListener()
{
#Override
public boolean onDoubleTap(MotionEvent e) {
return super.onDoubleTap(e);
}
#Override
//swipe does not work!
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)
{
enter(words, linearLayout, llp, view);
return super.onFling(e1, e2, velocityX, velocityY);
}
#Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return super.onSingleTapConfirmed(e);
}
private boolean permissibleYVelocity(float velocityY)
{
if ((velocityY < -200) || (velocityY > 200))
{
return false;
}
else
{
return true;
}
}
};
final GestureDetector myGestureDetector = new GestureDetector(getApplicationContext(), mySimpleGestureListener);
//button listener works
on_enter_button.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
enter(words, linearLayout, llp, view);
}
});
}
}
You need to override View.onTouchEvent().
#Override
public boolean onTouchEvent(MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
Call your method in SimpleOnGestureListener.onFling():
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)
{
enter(words, linearLayout, llp, view);
return true;
}
EDIT:
Setup your GestureDectector in onCreate() as well:
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener()
{
#Override
public boolean onDoubleTap(MotionEvent e) {
return super.onDoubleTap(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)
{
enter(words, linearLayout, llp, view);
return super.onFling(e1, e2, velocityX, velocityY);
}
#Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return super.onSingleTapConfirmed(e);
}
private boolean permissibleYVelocity(float velocityY)
{
if ((velocityY < -200) || (velocityY > 200))
{
return false;
}
else
{
return true;
}
}
});
I need to use Androids Switch button control but I need to be able to detect changes when the user is dragging the control not on clicking. So if the user drags from off to on and holds it in the on position I need to detect that. I thought I could just set the onTouchListener and then look at when the switches text changes state (on/off off/on) and then trigger my changes then but I can't. The
mySwitch.getText()
Does not work for me. It return blank text even though I have the textOn and textOff attributes set. I need to be able to detect the state change when the user is dragging, not on click. The onCheckedChanged listener will not work for me since that triggers only when the user toggles or slides and lifts there finger off of the button. Any help would be appreciated. Thank you.
Basic Code:
public class MainActivity extends Activity {
private String TAG = MainActivity.class.getSimpleName();
private TextView switchStatus;
private Switch mySwitch;
private TextView mySwitchText;
private String oldState;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchStatus = (TextView) findViewById(R.id.switchStatus);
mySwitch = (Switch) findViewById(R.id.mySwitch);
//set the switch to ON
mySwitch.setChecked(false);
oldState = mySwitch.getText().toString();
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
//switchStatus.setText("Switch is currently ON");
}else{
// switchStatus.setText("Switch is currently OFF");
}
}
});
mySwitch.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == event.ACTION_MOVE) {
if(oldState.equals("OFF") && mySwitch.getText().equals("ON")) {
switchStatus.setText("Off to On");
oldState = "ON";
}
if(oldState.equals("ON") && mySwitch.getText().equals("OFF")) {
switchStatus.setText("On to Off");
oldState = "OFF";
}
}
Log.v(TAG, "Old State: " + oldState + " my Switch: " + mySwitch.getText().toString());
return false;
}
});
mySwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mySwitch.isChecked()) {
mySwitch.setChecked(false);
}
}
});
//check the current state before we display the screen
if(mySwitch.isChecked()){
switchStatus.setText("Switch is currently ON");
}
else {
switchStatus.setText("Switch is currently OFF");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Switch is a distant descendant of textview. Therefore you'd have to do this to make it work.
oldState = (TextView)mySwitch.getText().toString();
However, Switch has a textOn and textOff that works for this purpose.
I am not sure how to make a simple onFling simply start an animation. It doesnt matter which direction the swipes go any contact and slide across the screen should cause the animation to start. The other thing I am wondering is how to get it to let the animation run through and when the animation finishes I want it to display a picture. To give you an idea of what I am doing picture a twister spin board. The animation is the spinner spinning and after it finishes spinning it stops and points in a direction. How can I get a similar effect. (The animation is a spinning animation and the pictures are all pointing in differnt directions)
Would appreciate any help anyone can give. Thanks.
one possibility: use a gesturedetector to detect the fling.
psuedocode:
public class WhatEver extends Activity implements OnGestureListener {
private GestureDetector gestures;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gestures = new GestureDetector(mContext, this);
View yourViewYouWantToHaveThemFling=(View) findViewById(blah..);
yourViewYouWantToHaveThemFling.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
if (gestures.onTouchEvent(event)) {
return true;
}
return false;
}
});
}
//all your normal stuff
#Override
public boolean onDown(MotionEvent e) {
return true; //must return true to continue
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
//do something
return false;
}
#Override
public void onLongPress(MotionEvent e) {
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}
#Override
public void onShowPress(MotionEvent e) {
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
}
as for the animation, set a listener on your animation,
yourAnimation.setAnimationListener(new DisplayPicture());
then
private final class DisplayPicture implements Animation.AnimationListener {
.
.
public void onAnimationEnd(Animation animation) {
//code to display your picture here
}
.
.
}