- Home /
Reset local object to original forward direction after facing another direction
Hey,
I have a script that changes the forward direction of a bullet spawner object depending on whether the Player has locked onto an enemy. The conditions are simple;
If an enemy IS targeted - set forward direction of spawner towards enemy's position.
If an enemy IS NOT targeted face forward direction again - i.e. shoot ahead as normal.
The issue I'm having is that when the Player rotates away from his starting position (which points along the World Vector3.forward to begin with), the spawner continues to fire in that same direction.
If anyone can lend a hand that would be great. I seem to recall something about a 'Relative forward' calculation to find the forward direction of local objects (BTW, it's attached to the Player, as expected).
The relevant code is below - Thanks
// Access the ClosestEnemy script and check whether the we have an enemy targeted.
if (ClosestEnemyScript_ref.EnemyTargetted)
{
// Debug.Log("ENEMY TARGETTED");
// Calculate the relative position of the Player to the Enemy and store in bulletDirection (direction)
bulletDirectionR = (ClosestEnemyScript_ref.EnemyPosition - BulletSpawnerR_obj.transform.position).normalized;
}
// Otherwise, no enemy is target and so we just shoot forward
else
{
// Debug.Log("NO ENEMY TARGETTED");
// Hmmmm ??
bulletDirectionR = Vector3.forward;
}
BulletSpawnerR_obj.forward = bulletDirectionR;
}
Try to rotate the character to make the target be in the character front, so use Transform.TransformDirection(Vector3.forward) as location for instantiation. Before you make the target, just save the Transform.eulerAngles and use it for your reset.
transform.TransformDirection(Vector3.forward)
is the same as transform.forward
.
Answer by Wolfram · Feb 02, 2013 at 11:03 PM
Vector3.forward
will always be the +Z world axis. Use transform.forward
(or myObject.transform.forward
respectively) to find the local/"relative" forward axis of any rotated object.
Your answer
![](https://koobas.hobune.stream/wayback/20220613092017im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to add slight angle/rotation variation to transform.forward? 5 Answers
Change velocity direction 1 Answer
How to get a vector as if it were a local position to an object? 1 Answer
Fade shader based on heading angle to camera not working 1 Answer
modify mesh local direction... (defining two directions at once) 1 Answer