牛骨文教育服务平台(让学习变的简单)
博文笔记

android虚拟手柄摇杆的实现

创建时间:2015-03-02 投稿人: 浏览次数:3678

最近的项目开发中的一个任务是实现Android虚拟手柄界面,如图所示:


界面是一个SurfaceView,摇杆和按键都是通过画图显示出来的,这里详细介摇杆的实现,当用户点击摇杆即中间的黄球时,然后可以再圆圈内移动,这里运用了三角函数的知识,我们可以把黄球的中心点为一个含有4个象限的坐标的中心,当黄球移动的位置超出了圆圈时,就让黄球的位置设置为相对于坐标中心同一角度圆圈的边缘的点上的位置。下面直接上代码:

private void handleTouchMoveEvent(int x, int y) {
		if (found) {
			handleTouchDownEvent();
			mRect.left = x - mStickWidth/2;  
			mRect.top = y - mStickHeight/2;  
			mRect.right=mRect.left+mStickWidth;  
			mRect.bottom=mRect.top+mStickHeight; 
			//把摇杆的中心点作为基准坐标
			int baseX = (int) mPosition[0]+ mStickWidth/2;
			int baseY = (int) mPosition[1]+ mStickHeight/2;
			//当超出圆形区域后摇杆显示的坐标点
			int tX =mRect.left;
			int tY =mRect.top;
			//获取当前摇杆距离中心点的距离
			double r = Math.sqrt(Math.pow((x-baseX),2)+Math.pow((y-baseY),2));
			
			if(r!= 0 && r>maxLength){
				double sin = Math.abs(y-baseY)/r;
				double cos = Math.abs(x-baseX)/r; 
				//根据三角函数计算当摇杆超出圆形区域后在圆形区域边界显示的点的x轴和y轴分别距离中心点的距离
				int xLength = (int) (maxLength * cos);
				int yLength = (int) (maxLength * sin);
				//当摇杆与中心点在同一x轴时的坐标
				if(x==baseX && Math.abs(y-baseY)>maxLength){
					if(y>baseY){
						tY = baseY+maxLength;
					}else{
						tY = baseY-maxLength;
					}
				}
				//当摇杆与中心点在同一y轴时的坐标
				if(y==baseY && Math.abs(x-baseX)>150){
					if(x>baseX){
						tX = baseX+150;
					}else{
						tX = baseX-150;
					}
				}
				//当摇杆在以中心点为轴心的第一象限的范围内时的坐标
				if((x - baseX)>0 && (y-baseY)<0){
					tX = baseX + xLength;
					tY = baseY - yLength;
				}
				//当摇杆在以中心点为轴心的第二象限的范围内时的坐标
				if((x - baseX)<0 && (y-baseY)<0){
					tX = baseX - xLength;
					tY = baseY - yLength;
				}
				//当摇杆在以中心点为轴心的第三象限的范围内时的坐标
				if((x - baseX)<0 && (y-baseY)>0){
					tX = baseX - xLength;
					tY = baseY + yLength;
				}
				//当摇杆在以中心点为轴心的第四象限的范围内时的坐标
				if((x - baseX)>0 && (y-baseY)>0){
					tX = baseX + xLength;
					tY = baseY + yLength;
				}
				mRect.left = tX - mStickWidth/2;
				mRect.top = tY - mStickHeight/2;
				mRect.right =  mRect.left+mStickWidth;
				mRect.bottom = mRect.top+mStickHeight; 
			}
			updateValue(mRect.centerX(), mRect.centerY());
		} else {
			handleTouchUpEvent();
		}
	}


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。