碰撞检测算法问题 [英] collision detection algorithm issue

查看:113
本文介绍了碰撞检测算法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前正在研究的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 :


  1. 你可以看到,当我从一点距离冲出或踢角色时,碰撞检测功能不起作用即使您可以在屏幕上看到用户正在惩罚角色

  2. 如何修复此碰撞检测功能以使其正常工作?

  1. 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
  2. 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

这篇关于碰撞检测算法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆