Could somebody please breakdown how this code works?
Hello. I have started to learn game maker this past week and have been doing OK. This is also my first introduction to programming.
I was trying to get a bullet to spawn at the tip of a gun, and on my own I had it very close to working but just couldn't get it right.
I found this document online which gave a perfect solution to my problem. Here's a link: https://docs.google.com/document/edit?id=19O-gB9K6T5-UI4ot4cGCoICfPzETzefUkS-8zga20q0&hl=en_GB
"Case 3" is the solution I was after.
Len = point_distance(0, 0, DX, DY);
Angle = point_direction(0, 0, DX, DY);
bullet_id = instance_create(x + lengthdir_x(Len, Angle+image_angle), y + lengthdir_y(Len, Angle+image_angle), obj_bullet);
So, I understand why and how to obtain DX and DY (see link). I understand why I want to add the lengthdir_x&y to x&y. But I'm confused on how point_distance and point_direction work in this context. And why I want to add the point_direction to image_angle.
A explanation of the code here would be very helpful as I plan to do similar things in the future and really don't want to be using code I don't understand.
Thank you! :)
Posted Apr 30, 2017, 7:09 AM UTC
Certainly! So you say that you understand why we use lengthdir_x and lengthdir_y. These functions are used to convert a vector (a direction and magnitude) into it's horizontal and vertical components.
We use a vector to place the bullet because it can rotate perfectly and does not become distorted. But how do we get this vector? Using point_distance and point_direction.
point_distance gives us the magnitude, or length, of the vector. point_direction gives us the direction of the vector. Thus, Len is how far away the bullet spawns from the center of the player. Angle is the amount of offset from the direction of the player the bullet will spawn.
Consider this graphic to help. The black circle is the player, and the red one is the bullet. The blue line is the distance from the player to the spawn point of the bullet, or Len. The purple line going directly to the right is the direction of the player, and the purple angle is the offset from the player's direction and the direction to the bullet, or Angle. As the player rotates, the vector that points to the bullet rotates too, perfectly. This kind of rotation is not possible with normal horizontal and vertical lengths.