Jump to content

  • Log In with Google      Sign In   
  • Create Account


Trigonometry


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
14 replies to this topic

#1 MiniKong   Members   -  Reputation: 175

Like
1Likes
Like

Posted 13 March 2013 - 01:04 PM

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?

Sponsor:

#2 BeerNutts   Crossbones+   -  Reputation: 2191

Like
2Likes
Like

Posted 13 March 2013 - 01:26 PM

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).


My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#3 EddieV223   Members   -  Reputation: 1265

Like
2Likes
Like

Posted 13 March 2013 - 01:28 PM

http://www.mathsisfun.com/algebra/trigonometry-index.html


If this post or signature was helpful and/or constructive please give rep.

 

// C++ Video tutorials

http://www.youtube.com/watch?v=Wo60USYV9Ik

 

// Easy to learn 2D Game Library c++

SFML2.1 Download http://www.sfml-dev.org/download.php

SFML2.1 Tutorials http://www.sfml-dev.org/tutorials/2.1/

 

// SFML 2 book

http://www.amazon.com/gp/product/1849696845/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1849696845&linkCode=as2&tag=gamer2creator-20

 


#4 MiniKong   Members   -  Reputation: 175

Like
0Likes
Like

Posted 13 March 2013 - 02:44 PM

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

#5 Álvaro   Crossbones+   -  Reputation: 10625

Like
1Likes
Like

Posted 13 March 2013 - 02:56 PM

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);


#6 BeerNutts   Crossbones+   -  Reputation: 2191

Like
1Likes
Like

Posted 13 March 2013 - 02:57 PM

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, 13 March 2013 - 02:58 PM.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#7 MiniKong   Members   -  Reputation: 175

Like
0Likes
Like

Posted 13 March 2013 - 02:59 PM

Oh ok thanks you guys! I doesn't seem as confusing now

#8 MiniKong   Members   -  Reputation: 175

Like
0Likes
Like

Posted 13 March 2013 - 03:20 PM

http://inventwithpython.com/blog/2012/07/18/using-trigonometry-to-animate-bounces-draw-clocks-and-point-cannons-at-a-target/#more-823

I found this online so I'm gonna read through it and play around with what I learn

#9 Álvaro   Crossbones+   -  Reputation: 10625

Like
2Likes
Like

Posted 13 March 2013 - 04:47 PM

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.

#10 Nercury   Crossbones+   -  Reputation: 766

Like
1Likes
Like

Posted 14 March 2013 - 05:29 AM

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, 14 March 2013 - 06:02 AM.


#11 MiniKong   Members   -  Reputation: 175

Like
0Likes
Like

Posted 14 March 2013 - 04:56 PM

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

#12 Nercury   Crossbones+   -  Reputation: 766

Like
1Likes
Like

Posted 14 March 2013 - 05:15 PM

Looks like pymunk tutorial is here:

 

https://code.google.com/p/pymunk/wiki/SlideAndPinJointsExample

 

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



#13 MiniKong   Members   -  Reputation: 175

Like
0Likes
Like

Posted 14 March 2013 - 06:32 PM

Looks like I'm working with vectors then

#14 MiniKong   Members   -  Reputation: 175

Like
0Likes
Like

Posted 14 March 2013 - 08:14 PM

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
space.add(PLAYER_shape)

# 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, 14 March 2013 - 08:43 PM.


#15 MiniKong   Members   -  Reputation: 175

Like
0Likes
Like

Posted 14 March 2013 - 08:15 PM

Looks like pymunk tutorial is here:
 
https://code.google.com/p/pymunk/wiki/SlideAndPinJointsExample

 

thanks!






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS