https://github.com/jaytwolab/rotating-2d
2D Rotation Algorithm and Example Code. :kr: 2차원 회전 알고리즘과 예제 코드
https://github.com/jaytwolab/rotating-2d
Last synced: 10 months ago
JSON representation
2D Rotation Algorithm and Example Code. :kr: 2차원 회전 알고리즘과 예제 코드
- Host: GitHub
- URL: https://github.com/jaytwolab/rotating-2d
- Owner: JayTwoLab
- License: mit
- Created: 2025-01-07T00:32:10.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-01-07T01:07:10.000Z (about 1 year ago)
- Last Synced: 2025-03-28T03:07:34.290Z (10 months ago)
- Language: Python
- Homepage:
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.ko.md
- License: LICENSE
Awesome Lists containing this project
README
# rotating-2d : 2차원(2D) 회전 알고리즘과 예제 코드
> [English](README.md) , [Korean](README.ko.md)
## 회전 공식
- **회전 전 좌표**: (x, y)
- **회전 후 좌표**: (x', y')
- **회전 중심점**: (cx, cy)
- **회전 각도**: θ (라디안 단위)
### 회전 후 좌표 계산
```
x' = cos(θ) * (x - cx) - sin(θ) * (y - cy) + cx
y' = sin(θ) * (x - cx) + cos(θ) * (y - cy) + cy
```
---
## 예제 코드
```python
import math
import matplotlib.pyplot as plt
def rotate_point(x, y, cx, cy, angle):
"""점 (x, y)를 중심점 (cx, cy)를 기준으로 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):
"""사각형의 모든 점을 회전"""
return [rotate_point(x, y, cx, cy, angle) for x, y in rect]
# 사각형 초기 좌표 (시작점: 좌상단, 시계 방향)
rectangle = [(1, 3), (4, 3), (4, 1), (1, 1)]
center = (2.5, 2) # 회전 중심
angle = 45 # 회전 각도 (도)
# 사각형 회전
rotated_rectangle = rotate_rectangle(rectangle, *center, angle)
# 시각화
def plot_rectangle(rect, label, color):
x, y = zip(*rect + [rect[0]]) # 사각형 닫기 위해 첫 점 추가
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()
```
---
## 코드 설명
1. **`rotate_point` 함수**: 주어진 점을 중심점 기준으로 회전시킵니다.
2. **`rotate_rectangle` 함수**: 사각형의 네 꼭짓점을 모두 회전시킵니다.
3. **Matplotlib 시각화**: 원래 사각형(파란색)과 회전된 사각형(빨간색)을 그립니다.
4. **회전 중심점**: 초록색 점으로 표시됩니다. 위 코드에서 회전 각도의 기준은 0도이며, 반시계 방향으로 회전합니다.
### 참고 사항
- 반시계 방향으로 회전하려면 각도를 양수로 설정합니다.
- 시계 방향으로 회전하려면 각도를 음수로 설정하거나, `rotate_point` 함수에서 음수 각도를 사용합니다.
---
### 실행 결과
45도 회전된 사각형이 원래 사각형과 함께 그려지며, 회전 변환이 시각적으로 확인됩니다.