- Home /
Rotate a Vector Relative to Another Vector
I'm making a runner game which scrolls forward on the z-axis. When the player clicks on a target, a projectile called bolt is fired at the enemy position. I want to have a Spread powerup (similar to Spread seen in the old Contra games), where a second bolt is fired at an angle relative to the target vector.
The problem I am having is that the second bolt ends up firing almost a mirror image (flipped on the x-axis) from where the target is when I shoot to the right, and not accurately when I shoot to the left. How can I make this work properly? Here is my existing code, in the handler for the bolt object:
//Move bolt towards enemy
float time = 0.5f;
float t = 0f;
Vector3 startPos = Runner.runnerPosition;
Vector3 newPos = enemyScript.enemyPosition;
newPos.z += enemyScript.speed * time;
//***This line of code is not working as intended***
Vector3 spreadPos = Quaternion.AngleAxis(-5f, Vector3.up) * newPos;
switch (this.gameObject.tag)
{
case "FiredBolt":
while (t < 1.0f){
t += Time.deltaTime / time; // Sweeps from 0 to 1 in time seconds
if (bolt != null) {
bolt.position = Vector3.Lerp(startPos, newPos, t);
}
yield return 0;
}
Destroy(GameObject.FindGameObjectWithTag("FiredBolt"));
break;
case "SpreadBolt":
while (t < 1.0f) {
t += Time.deltaTime / time; // Sweeps from 0 to 1 in time seconds
if (bolt != null) {
bolt.position = Vector3.Lerp(startPos, spreadPos, t);
}
yield return 0;
}
Destroy(GameObject.FindGameObjectWithTag("SpreadBolt"));
break;
}
Answer by robertbu · May 03, 2013 at 04:32 AM
I think you are looking for something like this:
Vector3 spreadPos = startPos + Quaternion.AngleAxis(-5f, Vector3.up) * (newPos - startPos);
Your current code rotates the vector based on the world origin. In order to get the spread, you want to rotate it from the point the bolt is shot.
Your answer