Home > Software design >  C shooting towards the cursor from points that move around the player
C shooting towards the cursor from points that move around the player

Time:01-14

I'm learning video game design in Kingston University, London, and I'm having an issue with my 2D project. My player character in the project is a sword, that fires smaller daggers towards the cursor, but they appear from the left and right sides of the player character alternating. I want these daggers to always shoot towards the cursor, and appear at the left and right of the player character, no matter its rotation or where the cursor is aiming.

my current code is basically (oversimplified as I don't have it with me).

Dagger = Sword.GetX() 20

so it takes the player's X coords, adds or subtracts from them, and places a dagger that fires towards the cursor. This presents the issue of them always spawning in the same place, no matter where I am aiming. I want them to dynamically fire from either side of the player character no matter where I aim.

I thought of drawing a line perpendicular to the player character/looking angle and placing the dagger spawns along that, but I'm inept at maths and have no idea of how to do this.

Also sorry if the code baffles you, we are using a custom made game engine called GFC, made by Kingston University.

CodePudding user response:

enter image description here

So you know the coordinates of points A and B and you want to calculate C. With the kind of math you don't know yet but will learn as you make some games, it's reasonably straightforward.

  1. Calculate the direction AB which is (x=B.x-A.x, y=B.y-A.y)
  2. Normalize the AB you just calculated - that is, divide both coordinates by the length (so the length is 1). The length is sqrt(x*x y*y). If A and B are the same point, this is a divide by zero, which makes sense because there is no right answer, so figure out what you want to do if that happens.
  3. Rotate 90 degrees. The old -x is the new y, and the old y (not -y) is the new x. This is clockwise if X is right and Y is up. If Y is down then it's counter-clockwise. You can reverse the direction by changing which coordinate has a - sign in front of it.
  4. Multiply both x and y by how far away you want C to be from A (for example 20 units).
  5. Add back on point A's coordinates, that we subtracted in step 1. (x = A.x; y = A.y;)

Now you have the coordinates of point C.

In code that might look like this:

float x = B.x-A.x, y = B.y-A.y;
float length = sqrt(x*x   y*y);
if(length < 0.00001) {
    // just pick a direction
    C.x = A.x   20;
    C.y = A.y;
} else {
    x /= length; y /= length;
    swap(x, y); y = -y;
    x *= 20; y *= 20;
    C.x = A.x   x;
    C.y = A.y   y;
}

or if you have a vector class with all these functions:

vec2f v = B-A;
if(v.isZero())
    C = A   vec2f(20, 0); // just pick a direction
else
    C = A   v.normalize().rotate90()*20;
  •  Tags:  
  • c
  • Related