The Concept of Velocity and Gravity

To make a sprite move realistically (fall, jump), we need two new variables in our sprite data structure:

  1. Velocity (DY): The current speed and direction of the sprite on the Y-axis.
  2. Gravity: A constant value that is continually added to the velocity every frame, causing the sprite to accelerate downward.

The Calculation: The physics update is done by:

  1. Velocity ← Velocity + Gravity
  2. Y-Coordinate ← Y-Coordinate + Velocity

Updating Velocity with Gravity

We will need a new field in our sprite descriptor (e.g., offset +A for an 8-bit velocity) and a constant for gravity.

Example: Applying Gravity (8-bit)

SPRITE_DY_ADDR EQU +A         ; 8-bit Y-Velocity at offset A
GRAVITY_CONST  EQU 01H        ; Gravity force (1 pixel/frame)

APPLY_GRAVITY:
    LD   IX, SPRITE_ADDR      ; IX points to the sprite control block
    LD   A, (IX + SPRITE_DY_ADDR) ; A ← Current DY
    
    ADD  A, GRAVITY_CONST     ; A ← DY + 1 (A now holds new DY)
    LD   (IX + SPRITE_DY_ADDR), A ; Store new DY back to memory
    RET

Updating Position with Velocity

Once the velocity is updated, we add the velocity value to the sprite’s actual Y-coordinate. Since the Y-coordinate can be large (16-bit), we must use the ADC (Add with Carry) routine from Part 8.

Example: Y-Position Update (Simplified)

SPRITE_Y_LOW  EQU +2          ; Y-Coordinate Low Byte
SPRITE_Y_HIGH EQU +3          ; Y-Coordinate High Byte

UPDATE_Y_POS:
    CALL APPLY_GRAVITY        ; Apply gravity first (A holds the new DY)
    
    ; Add DY (A) to the Y-Coordinate (HL pair is used for Y address)
    LD   HL, (SPRITE_Y_LOW)   ; HL ← Current Y-Coordinate
    
    ; Add the 8-bit velocity (A) to the 16-bit Y-coordinate (complex math required)
    
    ; ... (Code performs 16-bit addition)

    LD   (SPRITE_Y_LOW), L    ; Store new Y low byte
    LD   (SPRITE_Y_HIGH), H   ; Store new Y high byte
    RET

Jumping Implementation

Jumping is simply a sudden, large negative velocity applied to the Y-axis when the jump key is pressed and the sprite is on the ground.

Jump Logic:

  1. Check if the jump key is pressed and the sprite status is ‘ON_GROUND’.
  2. If true, load the velocity field with a large negative number (e.g., LD A, -10 or LD A, 0F6H in two’s complement).
  3. Gravity will then take over, gradually reducing the negative velocity (upward movement) until it becomes positive (downward movement), simulating the arc.