使用Pyxel开发2D游戏:如何绕原点旋转图像?
Hey there! Great question—rotating sprites in Pyxel does require a bit of extra legwork since pyxel.blt doesn’t support rotation directly out of the box. Let me break down how to implement this step by step.
The Core Idea: Rotation Math
To rotate a sprite around a pivot point (like its center or top-left corner), you’ll use basic trigonometry with a rotation matrix. For any point (rel_x, rel_y) relative to the pivot, rotating it by θ radians gives you a new point:
rotated_x = rel_x * cosθ - rel_y * sinθrotated_y = rel_x * sinθ + rel_y * cosθ
We’ll apply this to every pixel in your sprite to draw it in the rotated position.
Custom Rotated Blit Function
Here’s a reusable function that mimics pyxel.blt but adds rotation support. It calculates each pixel’s rotated position and draws it to the screen:
import math def rotated_blt(screen_x, screen_y, img_bank, u, v, width, height, angle, pivot_x=0, pivot_y=0): # Calculate the pivot's position within the source sprite pivot_u = u + pivot_x pivot_v = v + pivot_y # Iterate over every pixel in the sprite for dy in range(height): for dx in range(width): # Get the pixel's position relative to the pivot rel_x = dx - pivot_x rel_y = dy - pivot_y # Apply rotation matrix (convert angle to radians first if needed) cos_theta = math.cos(angle) sin_theta = math.sin(angle) new_rel_x = rel_x * cos_theta - rel_y * sin_theta new_rel_y = rel_x * sin_theta + rel_y * cos_theta # Calculate final screen position final_x = screen_x + new_rel_x + pivot_x final_y = screen_y + new_rel_y + pivot_y # Get the pixel color from the source image pixel_color = pyxel.image(img_bank).get(u + dx, v + dy) # Draw only non-transparent pixels (assuming color 0 is transparent) if pixel_color != 0: pyxel.pset(int(final_x), int(final_y), pixel_color)
How to Use It
Let’s say you have a 16x16 sprite in image bank 0, starting at (0,0) in the image. To draw it at screen position (100,100) rotated 45 degrees around its center:
# Convert 45 degrees to radians rotation_angle = math.radians(45) # Pivot is the center of the 16x16 sprite rotated_blt(100, 100, 0, 0, 0, 16, 16, rotation_angle, pivot_x=8, pivot_y=8)
Performance Tips
- For small sprites (16x16 or smaller), the above function works perfectly for most small games.
- If you need to rotate sprites frequently (like a spinning player character), pre-render rotated versions of the sprite into unused image banks during initialization. Then you can use regular
pyxel.bltto draw them, which is much faster than calculating pixels in real-time.
内容的提问来源于stack exchange,提问作者F. Leone

