Skip to content

Better ball velocity in Ball.lua class #80

@Rye-Catcher

Description

@Rye-Catcher

In pong-5/Ball,lua, the ball velocity along the x-axis and y-axis is not so good compared to pong-4. The ball will either has -100 or 100 velocity along y-axis but will have a random velocity from -50 to 50 along x-axis. As a result, the ball movement is unnatural and does not look like random (we have longer x distance and less y distance. It will be more natural if the x-axis velocity is a fixed big number and y-axis velocity is a random relatively small number). This issue affects all programs with the Ball.lua class. Namely, from pong-5 to pong-12. The issue will be more obvious with the interaction with paddles since the ball x-axis velocity can be captured as drastically being faster or slower after colliding with the paddle (again, the reason is that we have a long x distance).

function Ball:reset()
    self.x = VIRTUAL_WIDTH / 2 - 2
    self.y = VIRTUAL_HEIGHT / 2 - 2
    self.dy = math.random(2) == 1 and -100 or 100
    self.dx = math.random(-50, 50)
end

However, in pong-4/main.lua, it will look like the ball is having a natural and random movement.

function love.keypressed(key)
    -- keys can be accessed by string name
    if key == 'escape' then
        -- function LÖVE gives us to terminate application
        love.event.quit()
    -- if we press enter during the start state of the game, we'll go into play mode
    -- during play mode, the ball will move in a random direction
    elseif key == 'enter' or key == 'return' then
        if gameState == 'start' then
            gameState = 'play'
        else
            gameState = 'start'
            
            -- start ball's position in the middle of the screen
            ballX = VIRTUAL_WIDTH / 2 - 2
            ballY = VIRTUAL_HEIGHT / 2 - 2

            -- given ball's x and y velocity a random starting value
            -- the and/or pattern here is Lua's way of accomplishing a ternary operation
            -- in other programming languages like C
            ballDX = math.random(2) == 1 and 100 or -100
            ballDY = math.random(-50, 50) * 1.5
        end
    end
end

In summary, the dx and dy velocity of ball in all Ball.lua class should be swapped.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions