[Solved]Shooting at the player

edited February 2012 in Help request
I just realized something important. If I want a bullet to fly in the general direction of the player, I can't just set its speed to the players position. (Although, it would be quite humorous if I did...)

Anyway, there has to be an equation I can use to figure out what the speed has to be set to in order to fire a bullet at the player, and maintain control of the speed of the bullet.

Also, what is angular velocity, and would it be used for this purpose?

Comments

  • edited February 2012
    Hi sonic,

    I have used unit vectors for this purpose in the past.

    Assume you have the player at vector coordinates (0, 0, 0) and the enemy at vector coordinates (10, 20, 0).

    You know the vector from the enemy to the player (the trajectory down which the bullet must be fired) is (-10, -20, 0). dX = -10, dY = -20, dZ = 0

    However, as you said, you wouldn't set the speed of the bullet to that vector :)

    Instead, you can calculate the unit vector, which is defined as a vector of length 1 in the same direction as the original vector.

    Calculate the unit vector of the vector (-10, -20, 0). Here is the formula. Just plug in your numbers instead (or see sample code below): http://maxwell.byu.edu/~spencerr/websumm122/node7.html

    Now you have a very small vector that points from the enemy to the player. You can multiply the components of this vector by an arbitrary quantity which is the speed of the bullet. This gives you the speed vector which you can apply to the bullet.

    Sample code:
    // Calculate unit vector for dX, dY
    orxFLOAT rdX = 0;
    orxFLOAT rdY = 0;
    float rprim = pow(dX, 2) + pow(dY, 2);
    
    if (rprim > 0) {
      orxFLOAT r = sqrt(rprim);
      rdX = dX / r;
      rdY = dY / r;
    }
    
    orxVECTOR speed = {0, 0, 0};
    
    // Adjust speed of the projectile by changing value of SPEED
    speed.fX = rdX * SPEED;
    speed.fY = rdY * SPEED;
    

    Where dX and dY are values representing the original vector between the source and target objects, and SPEED is a constant representing the desired speed of the projectile.

    Maybe there are others ways to do this for well, but this is a very easy method I have used successfully. I hope this helps you.
  • edited February 2012
    Hi,

    Just a little precision, orxVector.h define some usefull function to do that.

    To compute a unit vector (called normalized vector too), you can use orxVector_Normalize().

    To apply the speed to your normalized vector, you can use orxVector_Mulf().

    It's the same, but just already done in Orx ;)

    Cheers.
  • edited February 2012
    thanks guys!
Sign In or Register to comment.