如何进行碰撞预防?(重置玩家对象的位置)

How to do collision prevention? (Resetting position of player object)

本文关键字:玩家 对象 位置 碰撞 何进行      更新时间:2023-09-26

我遇到了一些严重的问题,无法阻止我的玩家在画布上复制与我的其他对象相同的位置。

以下代码是我的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.
    }
}

问题是您没有复制位置数据。您只是在创建对对象位置的新引用。

在javascript中,对象和数组通过它们的引用进行访问。把它想象成一个指向内存位置的指针。

如果你有一个对象

var myObject = {
      str: "aaaa",
      num: 100,
}

然后复制

var myObject2 = myObject;

它们都指向相同的结构。因此,如果我将值更改为一,它将同时显示在两个值中。

myObject.num = 200;
console.log(myObject.num); // 200 is displayed
console.log(myObject2.num); // 200 is displayed

阵列也是如此

var myArr = [0,1,2,3,4,5];
var myArrRef = mayArr;
myArr[1] = 10;
console.log(myArrRef[1]); // as they are the same array the output is 10;

只有基元类型在将其指定给另一个变量时才创建副本。

var str = "Blah blah"
var str1 = str;   // there are now two copies of "blah blah"
str1 += " blah";
console.log(str);  "Blah blah"
console.log(str1);  "Blah blah blah"

数字、布尔值和正则表达式也是如此。

因此,如果你想复制一个对象,你必须显式地复制所有的基元类型。

var position = {
    x: 0,
    y: 0,
}
var oldPos = {
     x:position.x,
     y:position.y,
    // and any other relevant info
}

进行碰撞测试

if(collision){
     position.x = oldPos.x;
     position.y = oldPos.y;
    // and any other relevant info
}

希望这能有所帮助。