Skip to content

2D Rotation Algorithm and Example Code. 🇰🇷 2차원 회전 알고리즘과 예제 코드

License

Notifications You must be signed in to change notification settings

JayTwoLab/rotating-2d

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rotating-2d : 2D Rotation Algorithm and Example Code

English , Korean

Rotation Formula

  • Original coordinates: (x, y)
  • Rotated coordinates: (x', y')
  • Pivot point: (cx, cy)
  • Rotation angle: θ (in radians)

Rotated Coordinates

x' = cos(θ) * (x - cx) - sin(θ) * (y - cy) + cx
y' = sin(θ) * (x - cx) + cos(θ) * (y - cy) + cy

Example Code

import math
import matplotlib.pyplot as plt

def rotate_point(x, y, cx, cy, angle):
    """Rotate point (x, y) around pivot (cx, cy) by a given angle"""
    radians = math.radians(angle)
    cos_theta = math.cos(radians)
    sin_theta = math.sin(radians)
    x_new = cos_theta * (x - cx) - sin_theta * (y - cy) + cx
    y_new = sin_theta * (x - cx) + cos_theta * (y - cy) + cy
    return x_new, y_new

def rotate_rectangle(rect, cx, cy, angle):
    """Rotate all points of a rectangle"""
    return [rotate_point(x, y, cx, cy, angle) for x, y in rect]

# Initial rectangle coordinates (starting from top-left, clockwise)
rectangle = [(1, 3), (4, 3), (4, 1), (1, 1)]
center = (2.5, 2)  # Pivot point
angle = 45  # Rotation angle (degrees)

# Rotate the rectangle
rotated_rectangle = rotate_rectangle(rectangle, *center, angle)

# Visualization
def plot_rectangle(rect, label, color):
    x, y = zip(*rect + [rect[0]])  # Close the rectangle by adding the first point again
    plt.plot(x, y, marker='o', label=label, color=color)

plt.figure()
plot_rectangle(rectangle, 'Original', 'blue')
plot_rectangle(rotated_rectangle, 'Rotated', 'red')

plt.scatter(*center, color='green', label='Center', zorder=5)
plt.legend()
plt.gca().set_aspect('equal', adjustable='box')
plt.grid(True)
plt.title(f"Rectangle Rotation (Angle: {angle}°)")
plt.show()

Code Explanation

  1. rotate_point function: Rotates a given point around a specified pivot point.
  2. rotate_rectangle function: Rotates all four corners of a rectangle.
  3. Matplotlib Visualization: Plots the original rectangle (blue) and the rotated rectangle (red).
  4. Pivot Point: Shown as a green dot. The rotation angle is measured counterclockwise starting from 0 degrees.

Notes

  • To rotate counterclockwise, use a positive angle.
  • To rotate clockwise, use a negative angle or modify the rotate_point function to handle negative angles directly.

Execution Result

The rotated rectangle, rotated by 45 degrees, is visualized alongside the original rectangle to demonstrate the transformation.

About

2D Rotation Algorithm and Example Code. 🇰🇷 2차원 회전 알고리즘과 예제 코드

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages