⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mycanvas.txt

📁 JAVA写的简单的碰撞检测
💻 TXT
字号:
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;


public class MyCanvas extends Canvas{
  //移动小方块的左上角坐标和长宽
	int x,y,d;
  //静止小方块的左上角坐标和长宽
	int rectx,recty,rectw,recth;
	/**
	 * 构造函数。完成初始化
	 */
	public MyCanvas(){
		x=10;
		y=10;
		d=10;
		rectx=100;
		recty=100;
		rectw=20;
		recth=10;
	}
	public void paint(Graphics g){
		g.setColor(0xffffff);
		g.fillRect(0, 0, getWidth(),getHeight());
		g.setColor(150,200,100);
		g.fillRect(x,y,d,d);
		g.fillRect(rectx, recty, rectw, recth);
	}
	public void keyPressed(int keyCode){
		int gameAction=this.getGameAction(keyCode);
		//保存状态:direction 0:上  1:下  2:左  3:右
		int direction=-1;
		switch(gameAction){
		case UP:
		    y-=10;
		    if(y<0)
		    	y=0;
		    direction=0;
		    break;
		case DOWN:
		    y+=10;
		    if(y+d>getHeight())
		    	y=getHeight()-d;
		    direction=1;
		    break;
		case LEFT:
			x-=10;
			if(x<0)
				x=0;
			direction=2;
			break;
		case RIGHT:
			x+=10;
			if(x+d>getWidth())
				x=getWidth()-d;
			direction=3;
			break;
		}
		//
		if(isCollide()){
			switch(direction){
			case 0:
				y=recty+recth;
				break;
			case 1:
				y=recty-d;
				break;
			case 2:
				x=rectx+rectw;
				break;
			case 3:
				x=rectx-recth;
				break;
			}
		}
		repaint();
	}
	//
	public boolean isCollide(){
		return(x+d>rectx && x<rectx+rectw && y+d>recty && y<recty+recth);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -