Trigonometry

This topic is 1773 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I've made a few games now such as pong, frogger, duck hunt and a few other clones but now I'm ready to try and make a top down shooter with a scrolling camera ...unfortunately that requires that the player is able to rotate towards the mouse and for that I've been told I need trigonometry :(
Does anyone here know of any tutorials or anything that can help me? I'm using python and pygame. Is their a way for pygame can easly just rotate the objects towards the mouse?

Share on other sites

I don't know pygame specifics, but you'll have to rotate your player's image to face the mouse, so I assume there's some method to do this on sprites in pygame.

In a top-down action shooter I made in C++, I have this code for setting the player's body towards the mouse:

// Finally, find location of Mouse and point player towards it
cpFloat MouseX = (cpFloat)Input.GetMouseX();
cpFloat MouseY = (cpFloat)Input.GetMouseY();

cpFloat Angle = atan2(MouseY - (cpFloat)(mpApp->GetHeight()/2),
MouseX - (cpFloat)(mpApp->GetWidth()/2));
cpBodySetAngle(mpBody, Angle);


The crux of it comes from the atan2() call, which is arc tangent.  There should be a python function that performs it, and the parameters given to it are the Y and X distances between the mouse and the player.

You can take a look at the whole blog post here to see how I also include firing the bullets (and rotating the bullets to be facing the correct way).

Share on other sites
Thanks but I have no idea how to read c++ so I have no idea what's going on lol

Share on other sites

Here it is again with more of a generic-C-dialect feel:

// Finally, find location of Mouse and point player towards it
MouseX = GetMouseX();
MouseY = GetMouseY();

Angle = atan2(MouseY - WindowHeight / 2, MouseX - WindowWidth / 2);

body.SetAngle(Angle);


Share on other sites

Thanks but I have no idea how to read c++ so I have no idea what's going on lol

It should be obvious what it is doing by looking at the lines:

The 1st 2 lines are getting the X and Y coordinates of the mouse on the screen, storing them in variables MouseX and MouseY

The next line performs the atan2 function using the difference of the location of the mouse and the player on the screen (the player is ALWAYS at the center of the screen, that's why it uses mpApp->GetHeight()/2 and mpApp->GetWidth()/2

Think of it like this

// PlayerX and PlayerY are the x and y coordinates of the player on the screen
Angle = atan2(MouseY - PlayerY, MouseX - PlayerY);

// Take the Angle and apply it to your player's sprite or physical body
PlayerSprite->Rotate(Angle)

Edited by BeerNutts

Share on other sites
Oh ok thanks you guys! I doesn't seem as confusing now

Share on other sites
I can't waste the opportunity to say that many of these things are better implemented using vector algebra than angles. Angles are very intuitive, but code that uses them is often full of special cases that have to be dealt with using if' statements, and they require using expensive calls to trigonometric functions.

Vector math is perhaps less intuitive (only because Math is very poorly taught in high school, if you ask me) but is more elegant and it's easier to get right.

The main idea is to use a vector (a pair or real numbers) to represent a direction. You can think of it as a little arrow, the way most people do. Since big arrows and small arrows all point in the same direction, one usually picks the vector of length 1 to represent the direction. If you do some reading on trigonometry, the conversion from vector (x,y) to angle a is a = atan2(y,x)', and the conversion from angle to vector is (x,y) = (cos(a),sin(a))'. But you really shouldn't need to use angles for pretty much anything.

The only tricky part might be how to represent rotations. You can still represent a rotation of an angle a' by the vector (cos(a),sin(a))'. The formula to apply the rotation to a point is

x' = x * cos(a) - y * sin(a)
y' = x * sin(a) + y * cos(a)

Although I wrote cos(a)' and sin(a)' in the two lines above, remember that you don't need to call any functions, because you are already storing (cos(a),sin(a))' as a vector, instead of computing them from a'. As you see, you just need a few simple arithmetic operators to get everything done.

Share on other sites

I can't waste the opportunity to say that many of these things are better implemented using vector algebra than angles. Angles are very intuitive, but code that uses them is often full of special cases that have to be dealt with using if' statements, and they require using expensive calls to trigonometric functions.

I can't agree more: you may not know, but there is a little need of "school trigonometry" even in 3D, because everything can be done very elegantly using vectors. And all of it works on 2D, you just don't use Z axis.

If you store the locations for object a and b as vectors, you can:

- Get a distance between them by subtracting them and returning distance vector's length: (A-B).length() or (B-A).length()

- Get a direction A must go to to eventually get to B: (B-A).normalize() ("normalizing" always returns vector of length 1)

- Angle between two normalized vectors C and D is acos(C dot D).

And there are math libraries which already have all these operations written for vectors.

So if you need a rotation vector for your object to face your mouse, you would write something like this (assuming object position is in same space as mouse position):

#mousePos = ...
#objectPos = ...
initialLookDirection = Vector2(0, 1) # intitally your object looks "up", if Y axis is "up"
targetLookDirection = (mousePos - objectPos).normalize()
rotationInRadians = acos(initialLookDirection * targetLookDirection) # "*" is "dot" product in pygame Vector2


For pygame, you would use pygame.math.Vector2.

Edited by Nercury

Share on other sites
I found I pygame library called pymunk that's supposed to help out with physics and trig I downloaded it a checked out the examples that came with it, it looks really helpfull but doesnt explain much so I guess I'm gonna look more into pygames vectors

Share on other sites

Looks like pymunk tutorial is here:

However looks like pymunk uses compiled C lib, my knowledge ends here.

Share on other sites
Looks like I'm working with vectors then

Share on other sites
ok i went back to the pymunk site printed out the examples,read through the library and yanked out the highlighters! i figured out how to rotate and walk the little circle around! heres my code (sorry if im not supposed to post code here)

#player move

# I - IMPORT---------------------------------------

import sys

import pygame
from pygame.locals import *
from pygame.color import *

import pymunk
from pymunk.vec2d import Vec2d
from pymunk.pygame_util import draw_space, from_pygame

# D - DISPLAY CONFIGURATION-----------------------------------
width, height = 690,600
screen = pygame.display.set_mode((width,height))
WHITE = (255,255,255)

# E - ENTITIES ----------------------------------
space = pymunk.Space() #space is kinda like pygames surface

# "player"
PLAYER_body = pymunk.Body(pymunk.inf, pymunk.inf)
PLAYER_shape = pymunk.Circle(PLAYER_body, 25)
PLAYER_shape.sensor = True
PLAYER_body.position = 100,100

# A - ACTION (BROKEN INTO ALTER STEPS)---------------------------

# A - ASSIGN VALUES TO KEY VARIABLES------------------------

PLAYER_VELOCITY = 100. *2.

PLAYER_body.position = 100,100

clock = pygame.time.Clock()

def main():
pygame.init()

running = True

# L - SET UP MAIN GAME LOOP--------------------------------
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False

keys = pygame.key.get_pressed()
target_vx = 0

speed = 2.5
if (keys[K_UP]):
PLAYER_body.position += Vec2d(0,1) * speed
if (keys[K_DOWN]):
PLAYER_body.position += Vec2d(0,-1) * speed
if (keys[K_LEFT]):
PLAYER_body.position += Vec2d(-1,0) * speed
if (keys[K_RIGHT]):
PLAYER_body.position += Vec2d(1,0) * speed

if (keys[K_LEFT]):
direction = -1
target_vx -= PLAYER_VELOCITY
if (keys[K_RIGHT]):
direction = 1
target_vx += PLAYER_VELOCITY
if (keys[K_DOWN]):
direction = -3

mouse_position = from_pygame( Vec2d(pygame.mouse.get_pos()), screen )
PLAYER_body.angle = (mouse_position - PLAYER_body.position).angle

# T - TIMER TO SET FRAME RATE-------------------------------
screen.fill(WHITE)
fps = 40
clock.tick(fps)

# E - EVENT HANDLEING--------------------------------------

draw_space(screen, space)

# R - REFRESH DISPLAY---------------------------------------
pygame.display.flip()

if __name__ == '__main__':
sys.exit(main()) Edited by MiniKong

• 10
• 11
• 9
• 16
• 19