- Sprite còn hỗ trợ lệnh collidesWith giúp kiểm tra khi sprite[1] trạm vào sprite[2] và đưa ra một thông báo gì đó (thông báo ở đây là do người viết đặt ra) ví dụ khi sprite[1] trạm vào sprite[2] và đưa ra thông báo "Bạn đã thua" chẳng hạn, mọi người xem code sau để hiểu dõ hơn
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class canvasCollides extends Canvas{
int w, h, x=0, y=0, check=0;
Image[] im=new Image[1];
Sprite nv, qv;
public canvasCollides(){
setFullScreenMode(true);
w=getWidth();
h=getHeight();
try{
im[0] = Image.createImage("/mChar.png");
im[1] = Image.createImage("/mBoss.png");
}catch(Exception e){}
nv = new Sprite (im[0], im[0].getWidth(), im[0].getHeight());
qv = new Sprite(im[1], im[1].getWidth(), im[1].getHeight());
}
public void paint(Graphics g){
g.setColor(0);
g.fillRect(0,0,w,h);
// ve nhan vat nen graphics
nv.setPosition(x, y);
nv.setFrame(0);
nv.paint(g);
// ve quai vat nen graphics
qv.setPosition(w/2, h/2);
qv.setFrame(0);
qv.paint(g);
// xu li khi nhan vat tram vao quai vat
if(nv.collidesWidth(qv, true)){
check=1;
}
drawCheck();
repaint();
}
public void drawCheck(){
if(check==1){
g.setColor(0);
g.fillRect(0,0,w,h);
g.setColor(0xF0F0F0);
g.drawString("You lose", w/2, h/2, 1|32);
}
}
protected void keyPressed(int keyCode){
if(keyCode==-1){
y-=4;
}
if(keyCode==-2){
y+=4;
}
if(keyCode==-3){
x+=4;
}
if(keyCode==-4){
x-=4;
}
}
}
- Chúc bạn thành công!