Character never stops from walking - android

I am creating a game which uses andendgine and here is my code:
Player stanley = new Player();
...
scene.registerUpdateHandler(new IUpdateHandler() {
public void onUpdate(float pSecondsElapsed) {
stanX = stanley.getX();
destX = x.getX();
if(destX < stanX){
if(hasMovedRight == 1){
stanley.stop();
hasMovedRight = 0;
}
else{
stanley.moveLeft();
hasMovedRight = 0
hasMovedLeft = 1;
}
}
if(destX > stanX){
if(hasMovedLeft == 1){
stanley.stop();
hasMovedLeft == 0;
}
else{
stanley.moveRight();
hasMovedLeft = 0;
hasMovedRight = 1;
}
}
}
}
what i want is to stop Player from walking whenever his position X is equal to the touched area X. The problem is it never stop from walking. Thanks!

Your if statements are missing an element where destX == stanX. and you should really use else if. See modified code below.
if(destX + 8 < stanX){
if(hasMovedRight == 1){
stanley.stop();
hasMovedRight = 0;
}
else{
stanley.moveLeft();
hasMovedRight = 0
hasMovedLeft = 1;
}
}
else if(destX - 8 > stanX){
if(hasMovedLeft == 1){
stanley.stop();
hasMovedLeft == 0;
}
else{
stanley.moveRight();
hasMovedLeft = 0;
hasMovedRight = 1;
}
}
else //makes stanley stop. (calls stop method), if at touched x.
{
stanley.stop();
hasMovedRight = 0;
hasMovedLeft = 0;
}

try this one
setOnSceneTouchListener(new IOnSceneTouchListener() {
#Override
public boolean onSceneTouchEvent(Scene scene, TouchEvent event) {
int touchX = (int) (event.getX() - (sCHARStanley.getWidth() / 2));
//so that your sprite will go to the touched part of the screen
}

Related

Multi-Swipe in Unity

So I am trying to make a simple android game in which player has to move two objects in different halfs of the screen at the same time using swipes. It works just fine if I try to swipe to move one object and then the second one a moment after the first. But if I try swiping in two halfs at the same time it won't work. I tried managing with so-called multi-tuch but... well I need extra help.
public static event OnSwipeInput SwipeEvent;
public delegate void OnSwipeInput(Vector2 direction,bool side);
public static event OnSwipeInput SwipeEvent2;
private Vector2 tapPosition;
private Vector2 tapPosition2;
private Vector2 delta;
private Vector2 delta2;
private float deadZone = 30;
private bool isSwiping;
private bool isSwiping2;
private bool isMobile;
private bool left_side = true;
private bool left_side2 = true;
void Start()
{
isMobile = Application.isMobilePlatform;
isMobile = true;
Debug.Log("aaaa "+isMobile);
}
void Update()
{
float p;
if (!isMobile)
{
p = Mathf.Abs(Input.mousePosition.x) - Screen.width / 2;
if (Input.GetMouseButtonDown(0))
{
isSwiping = true;
tapPosition = Input.mousePosition;
if (p < 0)
left_side = true;
else
left_side = false;
}
else if(Input.GetMouseButtonDown(0))
ResetSwipe();
}
else
{
if (Input.touchCount >= 1) //try
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
p = Mathf.Abs(Input.GetTouch(0).position.x) - Screen.width / 2;
if (p < 0)
left_side = true;
else
left_side = false;
isSwiping = true;
tapPosition = Input.GetTouch(0).position;
}
else if (Input.GetTouch(0).phase == TouchPhase.Canceled || Input.GetTouch(0).phase == TouchPhase.Ended)
{
ResetSwipe();
}
}
if (Input.touchCount >= 2)
{
Input.multiTouchEnabled = true;
if (Input.GetTouch(1).phase == TouchPhase.Began)
{
p = Mathf.Abs(Input.GetTouch(1).position.x) - Screen.width / 2;
if (p < 0)
left_side2 = true;
else
left_side2 = false;
isSwiping2 = true;
tapPosition2 = Input.GetTouch(1).position;
}
else if (Input.GetTouch(1).phase == TouchPhase.Canceled || Input.GetTouch(1).phase == TouchPhase.Ended)
{
ResetSwipe2();
}
}
}
CheckSwipe();
}
private void CheckSwipe(){
if(Input.touchCount >= 1 || Input.GetMouseButton(0))
{
Debug.Log("there is 1 swipe");
delta = Vector2.zero;
if (isSwiping)
{
if (!isMobile && Input.GetMouseButton(0))
{
delta = (Vector2)Input.mousePosition - tapPosition;
}
else if (Input.touchCount == 1)
{
delta = (Vector2)Input.GetTouch(0).position - tapPosition;
}
}
if (delta.magnitude > deadZone)
{
if (SwipeEvent != null)
{
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
{
SwipeEvent.Invoke(delta.x > 0 ? Vector2.right : Vector2.left, left_side);
}
else
{
SwipeEvent.Invoke(delta.y > 0 ? Vector2.up : Vector2.down, left_side);
}
}
ResetSwipe();
}
}
else
{
Debug.Log("there are NO swipes");
}
if (Input.touchCount == 2)
{
Debug.Log("there are 2 swipes");
delta2 = Vector2.zero;
if (isSwiping2)
{
if (Input.touchCount == 2)
{
delta2 = (Vector2)Input.GetTouch(1).position - tapPosition;
}
}
if (delta2.magnitude > deadZone)
{
if (SwipeEvent2 != null)
{
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
{
SwipeEvent2.Invoke(delta2.x > 0 ? Vector2.right : Vector2.left, left_side2);
}
else
{
SwipeEvent2.Invoke(delta2.y > 0 ? Vector2.up : Vector2.down, left_side2);
}
}
ResetSwipe2();
}
}
}
private void ResetSwipe()
{
isSwiping=false;
tapPosition=Vector2.zero;
delta = Vector2.zero;
}
private void ResetSwipe2()
{
isSwiping2 = false;
tapPosition2 = Vector2.zero;
delta2 = Vector2.zero;
}
As you can see I am trying to operate with swipes differently seeing how many touches there are. No luck so far.
Any advice will be appriciated!
thank you

maze example not generating maze

I am following Maze game tutorial from youtube Android Programming - Maze Game Pt4
The tutor's code in the video generates random mazes. I have followed the code to the 'T' throughout but my emulator only gives the following output -
My emulator's output
Here is my code. Can anyone tell me what i missed from the tutorial I was following or if the tutorial itself has some coding errors? -
public class MazaGame extends View {
private Cell[][] cells;
private static final int COLS = 7, ROWS = 10;
private static final float WALL_THICKNESS = 4;
private float cellSize,hMargin,vMargin;
private Paint wallPaint;
private Random random;
public MazaGame(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
wallPaint = new Paint();
wallPaint.setColor(Color.BLACK);
wallPaint.setStrokeWidth(WALL_THICKNESS);
random = new Random();
createMaze();
}
private Cell getNeighbor(Cell cell){
ArrayList<Cell> neighbors = new ArrayList<>();
//left neighbor
if(cell.col >0)
if(!cells[cell.col-1][cell.row].visited)
neighbors.add(cells[cell.col-1][cell.row]);
//right neighbor
if(cell.col < COLS-1)
if(!cells[cell.col+1][cell.row].visited)
neighbors.add(cells[cell.col+1][cell.row]);
//top neighbor
if(cell.row >0)
if(!cells[cell.col][cell.row-1].visited)
neighbors.add(cells[cell.col][cell.row-1]);
//bottom neighbor
if(cell.row < ROWS-1)
if(!cells[cell.col][cell.row+1].visited)
neighbors.add(cells[cell.col][cell.row+1]);
if(neighbors.size()>0) {
int index = random.nextInt(neighbors.size());
return neighbors.get(index);
}
return null;
}
private void removeWall(Cell current, Cell next){
if(current.col == next.col && current.row == next.row+1){
current.topWall = false;
next.bottomWall = false;
}
if(current.col == next.col && current.row == next.row-1){
current.bottomWall = false;
next.topWall = false;
}
if(current.col == next.col+1 && current.row == next.row){
current.leftWall = false;
next.rightWall = false;
}
if(current.col == next.col-1 && current.row == next.row){
current.rightWall = false;
next.leftWall = false;
}
}
private void createMaze() {
Stack<Cell> stack = new Stack<>();
Cell current, next;
cells = new Cell[COLS][ROWS];
for (int x = 0; x < COLS; x++) {
for (int y = 0; y < ROWS; y++) {
cells[x][y] = new Cell(x, y);
}
}
do {
current = cells[0][0];
current.visited = true;
next = getNeighbor(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while (!stack.empty());
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.RED);
int width = getWidth();
int height = getHeight();
if(width/height < COLS/ROWS)
cellSize = width/(COLS+1);
else
cellSize = height/(ROWS+1);
hMargin = (width-COLS*cellSize)/2;
vMargin = (height-ROWS*cellSize)/2;
canvas.translate(hMargin,vMargin);
for(int x=0;x<COLS;x++){
for(int y=0;y<ROWS;y++){
if(cells[x][y].topWall)
canvas.drawLine(
x*cellSize,
y*cellSize,
(x+1)*cellSize,
y*cellSize,
wallPaint);
if(cells[x][y].leftWall)
canvas.drawLine(
x*cellSize,
y*cellSize,
x*cellSize,
(y+1)*cellSize,
wallPaint);
if(cells[x][y].bottomWall)
canvas.drawLine(
x*cellSize,
(y+1)*cellSize,
(x+1)*cellSize,
(y+1)*cellSize,
wallPaint);
if(cells[x][y].rightWall)
canvas.drawLine(
(x+1)*cellSize,
y*cellSize,
(x+1)*cellSize,
(y+1)*cellSize,
wallPaint);
}
}
}
private class Cell{
boolean
topWall = true,
rightWall = true,
bottomWall = true,
leftWall = true,
visited = false;
int col,row;
public Cell(int col, int row) {
this.col = col;
this.row = row;
}
}
}
I'm not going to take the time to fully internalize 100% of the code you posted, but this section looks suspicious:
do {
current = cells[0][0];
current.visited = true;
next = getNeighbor(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while (!stack.empty());
I suspect you want this to look like this instead:
current = cells[0][0];
current.visited = true;
do {
next = getNeighbor(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while (!stack.empty());
What you have right now will continuously reset current to be the cell at (0,0), because every time through the loop, you're executing
current = cells[0][0];
current.visited = true;
I suspect that this is just supposed to be the initial setup for the first cell, and you don't want this happening every time through the loop.

How to test the touch screen like this

I want to create an app to test the touch screen as shown in the above image.
My code for creating the layout as shown in the image is as follows :
private void fillScreen() {
try {
for (int i = 1; i < 14; i++) {
layoutMain = new LinearLayout(getApplicationContext());
for (int j = 1; j < 14; j++) {
b = new Button(getApplicationContext());
b.setTag("btn" + i + j);
b.setBackgroundColor(getResources().getColor(R.color.orange));
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_button_bg));
} else {
b.setBackground(getResources().getDrawable(R.drawable.my_button_bg));
}
b.setOnTouchListener(getOnClickDoSomething(b));
b.setLayoutParams(param);
layoutMain.addView(b);
if (i == j || j == (15 - i - 1) || j == 13 || j == 1 || i == 1 || i == 13) {
b.setVisibility(View.VISIBLE);
}
else {
b.setVisibility(View.INVISIBLE);
}
}
layoutMain.setLayoutParams(layoutParams);
layoutButtons.addView(layoutMain);
}
} catch (Exception e) {
Log.e("promptMessage,RotationActivity Exception", e.toString());
}
}
View.OnTouchListener getOnClickDoSomething(final Button btn) {
return new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!buttons.contains(btn.getTag())) {
buttons.add(btn.getTag());
btnCounter++;
}
btn.setBackgroundColor(getResources().getColor(R.color.videocon_header_green));
if ((btnCounter) == 67) {
flag++;
if (flag == 2)
promptMessage("Touch Screen test pass?");
}
return false;
}
};
}
I can change the colors of the button on touch but i want to "change the colors of the button when i swipe my fingers on the screen to left right top bottom".

How can I make each individual frog stop using onTouch?

I am making a game where there there are frogs hopping around the screen. Once a frog is touched, I change the game image to what I have set as "deadFrog" and its movement stops. I have them all created under and array-list, and I am unsure as to how to only make changes to the individual frog. Right now, if one frog is tapped, all of the frogs stop moving and change to deadFrog. Hopefully you can help me fix the tactical nuke of a tap ;) *If you need any more information, just comment and I'll be sure to provide it!
Edit Is there not a way to access a single element in the blocks arraylist? I've tried doing blocks(1) for example but that's invalid.
Here is where the frogs are declared:
public void init() {
blocks = new ArrayList<Block>();
for (int i = 0; i < 5; i++) {
Block b = new Block(i * 200, MainActivity.GAME_HEIGHT - 95,
BLOCK_WIDTH, BLOCK_HEIGHT);
blocks.add(b);
tapped = false;
}
}
They are rendered with this:
private void renderFrogs(Painter g) {
if (!tapped) {
for (int i = 0; i < blocks.size(); i++) {
Block b = blocks.get(i);
if (b.isVisible()) {
Assets.runAnim.render(g, (int) b.getX(), (int) b.getY());
}
}
}
if (tapped) {
for (int i = 0; i < blocks.size(); i++) {
Block b = blocks.get(i);
if (b.isVisible()) {
g.drawImage(Assets.deadfrog, (int) b.getX(), (int) b.getY());
}
}
}
}
And this is the onTouchListener:
public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
recentTouchY = scaledY;
} else if (e.getAction() == MotionEvent.ACTION_UP) {
for (int i = 0; i < blocks.size(); i++) {
Block b = blocks.get(i);
if ((scaledY >= b.getY() - BLOCK_HEIGHT || scaledY <= b.getY()) && (scaledX >= b.getX() || scaledX <= b.getX() + BLOCK_WIDTH)) {
tapped = true;
}
}
}
return true;
}
Of course all frogs turn dead, you are supposed to keep "tapped" variable for each frog, your tapped variable is for all frogs at once.
Declare a class
public class Frog extends View{
public Drawable liveFrog;
public Drawable deadFrog;
public boolean isDead;
public Point location;
public int width;
public int height;
public Frog(Context context, int x, int y,int width,int height){
super(context);
this.isDead = false;
this.location = new Point(x,y);
this.width = width;
this.height = height;
}
public void onDraw(Canvas c){
super.onDraw(c);
if(!isDead){
//draw live frog at x,y
}else {
//draw dead frog at x,y
}
}
}
then you array is supposed to contain frogs
public void init(Context context) {
blocks = new ArrayList<Frog>();
for (int i = 0; i < 5; i++) {
Frog b = new Frog(context,i * 200, MainActivity.GAME_HEIGHT - 95,
BLOCK_WIDTH, BLOCK_HEIGHT);
blocks.add(b);
}
}
private void renderFrogs() {
for(Frog f : blocks){
//cause redraw
f.invalidate();
}
}
here comes the fun part, when you tap the frog
public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
recentTouchY = scaledY;
} else if (e.getAction() == MotionEvent.ACTION_UP) {
for (int i = 0; i < blocks.size(); i++) {
Frog frog = blocks.get(i);
if ((scaledY >= frog.getY() - BLOCK_HEIGHT || scaledY <= frog.getY()) && (scaledX >= frog.getX() || scaledX <= frog.getX() + BLOCK_WIDTH)) {
frog.isDead = true;
//cause one frog redraw
frog.invalidate();
//if the event was handled, stop here (unless you can have multiple frogs one on top of the other ?
return true;
}
}
}
//if the event was not handled, let it bubble up
return false;
}
From what I can see, your "tapped" boolean is not a property of EACH frog. It is declared once, and when triggered, per your for loop, will make every frog dead (obviously, since that's what you're experiencing).
Once "tapped" is true, your for loop is going through every block and assigning a dead frog to it.
I think you need to create a Frog class, and store instances of those in your ArrayList. A variable of the new frog class will be "touched", and when that is triggered you will do something to that specific instance only.

TextView onTouchEvent within customview

I have a custom view, and within the custom view I create 4 text views. I want each of these text views to respond to on touch events. However, the textviews themselves do not respond to an on touch event. I can however, make an ontouch listener for the entire custom view. However, I do not want the whole view to have an ontouch event because I want the textviews that I have created to be dragged and dropped. I tried going the route of registering the x and y coordinates of the ontouch event and assuming that if the ontouch event is within the bounds of a textview, to change the coordinates of the textview, but that was overly complicated because if one textview got dragged to the coordinates of another one, then the ontouch event would "pick up" the other textview, so then I'd be moving two text views, which is not what I want. So, to sum it up, I want to know if it's possible to set in ontouch listener for a textview inside a customview, and if possible, why it is not working:
mScale.mPositive.get(0).setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
mScale.mCurrentXPos[0] = event.getX();
mScale.mCurrentYPos[0] = event.getY();
mScale.mDrag = true;
return true;
}
});
This same code works for the custom view, but not for the specific textviews inside that customview.
Here is the custom view code:
public class Scale extends View
{
public Scale(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = this.getContext();
h = new Handler();
mCalendarDbHelper=new CalendarDbAdapter(mContext);
mCalendarDbHelper.open();
Cursor thoughts = mCalendarDbHelper.fetchThoughts();
//create a string array of negative thoughts from the db
while (thoughts.moveToNext())
{
if (thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)).length() > 0 && thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)).charAt(0) == '-')
{
negative_thoughts.add(thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)));
}
}
thoughts.close();
array_size = negative_thoughts.size();
mBag =BitmapFactory.decodeResource(getResources(), R.drawable.bag);
mGreenBag = BitmapFactory.decodeResource(getResources(), R.drawable.green_bag);
for (int i = 0; i < 72; i ++)
{
try
{
mScale[i] = BitmapFactory.decodeStream(context.getAssets().open("scale_"+i+".gif"));
}
catch (IOException e)
{
}
}
}
private Runnable r= new Runnable()
{
#Override
public void run() {
invalidate();
}
};
protected void onDraw (Canvas canvas)
{
if (first == true)
{
width = this.getWidth();
height = this.getHeight();
mScale[i] = Bitmap.createScaledBitmap(mScale[i], (int) (width * 1.5), height, true);
mBag = Bitmap.createScaledBitmap(mBag, width/2, height/2, true);
negative = new TextView(mContext);
word = negative_thoughts.get((int) (Math.random() * array_size));
negative.setText(word);
negative.layout(0, 0, width/3, height/4);
negative.setGravity(Gravity.CENTER);
negative.setTextSize(15);
negative.setTextColor(Color.BLACK);
negative.setTypeface(Typeface.DEFAULT_BOLD);
negative.setShadowLayer(5, 2, 2, Color.WHITE);
negative.setDrawingCacheEnabled(true);
negative.setBackgroundResource(R.drawable.graycloud);
positive_paint.setColor(Color.parseColor("#FF4444"));
positive_paint.setShadowLayer(5, 2, 2, Color.YELLOW);
positive_paint.setTypeface(Typeface.DEFAULT_BOLD);
positive_paint.setTextSize(25);
mCurrentXPos[0] = (width/2);
mCurrentYPos[0] = height/4;
mCurrentXPos[1] = (width/2) + (width/8);
mCurrentYPos[1] = height/6;
mCurrentXPos[2] = width/2;
mCurrentYPos[2] = height/12;
mCurrentXPos[3] = (width/2) + (width/8);
mCurrentYPos[3] = height/18;
mMoveXPos[0] = ((width/2) - width)/FRAME_RATE;
mMoveYPos[0] = ((height/4) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[1] = (((width/2) + (width/8)) - width)/ FRAME_RATE;
mMoveYPos[1] = ((height/6) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[2] = ((width/2) - width)/ FRAME_RATE;
mMoveYPos[2] = ((height/12) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[3] = (((width/2) + (width/8)) - width)/ FRAME_RATE;
mMoveYPos[3] = ((height/18) - (height + (height/4)))/FRAME_RATE;
mMoveByXPos[0] = -(width/2)/ FRAME_RATE;
mMoveByYPos[0] = -(height/4)/FRAME_RATE;
mMoveByXPos[1] = ((width - (width/3)) - (width/2 + (width/8)))/ FRAME_RATE;
mMoveByYPos[1] = -(height/6)/FRAME_RATE;
mMoveByXPos[2] = - (width/2)/ FRAME_RATE;
mMoveByYPos[2] = ((height) - (height/12))/FRAME_RATE;
mMoveByXPos[3] = ((width - (width/3)) - (width/2 + (width/8)))/ FRAME_RATE;
mMoveByYPos[3] = ((height) - (height/18))/FRAME_RATE;
currentX = width;
currentY = height + height/4;
first = false;
}
if (game_over == false)
{
canvas.drawBitmap(mScale[i], 0 - (width/4), 0, null);
canvas.drawBitmap(negative.getDrawingCache(),(int) (width/12), (int) (height - (height)/2.5) - (j), null);
}
else
{
canvas.drawBitmap(mBag, width/4, height/4, null);
}
if (mMoveScale == true)
{
i++;
j+=3;
ScaleIt(canvas, i);
if (i == 21 || i == 37 || i == 53 || i == 71)
{
mMoveScale = false;
}
}
if (tracker > 0)
{
if (tracker == 1)
{
if (currentX > width/2 && currentY > height/4 && sStop == false)
{
currentX += mMoveXPos[0];
currentY += mMoveYPos[0];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 2)
{
if (currentX > width/2 + (width/8) && currentY > (height/6) && sStop == false)
{
currentX += mMoveXPos[1];
currentY += mMoveYPos[1];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 3)
{
if (currentX > width/2 && currentY > height/12 && sStop == false)
{
currentX += mMoveXPos[2];
currentY += mMoveYPos[2];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 4)
{
if (currentX > width/2 + (width/8) && currentY > (height/18) && sStop == false)
{
currentX += mMoveXPos[3];
currentY += mMoveYPos[3];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
game_over = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (draw_em > 0 && game_over == false)
{
for (int i = 0; i < draw_em; i ++)
{
if (i == 0)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2, height/4 + j, null);
}
if (i == 1)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2 + (width/8), height/6 + j, null);
}
if (i == 2)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2, height/12 + j, null);
}
if (i == 3)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2 + (width/8), height/18 + j, null);
}
}
}
else if (game_over == true)
{
for (int i = 0; i < draw_em; i++)
{
if (i == 0 && mCurrentXPos[0] > 0 && mCurrentYPos[0] > 0 && mDrag == false)
{
mCurrentXPos[0] += mMoveByXPos[0];
mCurrentYPos[0] += mMoveByYPos[0];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[0], mCurrentYPos[0], null);
}
else if (i == 0 && mCurrentXPos[0] <= 0 || mCurrentYPos[0] <= 0 && mDrag == false)
{
canvas.drawBitmap(mPositive.get(0).getDrawingCache(), 0, 0, null);
}
else if (i == 0 && mDrag == true)
{
canvas.drawBitmap(mPositive.get(0).getDrawingCache(), mCurrentXPos[0], mCurrentYPos[0], null);
}
if (i == 1 && mCurrentXPos[1] < (width - (mPositive.get(i).getWidth()/2)) && mCurrentYPos[1] > mPositive.get(i).getHeight()/2)
{
mCurrentXPos[1] += mMoveByXPos[1];
mCurrentYPos[1] += mMoveByYPos[1];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[1], mCurrentYPos[1], null);
}
else if (i == 1 && mCurrentXPos[1] >= (width - (mPositive.get(i).getWidth()/2)) || mCurrentYPos[1] <= mPositive.get(i).getHeight()/2)
{
canvas.drawBitmap(mPositive.get(1).getDrawingCache(), width - (width/3), 0, null);
}
if (i == 2 && mCurrentXPos[2] > (mPositive.get(i).getWidth()/2) && mCurrentYPos[2] < (height - mPositive.get(i).getHeight()/2))
{
mCurrentXPos[2] += mMoveByXPos[2];
mCurrentYPos[2] += mMoveByYPos[2];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[2], mCurrentYPos[2], null);
}
else if (i == 2 && mCurrentXPos[2] <= (mPositive.get(i).getWidth()/2) || mCurrentYPos[2] >= (height - mPositive.get(i).getHeight()/2))
{
canvas.drawBitmap(mPositive.get(2).getDrawingCache(), 0, height - (height/4), null);
}
if (i == 3 && mCurrentXPos[3] < (width - (mPositive.get(i).getWidth()/2)) && mCurrentYPos[3] < (height - mPositive.get(i).getHeight()/2))
{
mCurrentXPos[3] += mMoveByXPos[3];
mCurrentYPos[3] += mMoveByYPos[3];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[3], mCurrentYPos[3], null);
}
else if (i == 3 && mCurrentXPos[3] >= (width - (mPositive.get(i).getWidth()/2)) || mCurrentYPos[3] >= (height - mPositive.get(i).getHeight()/2))
{
canvas.drawBitmap(mPositive.get(3).getDrawingCache(), width - (width/3), height - (height/4), null);
}
}
}
}
h.postDelayed(r, FRAME_RATE);
}
protected void moveIt(Canvas canvas, int moveX,int moveY, int i)
{
if (i == 0)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 1)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 2)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 3)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
}
protected void moveEm(Canvas canvas, int[]mMovePosX, int[] mMovePosY)
{
for (int i = 0; i < 4; i++)
{
}
}
protected void ScaleIt(Canvas canvas, int i)
{
mScale[i] = Bitmap.createScaledBitmap(mScale[i], (int) (width * 1.5), height, true);
mScale[i-1].recycle();
}
}
And here is the activity:
public class ScaleView extends Activity
{
Context mContext;
Scale mScale;
EditText positive_thought;
Button fire;
TextView pos;
private static Set<String> mPositiveWords;
private static Set<String> mNegativeWords;
int count;
private Pattern four_letter_words = Pattern.compile("not|cant|cnt|can't");
String inputLine;
private String[] inputTokens;
Button question;
Button skip;
public static boolean populatePositiveWords(Context context)
{
mNegativeWords = new HashSet<String>();
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open("negative_words.txt")));
String line = reader.readLine();
while (line != null)
{
mNegativeWords.add(line.toLowerCase(Locale.US));
line = reader.readLine();
}
reader.close();
}
catch (IOException exception)
{
return false;
}
return true;
//TODO list of negative words
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getActionBar().hide();
mContext = this;
populatePositiveWords(mContext);
setContentView(R.layout.activity_scale);
mScale = (Scale) findViewById(R.id.anim_view);
mScale.setClickable(true);
positive_thought = (EditText) findViewById(R.id.thoughts);
fire = (Button) findViewById(R.id.scale_it);
skip = (Button) findViewById(R.id.skip);
question = (Button) findViewById(R.id.question);
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(60);
positive_thought.setFilters(FilterArray);
fire.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
//if the button is clicked invalidate the ondraw method and pass in the text of the positive word
inputLine = positive_thought.getText().toString();
inputTokens = inputLine.split(" ");
if (inputLine.isEmpty())
{
Toast.makeText(mContext, "You have to write something!", Toast.LENGTH_SHORT).show();
return;
}
if (inputTokens.length < 3)
{
Toast.makeText(mContext, "At least three words are required.", Toast.LENGTH_SHORT).show();
return;
}
if (four_letter_words.matcher(inputLine).find() == true)
{
Toast.makeText(mContext, "Make an affirmative statement!", Toast.LENGTH_SHORT).show();
return;
}
boolean matchesToken = false;
for (int i = 0; i < inputTokens.length; i++)
{
String token = inputTokens[i];
if (mNegativeWords.contains(token.toLowerCase(Locale.US)))
{
matchesToken = true;
break;
}
}
if (matchesToken == true)
{
Toast.makeText(mContext, "Use positive words!", Toast.LENGTH_SHORT).show();
return;
}
else
{
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(positive_thought.getWindowToken(), 0);
pos = new TextView (mContext);
pos.layout(0, 0, mScale.width/3, mScale.height/4);
pos.setGravity(Gravity.CENTER);
pos.setTextSize(15);
pos.setTextColor(Color.RED);
pos.setTypeface(Typeface.DEFAULT_BOLD);
pos.setShadowLayer(5, 2, 2, Color.YELLOW);
pos.setText(positive_thought.getText().toString());
pos.setDrawingCacheEnabled(true);
pos.setBackgroundResource(R.drawable.whitecloud);
pos.setClickable(true);
mScale.mPositive.add(pos);
mScale.scale_it = true;
count++;
mScale.sStop = false;
mScale.tracker = count;
if (count == 4)
{
((RelativeLayout)question.getParent()).removeView(question);
((RelativeLayout)skip.getParent()).removeView(skip);
mScale.mPositive.get(0).setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
mScale.mCurrentXPos[0] = event.getX();
mScale.mCurrentYPos[0] = event.getY();
mScale.mDrag = true;
return true;
}
});
}
}
positive_thought.setText(null);
}
});
}
}
The reason your TextView cannot receive touch events is that the TextView is drawn on the canvas just as a bitmap, not as a View. An excerpt from your code shown below illustrates this.
protected void onDraw(Canvas canvs)
{
....
negative = new TextView(mContext);
...
canvas.drawBitmap(negative.getDrawingCache(), ...)
To deliver touch events to your TextView, your Scale class should extend not View but ViewGroup and the TextView needs to be added as a subview to Scale class by using ViewGroup.addView() or addViewInLayout(). It is not a simple task to implement a ViewGroup subclass. You may have to implement onInterceptTouchEvent(MotionEvent) depending on your needs.
Android's source code will be of help.
Is your CustomView also sets some TouchListner??
If yes then this might causing issue..Remove TouchListner from CustomView and see if it works..

Categories

Resources