0
votes

I wish to launch my Arrow GameObject at an angle of 30˚ and a velocity of 30 m/s. In a script I add a rigidbody to this Arrow. However, I am also trying to launch this Arrow in the direction of the player (away from the enemy) in a 3D scene. I cannot figure out how to plug in these variables to get the Vector3 for the "arrowRigidbody.velocity"

//THE VARIABLES REFERENCED ABOVE APPEAR LIKE SO:
Rigidbody arrowRigidbody;
Transform playerTransform;
Transform enemyTransform;
float angle = 30f;
float velocity = 30f;

//How do I use these variables in order to shoot the projectile at a speed
//of 30 m/s and an angle of 30˚ in the direction of the player in 3D scene
arrowRigidbody.velocity = /*????*/;

Thank you for your time and patience :)

2

2 Answers

0
votes

Assuming you only shoot 'forward' you can use the simplified:

    var targetDirn = transform.forward;
    var elevationAxis = transform.right;

    var releaseAngle = 30f;
    var releaseSpeed = 30f;

    var releaseVector = Quaternion.AngleAxis(releaseAngle, elevationAxis) * targetDirn;
    arrowRigidbody.velocity = releaseVector * releaseSpeed;

If you need to shoot 'off-axis', you can replace the first two lines:

    var targetDirn = (target.transform.position - transform.position).normalized;
    var elevationAxis = Vector3.Cross(targetDirn, Vector3.up);
0
votes

Using some geometry, knowing that vector will have a magnitude (m) of 1, the y-component will be m/2 and the x-component will be m*(3^.5)/2. Which will make your final value:

arrowRigidbody.velocity = new Vector2(Mathf.Pow(3, .5f)/2, 1/2) * velocity;

For a changing angle, you know that the x component will be m * cos(angle) and the y component will be m * sin(angle), leaving you with:

float velx = velocity * Mathf.Cos(angle * Mathf.Deg2Rad);
float vely = velocity * Mathf.Sin(angle * Mathf.Deg2Rad);
arrowRigidbody.velocity = new Vector2(velx, vely);