![](/img/trans.png)
[英]Collision Detection using algorithm and Rectangle.intersects (java/lwjgl)
[英]Collision detection, rectangle intersects at corner
我正在嘗試學習碰撞檢測在android中的工作原理,並且是使用Android矩形實現的。
我需要能夠檢測到第二個矩形的頂部,左側和底部壁的碰撞,但是問題是第一個矩形能夠通過左上角直接進入第二個矩形。
下面是我正在使用的代碼的片段:
GameView2類的摘錄:
private Shape s1 = new Shape(this, Color.BLACK, 0, 100, 50, 50);
private Shape s2 = new Shape(this, Color.BLUE, 200, 100, 50, 50);
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
this.drawBackground(canvas);
s1.onDraw(canvas);
s2.onDraw(canvas);
s1.x+=s1.vx;
s1.y+=s1.vy;
//left wall collision
if(s1.x+s1.width==s2.x && s1.y+s1.height > s2.y && s1.y < s2.y + s2.height){
s1.vx = 0;
}
//top wall
else if(s1.y+s1.height==s2.y && s1.x+s1.width > s2.x && s1.x < s2.x+s2.width){
s1.vy = 0;
}
else{
s1.vx = 2;
}
}
形狀等級:
public class Shape{
protected GameView2 game_view;
protected int x;
protected int y;
protected int vx;
protected int vy;
protected int width;
protected int height;
protected int color;
public Shape(GameView2 game_view, int color, int x, int y, int width, int height) {
this.game_view = game_view;
this.x = x;
this.y = y;
this.vx = 2;
this.vy = 0;
this.width = width;
this.height = height;
this.color = color;
}
public Rect getRect(){
return new Rect(x, y, x + width, y + height);
}
public void onDraw(Canvas canvas){
Paint paint = new Paint();
Rect rec = new Rect(x, y, x + width, y + height);
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(rec, paint);
}
}
這是一個非常簡單的算法,用於兩個矩形之間的碰撞。
x1 + width1 <x2 || x2 + width2 <x1 || y1 + height1 <y2 || y2 + height2
如果以上陳述為真,則不會發生沖突。 否則,兩個矩形相互碰撞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.