0

So I'm making a game and I've got some help from another post to make bullets fly towards the mouse cursor. The original person who showed me this did explain it to me and I have a rough idea what it does but I didn't quite understand it. So I'm posting here for further explanation.

    def Shoot(self):
        pos = self.rect.centerx, self.rect.centery
        mpos = py.mouse.get_pos()
        direction = py.math.Vector2(mpos[0] - pos[0], mpos[1] - pos[1])
        direction.scale_to_length(10)
        return Bullet(pos[0], pos[1], round(direction[0]), round(direction[1]))

Edit: well I know what it does I just don't how I do it. I know It allows for projectiles to a fly towards the mouse even on diagonals but I don't know how it does it.

2 Answers2

1

Whats happening is your getting the position of the cube/player with pos.

mpos is the mouse position on the screen

direction gets the direction between the player and the mouse. for example it the direction could be 10 pixels down and 100 pixels to the right.

pic of maths

The next line scales the direction down to 10, so instead of moving 100 pixels right and 10 down, its close to about 1 down and 10 right (not exactly but pretty close)

The last line creates the bullet with the x position, y position, x speed, y speed. rounding the speed as i said above, its not exactly 1 down and 10 right, it will be some decimal so to make it a nice number, you round it

The Big Kahuna
  • 2,097
  • 1
  • 6
  • 19
  • Oh ok, thanks. I'm weird I don't like to add code I don't fully understand it feels like I'm cheating or something idk. Anyway thanks for the explanation :) – Sir Braindmage May 08 '20 at 02:35
  • @TheBigKanuna hahaha hahaha. I might try AI later down the line when I'm better at coding :P – Sir Braindmage May 08 '20 at 02:44
0

I've tried to explain that in the answer to your previous question (Im currently making a game with pygame and Ive run into an Issue.), but I'll try it again.

The instruction

direction = py.math.Vector2(mpos[0] - pos[0], mpos[1] - pos[1])

Computes the distance from the point pos (A) to the point mpos (B) along the x-axis and y-axis. Such a tuple of axis aligned distances is called Vector:

At this point the Euclidean distance from point A to point B is unknown.

In the following the vector is scaled to a length of 10, by the operation pygame.math.Vector2.scale_to_length:

direction.scale_to_length(10)

That means that the x and y component of the vector is changed in that way (xd, yd), that the Euclidean length of the vector is 10 (d = 10):

If the components of the vector are added to the components of the point A, once per frame, then the point A steps towards the point B (A1, A2, ...):

Rabbid76
  • 202,892
  • 27
  • 131
  • 174