liveBook · Manning

Subtraction

As explained in Classic Game Programming on the NES: Make your own retro video game

Subtraction is an arithmetic operation that determines the difference between values by removing one value from another.

Subtraction removes one value from another. On the NES, it supports game tasks such as moving objects upward, alongside addition and bit manipulation. section 4.1 section 4.1.2

The `sbc` instruction subtracts a source value from the current 8-bit value in the A register and leaves the result in A. Set the carry flag first with `sec`; if carry is clear, `sbc` subtracts an additional 1. section 4.1.2

Listing 4.9 Subtracting a value from the A register
sec              #1
sbc <source>

Use `sec` immediately before `sbc` when performing an ordinary subtraction from A. section 4.1.2

A subtraction source can use several addressing forms:

Move a bullet upward

A moving bullet subtracts 4 from its Y position each update. If subtraction goes below zero, its Y position becomes `$FF`, removing it from the screen so it can be fired again. section 7.6

Listing 7.7 Moving the player’s bullet (megablast.s)
.segment "CODE"
 
.proc move_player_bullet
    lda oam + 16            #1
    cmp #$FF                #2
    beq @exit    
        sec
        sbc #4              #3
        sta oam + 16        #4
        bcs @exit
            lda #$FF        #5
            sta oam + 16
  
@exit:
    rts
.endproc

The routine checks whether the bullet is visible, subtracts four from its Y coordinate, and hides it after it passes the top edge. section 7.6

How Classic Game Programming on the NES: Make your own retro video game covers it

How deep it goes
Explains 8-bit `sbc` through carry behavior, A-register results, and immediate, memory, indexed, and indirect addressing forms.
Examples
Demonstrates direct, memory, zero-page, indexed, and indirect subtractions, then moves a player bullet upward by four pixels.
What it assumes
Introduces basic 8-bit subtraction through the A register without stating prior knowledge requirements.
What you can do after
Apply it via NES assembly instructions to subtract values from A and update a bullet position with an off-screen check.
How it connects
Connects subtraction with addition, bit manipulation, the A register, carry flags, memory addressing, and sprite Y positions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Game Programming on the NES: Make your own retro video game. The section links point to the parts of the book it draws on.