Very cool! I might use this sometime :) On Wed, Mar 12, 2008 at 8:06 PM, Kris Schnee <[EMAIL PROTECTED]> wrote:
> Just thought I'd offer this function, which might be useful for > characters with following behavior. It finds the angle from one point to > another, in degrees, with 0 being "up" and 90 being "right." It's > therefore useful for deciding whether a target is to a character's right > etc., and it's easily changed if you don't like the scale I used. > > ------ > > import math > def AngleToTarget(dx,dy): > """Returns the angle to a point (dx,xy) in degrees. > > 0==up/north, 90==right/east, 180==down/south, 270==left/west. > """ > if dx == 0: ## Special case to prevent zero-division > if dy > 0: > return 180 > elif dy < 0: > return 0 > else: > return None > > oa = float(dy)/float(dx) > theta = math.degrees(math.atan(oa)) + 90.0 > > if dx > 0: > return theta > else: > return 180+theta > > return theta > > > ## Demonstrate the function graphically: show angle from a "sun" to your > cursor. > import pygame > pygame.init() > from pygame.locals import * > s = pygame.display.set_mode((500,500)) > font = pygame.font.Font(None,36) > done = False > while not done: > for event in pygame.event.get(): > if event.type == KEYDOWN: > done = True > > x, y = pygame.mouse.get_pos() > dx, dy = x-250, y-250 > theta = AngleToTarget(dx,dy) > s.fill((0,0,0)) > pygame.draw.circle(s,(255,255,64),(250,250),10) > t = font.render(str(int(theta)),1,(255,255,255)) > pygame.draw.line(s,(128,128,128),(250,250),(x,y)) > s.blit(t,(0,0)) > pygame.display.update() > > -- - pymike (pymike.blogspot.com)
