@selennida04

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

ブロック崩しの当たり判定について

解決したいこと

ブロック崩しで箱に球の反射後にまた箱にあたり瞬間移動しているように見える。
また反射しないことがある。

ゲームつくり初心者で当たり判定の組み方がわからないのでわかりやすく修正お願いします。

Javascript

export class Boxes{
    constructor(x,y,width,height){
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.isHit = false;
    }
    ball_judge(player_ball){
        if(this.isHit) return false;
        if(
            this.x - player_ball.radius <= player_ball.x && player_ball.x <= this.x + this.width + player_ball.radius &&
            this.y - player_ball.radius <= player_ball.y && player_ball.y <= this.y + this.height + player_ball.radius
        ){
            let reflected = false;
            
            if (player_ball.prevX < this.x - player_ball.radius){
                player_ball.vx = -Math.abs(player_ball.vx);
                player_ball.x = this.x - player_ball.radius;
                reflected = true;
            }else if(player_ball.prevX > this.x +this.width + player_ball.radius){
                player_ball.vx = -Math.abs(player_ball.vx);
                player_ball.x = this.x + this.width + player_ball.radius;
            }

            if(player_ball.prevY < this.y - player_ball.radius){
                player_ball.vy = -Math.abs(player_ball.vy);
                player_ball.y = this.y - player_ball.radius;
                reflected = true;
            }else if(player_ball.prevY > this.y + this.height + player_ball.radius){
                player_ball.vy = -Math.abs(player_ball.vy);
                player_ball.y = this.y + this.height + player_ball.radius;
                reflected = true;
            }
            this.isHit = true;

            player_ball.prevX = player_ball.x;
            player_ball.prevY = player_ball.y;
            return reflected;
        }
        player_ball.prevX = player_ball.x;
        player_ball.prevY = player_ball.y;
        return false;

    }
    show(){
        if (this.isHit) return;
        ctx.fillStyle = "blue";
        ctx.fillRect(this.x,this.y,this.width,this.height);
    }
}

引数

インスタンスplayer_ballの引数には、x,y,radius,prevX,prevY,があり、
xは球のx座標
yは球のy座標
radiusは球の半径
prevXは球の一つ前のx座標
prevYは球の一つ前のy座標

0 likes

2Answer

html等も含めてコードは抜粋せずに すべて載せた方がいいと思います。

1Like

明確な答えは、コードを全て読んで、ball.vxなどの意味もエスパーしなければいけないので、自分でやってみるのがいいと思います。
まず、4つANDをしているところで、比較がわかりづらいと思いました。積極的にグループ化演算子 () を使ってみてください。バグが出やすい箇所です。
もう一つ、 player_ball.vx = -Math.abs(player_ball.vx) について、疑問に思いました。vxはx軸方向の速度だと推測しますが、絶対値をつけず単に - をつけるのが正しいのではと思いました。
バグには直接関係ないと思いますが、ballをboxで制御しているのもあまり良くない気がします。box以外の障害物(実装しないにしても)に衝突したときと挙動を共通にするため、その制御は ball.bouce() などの関数を定義して移動させるのが良いかもしれません。

1Like

Your answer might help someone💌