我在防止我的玩家在画布上占据与其他对象相同的位置时遇到了一些严重的麻烦。如何防止碰撞? (重置玩家对象的位置)
下面的代码是我的player.update方法,就我的逻辑而言,它应该阻止它,尽管在玩家和障碍之间留下了一个可能的缺陷,但那不是我现在关心的问题。
我测试过碰撞被检测到,所以我做错了什么?
update() {
var oldPosition = this.position; //Save the old player position.
this.accelerate(); //Accelerate the player through playerinput.
this.decelerate(); //Modify velocity to friction and gravity
this.position.addTo(this.velocity); //Move the player according to velocity.
for (var i = 0; i < this.cElements.length; i++) { //Run through all the elements on the canvas.
if (this.cElements[i] != this) { //Exclude the player itself.
if (this.collisionDetector.cElementsIntersect(this, this.cElements[i])) { //If there is collision
collision = true;
}
}
}
if (collision) {
this.position = oldPosition; //Reset the position.
}
}
Mozilla有一个很好的碰撞文章,它可以帮助你,也可以帮助你 - https://developer.mozilla.org/zh-CN/docs/Games/Techniques/2D_collision_detection – TrojanMorse
@Torean Thanks for该链接,但它不是真正的检测我遇到的问题,它阻止了玩家将它的位置转移到发生碰撞的位置。 –
您并未创建旧位置的副本。 'oldPosition = position'只是将引用(指向对象中的数据)复制到'position',因此当你执行'position = oldPosition'时,不会发生任何事情,因为它们都是同一个对象。您需要将位置的细节复制到新的对象中。 'var oldPos = {x:position.x,y:position.y ... etc',然后当你复制数据时做同样的事情,因为你需要恢复到原来的位置 – Blindman67