向量之间的碰撞检查-移动向量-HTML,JS,P5 [英] Collision check between vectors - moving vectors - HTML, JS, P5

查看:169
本文介绍了向量之间的碰撞检查-移动向量-HTML,JS,P5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次游戏结束时,我都会为玩家创建碰撞检查功能,直到物体(在这种情况下为矢量-圆圈)碰到玩家(也是矢量-圆圈)时.

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.

两个物体都在移动-障碍物在移动x + = 6,并且玩家跟随游标,因此速度有所变化.

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

我尝试过稍微调整距离,并且当障碍物的x触碰到玩家的x时,我设法结束了比赛,但实际上当寄宿生触碰时,我无法设法结束比赛.我附上下面的代码;

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;
    }

推荐答案

问题是由于圆圈的运动为3(this.mag)像素这一事实引起的.您只是偶然获得确切的联系点.大多数时候它们是相交的.
如果检测到碰撞,请以this.r + obstacle.r - d:

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;
    }
}

这篇关于向量之间的碰撞检查-移动向量-HTML,JS,P5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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