基于终点旋转 [英] Rotation based on end points

查看:113
本文介绍了基于终点旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pygame在两个任意点之间绘制一条线。我还希望在线条行进方向上朝外的线条末尾添加箭头。

在最后贴上箭头图像很简单,但我不知道如何计算旋转角度以保持箭头指向正确的方向。 / p>

解决方案

这是完成它的代码。请注意,在使用pygame时,y坐标是从顶部开始测量的,所以我们在使用数学函数时采用负数。

  import pygame 
import math
import random
pygame.init()
$ b $ screen = pygame.display.set_mode((300,300))
screen .fill((255,255,255))

pos1 = random.randrange(300),random.randrange(300)
pos2 = random.randrange(300),random.randrange(300)

pygame.draw.line(screen,(0,0,0),pos1,pos2)

arrow = pygame.Surface((50,50))
arrow.fill((255,255,255))
pygame.draw.line(arrow,(0,0,0),(0,0),(25,25))
pygame.draw.line (箭头,(0,0,0),(0,50),(25,25))
arrow.set_colorkey((255,255,255))

angle = math.atan2( - (pos1 [1] -pos2 [1]),pos1 [0] -pos2 [0])
##请注意,在pygame中y = 0表示屏幕的顶部
##所以它是在使用数学时反转y坐标是必要的
angle = math.degrees(angle)

def drawAng(angle,pos):
nar = pygame.transform.rot ate(arrow,angle)
nrect = nar.get_rect(center = pos)
screen.blit(nar,nrect)

drawAng(angle,pos1)
角度+ = 180
drawAng(angle,pos2)
pygame.display.flip()


I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling.

It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing in the right direction.

解决方案

Here is the complete code to do it. Note that when using pygame, the y co-ordinate is measured from the top, and so we take the negative when using math functions.

import pygame
import math
import random
pygame.init()

screen=pygame.display.set_mode((300,300))
screen.fill((255,255,255))

pos1=random.randrange(300), random.randrange(300)
pos2=random.randrange(300), random.randrange(300)

pygame.draw.line(screen, (0,0,0), pos1, pos2)

arrow=pygame.Surface((50,50))
arrow.fill((255,255,255))
pygame.draw.line(arrow, (0,0,0), (0,0), (25,25))
pygame.draw.line(arrow, (0,0,0), (0,50), (25,25))
arrow.set_colorkey((255,255,255))

angle=math.atan2(-(pos1[1]-pos2[1]), pos1[0]-pos2[0])
##Note that in pygame y=0 represents the top of the screen
##So it is necessary to invert the y coordinate when using math
angle=math.degrees(angle)

def drawAng(angle, pos):
    nar=pygame.transform.rotate(arrow,angle)
    nrect=nar.get_rect(center=pos)
    screen.blit(nar, nrect)

drawAng(angle, pos1)
angle+=180
drawAng(angle, pos2)
pygame.display.flip()

这篇关于基于终点旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆