Collision check between vectors - moving vectors - HTML, JS, P5

让人想犯罪 __ 提交于 2020-12-26 18:45:34

问题


I have created the collision check function for my player to every time when the object (in this case vector - circle) touches the player (also a vector - circle) the game is over.

I have managed to create a logic and there is a collision check working, however it's not calculating the actual distance between elements (instead of ending game when they actually touch its ending when they are some distance from each other.

Both objects are moving - obstacle is moving x+=6 and the player is following the coursor so the speed varies.

I have tried adjusting distance slightly and I have managed to end the game when the x of obstacle is touch x of the player but could not managed actually to when boarders touch. I attach the code I have below;

    class Player {
    constructor(x, y, r) {
    this.pos = createVector(x, y);
    this.r = r;
    this.vel = createVector(500, 500);
    this.mag = 3;
    this.velLerp = 0.1;
  }

  update() {
    let mouse = createVector(mouseX - width / 2, 
    mouseY - height / 2);
    mouse.setMag(this.mag);
    this.vel.lerp(mouse, this.velLerp);
    this.pos.add(this.vel);

  collisionCheck(obstacle) {
    let d = p5.Vector.dist(this.pos, obstacle.pos);

    if (d < this.r + obstacle.r) {
     console.log("GAME OVER");
     return true;
    }

回答1:


The issue is caused by the fact that the movement of the circles is 3 (this.mag) pixel. You just get the exact point of contact by chance. Most time they are intersecting.
If a collision is detected, change the player's position slightly by an offset of this.r + obstacle.r - d:

collisionCheck(obstacle) {
    let d = p5.Vector.dist(this.pos, obstacle.pos);

    if (d < this.r + obstacle.r) {
        
        let shift = p5.Vector.sub(this.pos, obstacle.pos);    
        shift.setMag(this.r + obstacle.r - d);
        this.pos.add(shift);

        console.log("GAME OVER");
        return true;
    }
}


来源:https://stackoverflow.com/questions/64696584/collision-check-between-vectors-moving-vectors-html-js-p5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!