Pong: How does the paddle know where the ball will hit?

后端 未结 7 2061
旧巷少年郎
旧巷少年郎 2021-02-05 04:16

After implementing Pacman and Snake I\'m implementing the next very very classic game: Pong.

The implementation is really simple, but I just have one little problem rema

7条回答
  •  梦毁少年i
    2021-02-05 05:13

    It just so happens I wrote a pong clone the other day just for fun.

    You can play it here and view the source code here.

    The AI takes the ball's current speed and multiplies the x-distance away from the wall. It then moves towards that calculated position at a capped speed. It doesn't account for vertical bounces, but that's sort of intended (to make the AI beatable).

    Here is the relevant snippet:

    /* Update enemy based on simple AI */
    enemy.update = function (delta) {
        var impactDistance, impactTime, targetY, speed;
        speed = .25; // a little slower than the human player
    
        if (ball.vx < 0) {
            // Ball is moving away, AI takes a nap ..
            return;
        }
    
        // Figure out linear trajectory ..
        impactDistance = width - ball.width - ball.x;
        impactTime = impactDistance / (ball.vx * .25 * 1000);
        targetY = ball.y + (ball.vy * .25 * 1000) * impactTime;
    
        if (Math.abs(targetY - (this.y + this.height/2)) < 10) {
            // AI doesn't need to move
            return;
        }
    
        if (targetY < this.y + (this.height / 2)) {
            // Move up if ball is going above paddle
            speed = -speed;
        }
    
        this.y += speed * delta;
        this.keepInBounds();
    };
    

提交回复
热议问题