Lesson 9: Smooth Movement โ Bounds + Float Tracking (Matthes Ch 12 ยง6 pt 2)
Learning Intentions
- Make movement smooth (not stuttering) by tracking the ship's x position as a float.
- stop the ship going off-screen.
Success Criteria
- My ship moves smoothly โ no stutter at low speeds.
- My ship stops at the left and right edges of the screen.
- I can explain why we use self.x = float(self.rect.x).
๐ Do Now โ Error of the Day
Watch this GIF (I'll show on projector) โ two ships side by side, one smooth, one stuttery. The stuttery one has ship_speed = 0.3. Why doesn't it move?
๐ I Do โ Teacher Demo
Live-demo the bug: set ship_speed = 0.3. The rect.x is an integer, so 0.3 added to it truncates to 0 โ ship goes nowhere. FIX: track self.x as a float, sync rect.x = self.x after each move. Then add bounds check.
๐ค We Do โ Build Together
Class adds float tracking + bounds together. Everyone's ship moves smoothly AND stops at screen edges. Test with ship_speed = 0.3, 1.5, 2.5.
๐ You Do โ Your Turn
Tune ship_speed until it feels right. Add bounds on ALL 4 sides if you did Up/Down in L08. Arcade quests cover float tracking + bounds.
- Add self.x = float(self.rect.x) to Ship.__init__
- In Ship.update(): if self.moving_right and self.rect.right < screen_rect.right: self.x += self.settings.ship_speed
- After each move: self.rect.x = self.x (sync rect back to int)
- Test with ship_speed = 0.3 โ should be smooth, not stuttering
๐ฎ Practice Quests โ work through these
Loading practice quests for this lesson...
Three tiers โ pick yours
Support
print self.x + self.rect.x each frame to see the mismatch
Core
implement from scratch
Extension
variable speed with Shift key
Extensions
- Add vertical bounds (if you did Up/Down in L08 extension).
- Make ship_speed a mutable โ pressing Shift doubles it briefly.
๐ Exit Ticket โ Coding Journal
Journal: why does the ship need a float self.x if pygame.Rect only stores integers?
Evidence of Learning
Ship moves smoothly at any speed. Ship cannot leave the screen horizontally.