Android happy Snake Game Development tutorial-05 virtual direction key (4) four triangle buttons, android-05

Source: Internet
Author: User

Android happy Snake Game Development tutorial-05 virtual direction key (4) four triangle buttons, android-05

Overview and directory of this series of tutorials: http://www.cnblogs.com/chengyujia/p/5787111.html

I. How to determine which direction key is clicked

In the previous tutorial, we implemented the triangle button on the left. In this tutorial, we implemented the buttons on the left, top, right, and bottom.
Can you make one? Should the other three be difficult? But it's not easy.
First, let's solve a problem left over from the last lesson. How can we determine which triangle button is clicked by the finger?


This should be solved by the resolution ry method.
Assume that our control is a square with a side length of 1 and establishes a plane Cartesian coordinate system (note: the origin of the coordinate system in the computer is in the upper left corner), for example:

The diagonal lines of a square divide the control into four triangle areas, that is, our four arrow keys.

We can see that:
The diagonal line from the upper left corner to the lower right corner is y = x;
Y> x contains the left and bottom triangles.
The area of y <x contains the right and top triangles.

The diagonal line from the upper right to the lower left is y =-x + 1;
The area of y> contains the right and bottom triangles.
The area of y <contains the left and top triangles.

In summary:
Y> x and y <indicates the Left triangle.
Y <x and y <indicates the upper triangle
Y <x and y> indicates the right triangle.
Y> x and y> indicate lower triangle

The above is the conclusion based on the square with a side length of 1. But in reality, our control is not necessarily a square, and the side length is not 1, but an uncertain rectangle. What should we do?
This requires a certain conversion to convert a normal rectangle to a square with a side length of 1.
This transformation is also simple, as follows:
If the coordinates of the touched points on the canvas are (x, y), then:

    float relativeX = x / width;//0<=relativeX<=1    float relativeY = y / height;//0<=relativeY<=1

We divide the horizontal and vertical coordinates of the touched points on the canvas by the width and height of the canvas. In this way, a relative coordinate is obtained, and the value of this relative coordinate must be between 0 and 1. This is equivalent to simplifying an uncertain rectangle into a square with a side length of 1.

Ii. program code

With the above understanding, you can write the code below. Because there are four triangle buttons, and each button has two states, the code will be a little longer. However, the logic of each button is the same, and the highlighted button is used to restore the normal state if the button is not displayed on time. The comments in the Code are more detailed. I believe that if you read the content of the previous tutorial, it should not be a problem. The only thing to note is that each time you call the invalidate method to redraw the interface, you need to re-paint the entire canvas, instead of just one triangle.

Here we need to first introduce an enumeration indicating the Direction: Direction

Package net. chengyujia. happysnake;/*** indicates the direction enumeration * Created by ChengYuJia on 2016/8/21. */public enum Direction {// none indicates that no Direction key is pressed for none, // left, // up, // right, // down ;}

 
The complete DirectionKeys code is as follows:

Package net. chengyujia. happysnake; import android. content. context; import android. graphics. canvas; import android. graphics. paint; import android. graphics. path; import android. util. attributeSet; import android. view. motionEvent; import android. view. view;/*** the virtual arrow key * Created by ChengYuJia on. */public class DirectionKeys extends View {// color (brighter) when the Left triangle is pressed private int leftPressedColor = 0xFFFF0000; // Normal display color of the Left triangle (darker) private int leftNormalColor = 0xFFAA0000; // The color when the top triangle is pressed (brighter) private int upPressedColor = 0xFF00FF00; // normal display color of the upper triangle (darker) private int upNormalColor = 0xFF00AA00; // color of the right triangle (brighter) private int rightPressedColor = 0xFF0000FF; // The normal display color of the right triangle (darker) private int rightNormalColor = 0xFF0000AA; // The color when the triangle is pressed (brighter) private int downPressedColor = 0xFFFFFF00; // The normal color (darker) of the lower triangle private int downNormal Color = 0xFFAAAA00; // Paint brush private paint = new Paint (); // draw the Path of the Left triangle private Path pathLeft = new Path (); // draw the triangle Path private Path pathUp = new Path (); // draw the right triangle Path private Path pathRight = new Path (); // draw the Path private Path pathDown = new Path (); // The width of the canvas private int width; // The height of the canvas private int height; // whether the initialization method has been executed. Make sure that the initialization method is only executed once. Private boolean initDone = false; // record which Direction key is currently pressed private Direction currentDirection = Direction. none; // The constructor with only one parameter is called when an instance is created using the "new" keyword in the program. Public DirectionKeys (Context context) {super (context) ;}// the constructor with two parameters is called when the system creates an instance in the XML layout file. Public DirectionKeys (Context context, AttributeSet attrs) {super (context, attrs);} // initialization method private void init (Canvas canvas) {/* obtain the length and width of the canvas */width = canvas. getWidth (); height = canvas. getHeight ();/* (TIPS: Generally, the upper left corner is used as the coordinate origin in the computer) the coordinates of the four vertices and the center points on the canvas are as follows: Top left vertex 0, bottom left vertex 0, height top right point width, 0 bottom right point width, height center point width/2, height/2 * // * set the path data of the Left triangle * // start pathLeft from the top left of the canvas. moveTo (0, 0); // draw a straight line to the canvas center pathLeft. lineTo (wid Th/2, height/2); // draw a straight line to the bottom left of the canvas. pathLeft. lineTo (0, height); // automatically close the image. Draw a straight line from the last vertex (lower left vertex) to the first vertex (upper left vertex ). PathLeft. close ();/* similarly set the path data of the triangle */pathUp. moveTo (0, 0); pathUp. lineTo (width/2, height/2); pathUp. lineTo (width, 0); pathUp. close ();/* similarly set the path data of the right triangle */pathRight. moveTo (width, 0); pathRight. lineTo (width/2, height/2); pathRight. lineTo (width, height); pathRight. close ();/* similarly set the path data of the triangle */pathDown. moveTo (width, height); pathDown. lineTo (width/2, height/2); pathDown. lineTo (0, height); pathDow N. close () ;}// shared method of painting Path private void drawPath (path Path, int color, Canvas canvas) {// set the paint color. setColor (color); // use a paint brush to draw a canvas Based on path data. drawPath (path, paint);} // specifies the normal color of the Left triangle. private void drawLeftNormal (Canvas canvas) {drawPath (pathLeft, leftNormalColor, canvas );} // draw the left Triangle Press color (highlighted) private void drawLeftPressed (Canvas canvas) {drawPath (pathLeft, leftPressedColor, canvas);} // draw the triangle normal color private Void drawUpNormal (Canvas canvas) {drawPath (pathUp, upNormalColor, canvas);} // draw a Triangle Press color (highlighted) private void drawUpPressed (Canvas canvas) {drawPath (pathUp, upPressedColor, canvas);} // draw the right triangle normal color private void drawRightNormal (Canvas canvas) {drawPath (pathRight, rightNormalColor, canvas);} // draw the right triangle press color (highlighted) private void drawRightPressed (Canvas canvas) {drawPath (pathRight, rightPressedColor, canvas );}/ /Draw down the normal triangle color private void drawDownNormal (Canvas canvas) {drawPath (pathDown, downNormalColor, canvas);} // draw down the triangle to press the color (highlighted) private void drawDownPressed (Canvas canvas) {drawPath (pathDown, downPressedColor, canvas);} // All buttons restore normal colors private void reset (Canvas canvas) {drawLeftNormal (canvas); drawUpNormal (canvas ); drawRightNormal (canvas); drawDownNormal (canvas);} // when you press the Left triangle, the Left triangle is highlighted. Other values are normal. Private void drawWhenLeftPressed (Canvas canvas) {drawLeftPressed (canvas); drawUpNormal (canvas); drawRightNormal (canvas); drawDownNormal (canvas);} // when you press the upper triangle, the upper triangle is highlighted, and others are normal. Private void drawWhenUpPressed (Canvas canvas) {drawLeftNormal (canvas); drawUpPressed (canvas); drawRightNormal (canvas); drawDownNormal (canvas);} // when you press the right triangle, highlight the right triangle. Other values are normal. Private void drawWhenRightPressed (Canvas canvas) {drawLeftNormal (canvas); drawUpNormal (canvas); drawRightPressed (canvas); drawDownNormal (canvas);} // when you press the triangle, the lower triangle is highlighted, others are normal. Private void drawWhenDownPressed (Canvas canvas) {drawLeftNormal (canvas); drawUpNormal (canvas); drawRightNormal (canvas); drawDownPressed (canvas );} /*** rewrite the onDraw method of the parent class to draw the image we need * This method will be called by the system when the control is displayed for the first time, the system calls the invalidate method each time later. ** @ Param canvas the canvas here is a rectangle canvas provided by the system. What we need to do is to draw what we want on this canvas. * // @ Override protected void onDraw (Canvas canvas) {if (! InitDone) {init (canvas); // make sure that the initialization method is executed only once. initDone = true;} // press different direction keys to draw different interface effects. Switch (currentDirection) {case left: // drawWhenLeftPressed (canvas); break; case up: // drawWhenUpPressed (canvas); break; case right: // right-click drawWhenRightPressed (canvas); break; case down: // drawWhenDownPressed (canvas); break; default: // reset (canvas) in other cases;}/*** when you touch the control, the system uses this method to tell the control "you have been touched, do you want to respond? If a response is returned, true is returned. If no response is returned, false is returned ." * The control says, "it depends on how you touch it. If it is pressed, I will highlight the corresponding triangle button; if it is lifted, I will restore all the triangle buttons to a normal color. I won't respond in other cases. Just touch it ." ** @ Param event: the parameter of the touch event that the system sends to us * @ return: If the touch event is processed, true is returned, and false is returned. * // @ Override public boolean onTouchEvent (MotionEvent event) {// get the current touch action int action = event. getAction (); if (action = MotionEvent. ACTION_DOWN) {// press // to obtain the coordinate float x = event of the touch point. getX (); float y = event. getY (); currentDirection = getDirection (x, y); invalidate (); // re-paint return true;} else if (action = MotionEvent. ACTION_UP) {// raise currentDirection = Direction. none; invalidate (); // re-paint return true;} el Se {// otherwise do not handle return false;} // determine which triangle Direction key is pressed according to the coordinates. private Direction getDirection (float x, float y) {// After coordinate transformation, unified into a square with a side length of 1. The four regions formed by diagonal lines represent four directions. Float relativeX = x/width; // 0 <= relativeX <= 1 float relativeY = y/height; // 0 <= relativeY <= 1/* Note: the origin is the upper left corner. The diagonal line from the upper left corner to the lower right corner is y = x; then: the area of y> x contains the left and bottom triangles. the area of y <x contains the diagonal line equation from the right and the bottom left to the top right of the upper triangle. The equation is y =-x + 1. Then: the area of y> contains the area of the right triangle and the area of the lower triangle y <contains the area of the Left triangle and the upper triangle: y> x and y <represents the Left triangle y <x and y <represents the upper triangle y <x and y> represents the right triangle y> x and y> represents the lower triangle. */if (relativeY> relativeX) {// left and lower if (relativeY <1-relativeX) {// left return Direction. left;} else {// return ction. down;} else {// and right if (relativeY <1-relativeX) {// return Direction. up;} else {// right return Direction. right ;}}}}

 

Iii. Running Effect

Effect when no click is found:

 

Effect of clicking the left button:

 

Click the created result:

 

Effect of right-click:

 

The following figure shows the effect when you click the lower key:

 

At this point, the four background triangles of our custom arrow keys are ready, and the color-changing button is clicked.

We will draw corresponding arrows on the four triangles, and the color change effect will also be displayed. We look forward to o (^) o

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.