JavaScript 2D冲突异常
JavaScript 2D collision anomaly
我正在试用JavaScript中的HTML5画布脚本,但在2D碰撞检测方面遇到了问题。我基本上是在检查"玩家"的坐标和我放在屏幕上的盒子的坐标,但出现了一个奇怪的结果。我知道为什么会发生这种事,但我不知道如何解决这个问题。
我的一些代码:
function Arc()
{
// Coordinates.
this.x = 540 / 2;
this.y = 0;
// Radius
this.r = 50;
// Gravity / velicoty.
this.g = 3;
this.vy = 15;
// Bounce.
this.b = -0;
this.speed = 20;
this.max_speed = 20;
this.friction = 0.03444;
}
Arc.prototype.collision = function()
{
for(var i = 0; i < game.sprites.length; i++)
{
if
(
// If the right side of the player is greater than the left side of the object.
this.x + this.r > game.sprites[i].x &&
// If the bottom of the player is greater than (meaning lower than) the top of the object.
this.y + this.r > game.sprites[i].y &&
// If the left side of the player is greater than the right side of the object.
this.x - this.r < game.sprites[i].x + game.sprites[i].w &&
// if the top of the player is greater than (meaning lower than) the bottom of the object.
this.y - this.r < game.sprites[i].y + game.sprites[i].h
)
{
this.y = game.sprites[i].y - this.r;
this.vy *= this.b;
}
}
}
异常情况是,当我将玩家精灵移动到框的左侧或右侧时,它会在Y轴上向上跳跃,因为上面的逻辑检查总是正确的。显然,这是出乎意料的,因为精灵应该只在发生跳跃时与框的顶部交互。
注意:我不是在寻找一个只在长方体两侧添加碰撞的解决方案(这很简单)。相反,我正在寻找一种解决方案,允许以目前的工作方式在盒子的所有侧面(包括顶部)发生碰撞,但不会出现精灵在触摸盒子时突然跳到盒子顶部的异常情况。
我在JSFiddle上复制了我的整个项目,用于演示(键a、d和空格键):http://jsfiddle.net/h5Fun/
无论这是否是您想要的,它都解决了问题:
this.x = game.sprites[i].x + 150;
this.vx *= this.b;
问题是您在碰撞时设置了不正确的组件。如果希望圆在碰到矩形时停止,而不是在其顶部,请使用x
,而不是y
。
150
是矩形的大小。这意味着它将停止在精灵的右侧。由于修改了速度(this.vx
),反弹已经存在。
相关文章:
- Javascript-ID冲突的几率
- 在javaservlet doPost方法中启动线程时,无法返回异常消息
- document.applet.method在Mounatin Lion上抛出safari 6+JDK7异常
- 导致内容安全策略(CSP)冲突错误的本地jquery.js文件
- 为什么浏览器没有为语法错误抛出异常
- java,javascript签名的小程序(文件选择,ftp上传)安全性/套接字异常
- node.js和express中的异常处理
- 派生进程的stdout在管道传输时工作异常
- NodeJS和pg promise,捕获PostgreSQL异常
- 当显式定义控制器参数时,默认模型绑定器会发生异常
- 显示引导弹出操作异常的逻辑
- 调用谷歌地图路线服务时未捕获的异常
- web配置http到https重定向异常
- 转换异常时间&Datestring到JavaScript日期
- 为什么在python中使用异常比javascript更容易接受
- PHP REST服务抛出异常——希望避免控制台错误
- JS异常:animate不是一个函数
- Pg承诺性能提升:在冲突中
- 在蓝鸟中处理异常
- JavaScript 2D冲突异常