碰撞检测算法问题
问题描述:
这是我目前正在研究的jsfiddle: http://jsfiddle.net/TLYZS/
here is the jsfiddle i am working on so far : http://jsfiddle.net/TLYZS/
如果您调试代码并检查碰撞功能,当用户与格斗游戏中的其他角色愿望重叠时,您可以看到碰撞正常不应该这样工作:
if you debug the code and check the collision function you can see that the collision is working fine when the user overlap with the other character wish in a fighting game the collision should not work like this :
- 你可以看到,当我从一点距离冲出或踢角色时,碰撞检测功能不起作用即使您可以在屏幕上看到用户正在惩罚角色
-
如何修复此碰撞检测功能以使其正常工作?
- you can see that when i punch or kick the character from a little distance the collision detection function does not work even if you can see it on the screen that the user is punishing the character
how can i fix this collision detection function to make it work fine ?
function Collision(r1, r2) {
return !(r1.x > r2.x + r2.w || r1.x + r1.w < r2.x || r1.y > r2.y + r2.h || r1.y + r1.h < r2.y);
}
答
这是我的老JS实现flash.geom.Rectangle。尝试在你的项目中使用它:
Here is my old JS implementation of flash.geom.Rectangle. Try to use it in your project:
function Rectangle(x, y, w, h) { // constructor
if(x==null) x=y=w=h=0;
this.x = x; this.y = y;
this.width = w; this.height = h;
}
Rectangle.prototype.isEmpty = function() { // : Boolean
return (this.width<=0 || this.height <= 0);
}
Rectangle.prototype.intersection = function(rec) { // : Rectangle
var l = Math.max(this.x, rec.x);
var r = Math.min(this.x+this.width , rec.x+rec.width );
var u = Math.max(this.y, rec.y);
var d = Math.min(this.y+this.height, rec.y+rec.height);
if(r<l || d<u) return new Rectangle();
else return new Rectangle(l, u, r-l, d-u);
}
然后你只需致电
var r1 = new Rectangle( 0, 0,100,100);
var r2 = new Rectangle(90,90,100,100);
// r1.intersection(r2) would be Rectangle(90,90,10,10)
if( !r1.intersection(r2).isEmpty() ) ... // there is a collision