I have a basic player object that is moving around the with mouse control and when clicked the left mouse button would cause the player to shoot objects/weapons (lasers, missiles, ect.). The main problem I am having is when I shoot the projectiles and the player is moving forward then the projectiles stack up.
I am trying to find away to prevent the stacking by adding the forward moving speed of the player to the base speed of the objects, thus stopping the stacking. I have tried several different methods to get this working and been through UnityAnswers thoroughly.
Here’s an idea that I think will work (or work with a bit of tweaking). It is untested.
Step 1: Get the velocity of your player. If it has a Rigidbody, then you can use Rigidbody.velocity. Same with character controller: CharacterController.velocity. If you are moving it through the transform, you’ll have to track the the distance changed each frame and divide it by deltaTime (or maybe a larger sample and time). I’ll call the player’s velocity ‘v3VPlayer’.
Step 2: Get the direction the weapon is going to fire. This will be the forward vector of the spawn point. Or it will be a vector you can calculate by: targetPos - playerPos. I’ll call this ‘v3VGun’.
Step 3: Compare the angle between the two. If it is greater than 90 degrees, don’t do anythings.
Step 4: Get the Dot product between the v3Gun and v3Player and assign that to the velocity of the projectile before you add force. A bit of untested example code:
if (Vector3.Angle(v3Gun, v3Player) < 90.0){
projectile.rigidbody.velocity = Vector3.Dot(v3Gun, v3Player);
}